Problem Description
Given two positive integers n and m, calculate the difference between the sum of all integers between 1 and n that are not divisible by m (num1) and the sum of all integers that are divisible by m (num2). The answer is num1 - num2.
Key Insights
- Recognize that the total sum of numbers from 1 to n can be computed with the formula: totalSum = n * (n + 1) / 2.
- Compute the sum of multiples of m in the range [1, n] without iterating by finding the number of multiples p = n // m, then using the formula: num2 = m * p * (p + 1) / 2.
- The sum of non-multiples is then: num1 = totalSum - num2.
- Finally, the result is simply num1 - num2.
Space and Time Complexity
Time Complexity: O(1) – We compute sums directly using arithmetic formulas. Space Complexity: O(1) – Only a constant amount of extra space is used.
Solution
We leverage mathematical formulas to compute the sum quickly. First, compute the total sum of numbers from 1 to n. Then, calculate how many numbers in this range are multiples of m using integer division. With that count, derive the sum of multiples (num2) using the formula for the sum of the first 'p' natural numbers, multiplied by m. Lastly, subtract num2 from the total sum to get the sum of non-multiples (num1) and compute the final result by subtracting num2 from num1. This approach avoids an explicit iteration over the range, achieving a constant time solution.