I calculated the total sum from 1 to n
using the formula n * (n + 1) // 2
. Then, I found how many numbers are divisible by m
(n // m
) and used the arithmetic series formula to get their sum. Finally, I subtracted the divisible sum from the total to get the difference between non-divisible and divisible sums.
class Solution:
def differenceOfSums(self, n: int, m: int) -> int:
total_sum = n * (n + 1) // 2
k = n // m
divisible_sum = m * k * (k + 1) // 2
return total_sum - 2 * divisible_sum
- Time: O(1)
- Space: O(1)
