Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Project Euler Problem #6

, 16 Aug 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

License

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

Share

About the Author

Jared Wallace
Business Analyst
United States United States
Visit my blog, Aimless Technical Babble

Comments and Discussions

 
QuestionUsing formulas PinmemberEusebiu Marcu22-Aug-11 12:57 
AnswerRe: Using formulas PinmemberSten Hjelmqvist22-Aug-11 22:12 
AnswerRe: Using formulas PinmemberFlorian.Witteler22-Aug-11 22:28 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411022.1 | Last Updated 16 Aug 2011
Article Copyright 2011 by Jared Wallace
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid