You are on the Home/Other Tutorials/Project Euler/Problem 6 page
Google
Web This Site

Project Euler - Problem 6

More about Project Euler.

Problem description

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.

Solution

There is a way to get the result with just some calculations -- and I did not find it until after solving this problem with Excel.  I already knew that the sum of the numbers 1,2, ..., n is n(n+1)/2 but what I did not know is that the sum of 12,22,...,n2 is n(n+1)(2n+1)/6 -- see http://en.wikipedia.org/wiki/Square_pyramidal_number

This is also easy to do in Excel.  In 100 contiguous cells in some column (say A1:A100) enter the numbers 1, 2, ..., 100.  There are several ways to do this.  Enter 1 and 2 in A1 and A2 respectively.  Then, select A1:A2, click the right-bottom corner of the cell and drag down to A100.  Or, enter 1 in A1 and =A1+1 in A2.  Select A2.  Next, open the GoTo dialog box (short cut is CTRL+g), enter A100 as the destination and hold SHIFT while clicking OK.  Fill down the contents of A2 with CTRL+d  There are still other ways to get this series in Excel.

To get the sum of the squares, in B1 enter =A1^2.  If Excel doesn't automatically fill B2:B100 with the formula do so yourself.  In B101 enter the formula to sum the numbers above.

To get the square of the sums, sum the values in A1:A100 in A101 and in A102 enter the formula to square the result in A101.