[LeetCode] Divisible and Non-divisible Sums Difference

2894. Divisible and Non-divisible Sums Difference

You are given positive integers n and m.

Define two integers, num1 and num2, as follows:

  • num1: The sum of all integers in the range [1, n] that are not divisible by m.
  • num2: The sum of all integers in the range [1, n] that are divisible by m.

Return the integer num1 - num2.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int differenceOfSums(int n, int m) {
int num1 = 0, num2 = 0;
for(int i = 1; i <= n; i++) {
if(i % m == 0) num2 += i;
else num1 += i;
}
return num1 - num2;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/08/PS/LeetCode/divisible-and-non-divisible-sums-difference/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.