Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Project Euler Problem #6

4.00/5 (1 vote)
16 Aug 2011CPOL 16.8K  
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Time for Problem 6. (Don't worry. This one is fairly simple.)

The sum of the squares of the first ten natural numbers is, 
12 + 22 + ... + 102 = 385 

The square of the sum of the first ten natural numbers is, 
(1 + 2 + ... + 10)2 = 552 = 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.

To me, this one screams brute force. In fact, I think it would be insulted if I executed any more brain power to develop a non-brute force method. So brute force it is.

First we need to find the sum of the squares for 1-100. We can do this using enumerables and lambda expressions and have it all in one handy dandy line of code:

C#
var sumOfSquares = (long)Enumerable.Range(1, 100).Sum(i => Math.Pow(i, 2));

All this does is generate an enumeration of all numbers from 1 to 100 and sum each square.

Now for the square of the sum:

C#
var squareOfSum  = (long)Math.Pow(Enumerable.Range(1, 100).Sum(), 2);

This is very similar to the previous, but we just grab the square of the sum of the number enumeration. That's it.

Now we can combine it all and retrieve our final answer:

C#
var sumOfSquares = (long)Enumerable.Range(1, 100).Sum(i => Math.Pow(i, 2));
var squareOfSum = (long)Math.Pow(Enumerable.Range(1, 100).Sum(), 2);
return squareOfSum - sumOfSquares;

And now we have our difference between the sum of squares and the square of the sum! Awesome.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)