Skip to content

2894. Divisible and Non-divisible Sums Difference 👍

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int differenceOfSums(int n, int m) {
    const int sum = (1 + n) * n / 2;
    const int num2 = getDivisibleSum(n, m);
    const int num1 = sum - num2;
    return num1 - num2;
  }

 private:
  // Returns the sum of all the integers in [1, n] that are divisible by m.
  int getDivisibleSum(int n, int m) {
    const int last = n / m * m;
    if (last == 0)
      return 0;
    const int first = m;
    const int count = (last - first) / m + 1;
    return (first + last) * count / 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int differenceOfSums(int n, int m) {
    final int sum = (1 + n) * n / 2;
    final int num2 = getDivisibleSum(n, m);
    final int num1 = sum - num2;
    return num1 - num2;
  }

  // Returns the sum of all the integers in [1, n] that are divisible by m.
  private int getDivisibleSum(int n, int m) {
    final int last = n / m * m;
    if (last == 0)
      return 0;
    final int first = m;
    final int count = (last - first) / m + 1;
    return (first + last) * count / 2;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def differenceOfSums(self, n: int, m: int) -> int:
    summ = (1 + n) * n // 2
    num2 = self._getDivisibleSum(n, m)
    num1 = summ - num2
    return num1 - num2

  def _getDivisibleSum(self, n: int, m: int) -> int:
    """Returns the sum of all the integers in [1, n] that are divisible by m."""
    last = n // m * m
    if last == 0:
      return 0
    first = m
    count = (last - first) // m + 1
    return (first + last) * count // 2