LeetCode 2894: Divisible and Non-divisible Sums Difference

Math

Problem Description

Explanation:

To solve this problem, we need to calculate two sums: the sum of numbers in the range [1, n] that are not divisible by m (num1) and the sum of numbers in the same range that are divisible by m (num2). The required answer is num1 - num2.

  1. Calculate num1:

    • For each number i in the range [1, n], if i is not divisible by m, add i to num1.
  2. Calculate num2:

    • Calculate the count of numbers in the range [1, n] that are divisible by m using the formula count = n / m.
    • The sum of all numbers divisible by m in the range [1, n] is m * count, where count is the number of multiples of m in the range [1, n].
  3. Return the difference num1 - num2.

Time Complexity:

The time complexity of this solution is O(1) because we are performing a constant number of operations regardless of the input size.

Space Complexity:

The space complexity of this solution is O(1) as we are using a constant amount of extra space.

:

Solutions

class Solution {
    public int subtractNonDivisible(int n, int m) {
        int num1 = 0;
        
        // Calculate num1
        for (int i = 1; i <= n; i++) {
            if (i % m != 0) {
                num1 += i;
            }
        }
        
        // Calculate num2
        int count = n / m;
        int num2 = m * count;
        
        return num1 - num2;
    }
}

Loading editor...