Project Euler Solution 6
#
Problem StatementWhat 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.
#
SolutionLet 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:
Number | 1 |
Square(number) | 1 |
Sum(square) | 1 |
Sum(number) | 1 |
Iteration 2:
Number | 1 | 2 |
Square(number) | 1 | 4 |
Sum(square) | 1 | 5 |
Sum(number) | 1 | 3 |
Iteration 3:
Number | 1 | 2 | 3 |
Square(number) | 1 | 4 | 9 |
Sum(square) | 1 | 5 | 14 |
Sum(number) | 1 | 3 | 6 |
Iteration 4:
Number | 1 | 2 | 3 | 4 |
Square(number) | 1 | 4 | 9 | 16 |
Sum(square) | 1 | 5 | 14 | 30 |
Sum(number) | 1 | 3 | 6 | 10 |
Similarly it goes until 10. The final table looks like this
Number | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
Square(number) | 1 | 4 | 9 | 16 | 25 | 36 | 49 | 64 | 81 | 100 |
Sum(square) | 1 | 5 | 14 | 30 | 55 | 91 | 140 | 204 | 285 | 385 |
Sum(number) | 1 | 3 | 6 | 10 | 15 | 21 | 28 | 36 | 45 | 55 |
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;}