#2894

Divisible and Non-divisible Sums Difference

Easy
MathArithmetic ProgressionMathematical Formulas
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

Instead of iterating through each number, we can use the formula for the sum of the first n integers and the properties of arithmetic sequences to calculate the sums directly. This approach is much faster and more efficient.

⚙️

Algorithm

5 steps
  1. 1Step 1: Calculate the total sum of integers from 1 to n using the formula n * (n + 1) / 2.
  2. 2Step 2: Calculate the number of multiples of m in the range [1, n] as k = n // m.
  3. 3Step 3: Calculate the sum of multiples of m using the formula m * (k * (k + 1)) / 2.
  4. 4Step 4: Calculate num1 as total_sum - num2, where total_sum is the sum from Step 1 and num2 is the sum from Step 3.
  5. 5Step 5: Return the difference num1 - num2.
solution.py6 lines
1def divisible_and_non_divisible_sum_difference(n, m):
2    total_sum = n * (n + 1) // 2
3    k = n // m
4    num2 = m * (k * (k + 1)) // 2
5    num1 = total_sum - num2
6    return num1 - num2

Complexity note: The time complexity is O(1) because we perform a constant number of arithmetic operations regardless of the size of n. The space complexity is O(1) since we only use a fixed amount of extra space.

  • 1Using arithmetic properties can significantly reduce computation time.
  • 2Understanding the relationship between divisibility and sums helps in optimizing solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.