An interactive programming challenge that visualizes the difference between sums of numbers divisible and not divisible by a given value.
๐ฎ Interactive Challenge ๐ฎ
Play the Game
0
Total Sum (1 to n)
0
Sum of Divisibles
0
Sum of Non-Divisibles
0
Final Difference
๐งโ๐ป Code Implementation
classSolution {
public:
intdifferenceOfSums(int n, int m) {
std::vector<int> numbers(n);
std::iota(numbers.begin(), numbers.end(), 1);
returnstd::transform_reduce(numbers.begin(), numbers.end(), 0,
std::plus<int>{},
[m](int num) { return num % m == 0 ? -num : num; });
}
};
from functools import reduce
from operator import add
defdifference_of_sums(n, m):
"""Calculate difference using functional programming approach"""
numbers = list(range(1, n + 1))
transformed = map(lambda num: -num if num % m == 0else num, numbers)
returnreduce(add, transformed, 0)
# Alternative using sum() with generator expression:defdifference_of_sums_modern(n, m):
returnsum(-num if num % m == 0else num
for num inrange(1, n + 1))
functiondifferenceOfSums(n, m) {
const numbers = Array.from({length: n}, (_, i) => i + 1);
return numbers
.map(num => num % m === 0 ? -num : num)
.reduce((sum, val) => sum + val, 0);
}
// Modern ES6+ approach with chaining:constdifferenceOfSums = (n, m) =>
Array.from({length: n}, (_, i) => i + 1)
.reduce((sum, num) => sum + (num % m === 0 ? -num : num), 0);
// Using Array.keys() alternative:constdifferenceOfSumsKeys = (n, m) =>
[...Array(n).keys()]
.map(i => i + 1)
.reduce((sum, num) => sum + (num % m === 0 ? -num : num), 0);
import java.util.stream.IntStream;
public classSolution {
public intdifferenceOfSums(int n, int m) {
returnIntStream.rangeClosed(1, n)
.map(num -> num % m == 0 ? -num : num)
.sum();
}
// Alternative using reduce for more explicit control:public intdifferenceOfSumsReduce(int n, int m) {
returnIntStream.rangeClosed(1, n)
.reduce(0, (sum, num) ->
sum + (num % m == 0 ? -num : num));
}
// Using parallel stream for larger datasets:public intdifferenceOfSumsParallel(int n, int m) {
returnIntStream.rangeClosed(1, n)
.parallel()
.map(num -> num % m == 0 ? -num : num)
.sum();
}
}
๐ฏ How it works:
Goal: Calculate the difference between the sum of numbers NOT divisible by m and the sum of numbers divisible by m.
Algorithm: For each number from 1 to n, if it's divisible by m, subtract it from our answer. Otherwise, add it to our answer.
Math Formula: result = ฮฃ(non-divisible) - ฮฃ(divisible)