12,943,528 members (46,784 online)
Technical Blog
alternative version

Stats

13.4K views
3 bookmarked
Posted 16 Aug 2011

Project Euler Problem #6

, 16 Aug 2011 CPOL
 Rate this:
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:

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

Share

Visit my blog, Aimless Technical Babble

You may also be interested in...

 First Prev Next
 Using formulas Eusebiu Marcu22-Aug-11 11:57 Eusebiu Marcu 22-Aug-11 11:57
 Re: Using formulas Sten Hjelmqvist22-Aug-11 21:12 Sten Hjelmqvist 22-Aug-11 21:12
 Re: Using formulas Florian.Witteler22-Aug-11 21:28 Florian.Witteler 22-Aug-11 21:28
 Last Visit: 31-Dec-99 18:00     Last Update: 22-May-17 15:48 Refresh 1