Number Difference

Irvi Aini · May 28, 2025 · 8 min read

🎮 Number Difference Game 🎮

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

🧑‍💻 Code Implementation

class Solution {
public:
    int differenceOfSums(int n, int m) {
        std::vector<int> numbers(n);
        std::iota(numbers.begin(), numbers.end(), 1);
        
        return std::transform_reduce(numbers.begin(), numbers.end(), 0, 
            std::plus<int>{},
            [m](int num) { return num % m == 0 ? -num : num; });
    }
};

🎯 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)

Twitter, Facebook

Enjoyed this?

I write about technology, open source, and being human. Subscribe to get new posts in your inbox.

Subscribe on Substack