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.
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 <= n, m <= 1000
Input: n = 10, m = 3
Output: 19
Explanation:
In the given example: –
We will solve “Divisible and Non-divisible Sums Difference” coding problem by iterating through number in range [1, n]. For each number
num1
by 1.num2
by 1. At the end of function return (num1 - num2)
as answer.
C++ implementation of above solution is as follows
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);
}
};
O(n)
O(1)
since we are not using any additional space.
Thanks for reading and have a nice day.