Problem Description
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 bym
.num2
: The sum of all integers in the range[1, n]
(both inclusive) that are divisible bym
.
Return the integer num1 - num2
.
Key Insights
- The range of integers from 1 to n can be easily iterated over, but there are mathematical formulas to sum consecutive integers efficiently.
- The sum of integers not divisible by
m
can be derived by subtracting the sum of integers that are divisible bym
from the total sum of integers from 1 to n. - Efficiently identifying the integers divisible by
m
can reduce the complexity of the solution.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
To solve this problem, we can utilize a simple loop to calculate both sums. We'll iterate through the integers from 1 to n and check if each integer is divisible by m. If it is, we add it to num2
; otherwise, we add it to num1
. Finally, we return the difference between num1
and num2
.
The algorithm follows these steps:
- Initialize
num1
andnum2
to 0. - Loop through each integer from 1 to n.
- Check if the integer is divisible by m.
- Update
num1
ornum2
accordingly. - Return
num1 - num2
.