Skip to main content
Back to problems
#2894
Easy Algorithms

Divisible and non divisible sums difference

Math
91.0% acceptance
Feb 25, 2026
668
36
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 by m. num2: The sum of all integers in the range [1, n] (both inclusive) that are divisible by m. Return the integer num1 - num2.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn difference_of_sums(n: i32, m: i32) -> i32 {
    // num1 - num2 = (total_sum - num2) - num2 = total_sum - 2*num2
    let total = n * (n + 1) / 2;
    let k = n / m;
    let num2 = m * k * (k + 1) / 2;
    total - 2 * num2
  }
}