Skip to main content

Project Euler Solution 6

Problem Statement#

What is the difference between the sum of squares and squares of the sum?

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

1² + 2² + ... + 10² = 385

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

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

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025-385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Solution#

Let us consider, difference between the sum of squares and squares of the sum of first 10 natural numbers.

The following tables show what happens during each iteration (see the for loop in the program).

Iteration 1:

Number1
Square(number)1
Sum(square)1
Sum(number)1

Iteration 2:

Number12
Square(number)14
Sum(square)15
Sum(number)13

Iteration 3:

Number123
Square(number)149
Sum(square)1514
Sum(number)136

Iteration 4:

Number1234
Square(number)14916
Sum(square)151430
Sum(number)13610

Similarly it goes until 10. The final table looks like this

Number12345678910
Square(number)149162536496481100
Sum(square)1514305591140204285385
Sum(number)13610152128364555

From the table,

Sum of the squares will be 385

Sum of the numbers will be 55

So, squares of the sum will be (55)² = 3025

Difference = 3025 - 385 = 2640.

Implementation#

#include <iostream>
using namespace std;
int MAX = 100;
int main(){    int i, square_sum, sum_square, sum, square, difference;    sum_square = 0;    sum = 0;    for (i = 1; i <= MAX; i++)    {        square = i * i;        sum_square = sum_square + square;        sum = sum + i;    }    square_sum = sum * sum;    difference = square_sum - sum_square;    cout << difference;    return 0;}

Sample Output#

Sample Output