Divisible and Non-divisible Sums Difference | LeetCode 2894

In this blog post, we will solve LeetCode Coding Problem “Divisible and Non-divisible Sums Difference”. We will solve this coding problem by brute force approach.

Problem Statement

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.

Constraints

1 <= n, m <= 1000

Example

Input: n = 10, m = 3

Output: 19

Explanation:

In the given example: –

  • Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37.
  • Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18.
  • We return 37 – 18 = 19 as the answer.

Solution

We will solve “Divisible and Non-divisible Sums Difference” coding problem by iterating through number in range [1, n]. For each number

  • If number is divisible by m, increase count of divisible number num1 by 1.
  • If number is not divisible by m, increase count of non-divisible number num2 by 1.

At the end of function return (num1 - num2) as answer.

C++ implementation of above solution is as follows

C++
class Solution {
public:
    int differenceOfSums(int n, int m) {
        int num1 = 0;
        int num2 = 0;

        for(int i=1; i<=n; i++) {
            if(i % m != 0) {
                num1 += i;
            }
            else {
                num2 += i;
            }
        }

        return (num1 - num2);
    }
};

Time Complexity

O(n)

Space Complexity

O(1) since we are not using any additional space.

Thanks for reading and have a nice day.