Click here to Skip to main content
15,885,669 members
Articles / Programming Languages / C#

Project Euler Problem #6

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
16 Aug 2011CPOL 16.5K   3   3
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)


Written By
Business Analyst
United States United States
Visit my blog, Aimless Technical Babble

Comments and Discussions

 
QuestionUsing formulas Pin
Eusebiu Marcu22-Aug-11 11:57
Eusebiu Marcu22-Aug-11 11:57 
1² + 2² + 3² + ... + (n-1)² + n² = n(n+1)(2n+1)/6
1 + 2 + 3 + ... + n = n(n+1)/2
(1 + 2 + 3 + ... + n)² = n²(n+1)²/4

Diff = n²(n+1)²/4 - n(n+1)(2n+1)/6 (which is O(1))
Eusebiu

AnswerRe: Using formulas Pin
Sten Hjelmqvist22-Aug-11 21:12
Sten Hjelmqvist22-Aug-11 21:12 
AnswerRe: Using formulas Pin
Florian.Witteler22-Aug-11 21:28
Florian.Witteler22-Aug-11 21:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.