From ProjectEuler.net:

`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

`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.`

I’m just going to say it: I really don’t get why this one is even here. It has to be the easiest of all the first six problems. I usually feel like each ProjectEuler problem is cleverly designed to teach some new concept or syntax, or reveal a flaw in earlier code – but I don’t see it with this one.

Anyhoo, I used just a single loop, in which I summed all the squares, and also kept track of the sum. After that, I just squared the sum, subtracted, and there you are.

C++ Output

C++ code:

#include <iostream>
using namespace std;
int main()
{
long sumOfSquares = 0;
long sum = 0;
long squareOfSums = 0;
for (int i = 1; i < 101; i++){sumOfSquares += i*i; sum += i;}
squareOfSums = sum*sum;
cout << endl << "The difference between the sum of the squares and the square of the sums of the first 100 natural numbers is: " << abs(squareOfSums-sumOfSquares) << "." << endl;
return 0;
}

Python:

import math
sumOfSquares = 0
sumz = 0
squareOfSumz = 0
for i in range(1, 101):
sumOfSquares += i*i
sumz += i
print "The difference between the sum of the squares and the square of the sums of the first 100 natural numbers is: " + str(abs(sumOfSquares-(sumz*sumz))) + "."

### Like this:

Like Loading...

*Related*

dnn

said:You can write a program that computes this difference without using for loops. Hint: the sum of the first n integers is n(n+1)/2 and the sum of the squared first n integers is (n+1)(2n+1)/6. This also makes it so you can solve it by hand, freeing you from tediously computing these sequences in an iterative fashion.