2894. Divisible and Non-divisible Sums Difference
Intuition
The problem requires us to find the difference between two sums:
- Sum of numbers from 1 to n that are NOT divisible by m
- Sum of numbers from 1 to n that are divisible by m
We can solve this by iterating through numbers 1 to n and checking if each number is divisible by m using the modulo operator.
Approach
- Initialize two variables:
nd
for sum of non-divisible numbersd
for sum of divisible numbers
- Iterate through numbers from 1 to n
- For each number i:
- If i is divisible by m (i % m == 0), add it to d
- If i is not divisible by m, add it to nd
- Return the difference (nd - d)
Complexity
- Time complexity: O(n)
- Space complexity: O(1)
Keywords
- Math
- Modulo Operation