Tuesday, August 16, 2011

Project Euler Problem #6


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 lamda expressions and have it all in one handy dandy line of code:

 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:

 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:

 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.

No comments:

Post a Comment