Divisible and Non-divisible Sums Difference — LeetCode 2894 Python Solution
- Problem
- #2894
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given positive integers n and m. Define two integers as follows: num1: The sum of all integers in the range [1, n] (both inclusive) that are not divisible by m.
Example
- Input
- n = 10, m = 3
- Output
- 19
- Explanation
- In the given example:
Python solution
class Solution:
def differenceOfSums(self, n: int, m: int) -> int:
return sum(i if i % m else -i for i in range(1, n + 1))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the given integer |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2894. Divisible and Non-divisible Sums Difference is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2894. Divisible and Non-divisible Sums Difference?
- LeetCode 2894. Divisible and Non-divisible Sums Difference is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2894. Divisible and Non-divisible Sums Difference?
- The Python solution on this page runs in O(n), where n is the given integer.
- What is the space complexity of LeetCode 2894. Divisible and Non-divisible Sums Difference?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2894. Divisible and Non-divisible Sums Difference cover?
- LeetCode 2894. Divisible and Non-divisible Sums Difference is tagged Math on LeetCode.