Project Euler Problem 6: Sum Square Difference

The Problem

The sum of the squares of the first ten natural numbers is:

1^2 + 2^2 + ... + 10^2 = 385

The square of the sum of the first ten natural numbers is:

(1 + 2 + ... + 10)^2 = 55^2 = 3025

The difference is 3025 - 385 = 2640. Find the same difference but for the first 100 natural numbers.

The Approach

This one is pretty straightforward once you break it into two separate things to compute:

  1. Sum of squares: square each number first, then add them all up
  2. Square of sums: add all the numbers up first, then square the total

These are two different loops, each with their own accumulator. After both loops finish, you just subtract one from the other.

The Code

#include <iostream>
#include <numeric>
#include <cmath>

int main() {
    int sum1, sum2, result;
    int accumulator1 = 0;
    int accumulator2 = 0;
 
    for (int i = 1; i <= 100; i++) // sum of squares
    {
        accumulator1 += std::pow(i, 2);
        sum1 = accumulator1;
    }
 
    for (int i = 1; i <= 100; i++) // square of sums
    {
        accumulator2 += i;
        if (i == 100)
        {
            sum2 = accumulator2 * accumulator2;
        }
    }
 
    result = sum2 - sum1;
    std::cout << result;
    return 0;
}

The first loop uses std::pow(i, 2) from <cmath> to square each number before adding it to accumulator1. By the end of the loop, sum1 holds the sum of squares.

The second loop just accumulates all numbers from 1 to 100 into accumulator2. Once the loop finishes at i = 100=, the full sum is ready, and squaring it at that point gives sum2.

Finally, sum2 - sum1 gives the answer.

What I Learned

The key insight here is just reading the problem carefully. “Sum of squares” and “square of sums” sound similar but are computed in a completely different order, and that order matters a lot. The difference between them turns out to be surprisingly large, which is part of what makes the problem interesting.

It is also a good reminder that accumulators need to live outside their loops, otherwise they reset every iteration and you just end up with the last value instead of the running total.