Everyday has one random leetcode quiz. Today’s quiz is 2894. Divisible and Non-divisible Sums Difference
Description:
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 bym.num2: The sum of all integers in the range[1, n](both inclusive) that are divisible bym.
Return the integer num1 - num2.
Get Jimmy’s stories in your inbox
Join Medium for free to get updates from this writer.
Example 1:
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.Example 2:
Input: n = 5, m = 6
Output: 15
Explanation: In the given example:
- Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15.
- Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0.
We return 15 - 0 = 15 as the answer.Example 3:
Input: n = 5, m = 1
Output: -15
Explanation: In the given example:
- Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0.
- Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15.
We return 0 - 15 = -15 as the answer.For each number from 1 to n, if it is divisible by m, subtract it from ans; otherwise, add it.
At the end, return ans as answer.
The time complexity is O(n)
/**
* @param {number} n
* @param {number} m
* @return {number}
*/
var differenceOfSums = function (n, m) {
let ans = 0
for (let i = 1; i <= n; i++) {
if (i % m === 0) {
ans -= i
} else {
ans += i
}
}
return ans
};



![Python DSA Coding Interview Series:11/29 [Linked Lists]](https://miro.medium.com/v2/resize:fit:1358/format:webp/1*RpzhG5-m6tzjX-E1XdLsWA.png)

