Problem 6:

*The sum of the squares of the first ten natural numbers is,*

1^{2} + 2^{2} + … + 10^{2} = 385

*The square of the sum of the first ten natural numbers is,*

(1 + 2 + … + 10)^{2} = 55^{2} = 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.*

A nice easy one this time. Basically we want to loop from 1 to 100. Use two variables. Sum1 = a sum of the values of 1-100 squared. Sum2 = a sum of the values of 1-100 (not squared). At the end of the loop, square Sum2. Subtract Sum1 from Sum2.

<cfset sum1 = 0>
<cfset sum2 = 0>
<cfloop index="i" from="1" to="100">
<cfset sum1 = sum1 + (i * i)>
<cfset sum2 = sum2 + i>
</cfloop>
<cfset sum2 = sum2 * sum2>
<cfset difference = sum2 - sum1>
<cfoutput>
sum1: #sum1#<br>
sum2: #sum2#<br>
difference: #difference#<br>
</cfoutput>

The only thing to watch out for is where it asks for “*the difference*“. I just did a straight subtraction. However, in other problems where it might be harder to guess which of two values would be greater, this should probably be wrapped in the Abs() function, to prevent a negative value being returned.

### Like this:

Like Loading...

*Related*

You could use the formula

1+2+..+N = (1/2)N(N+1)

1^2+2^2+…+N^2 = (1/6)N(N+1)(2N+1)

?

Comment by Jax — December 25, 2009 @ 2:23 am |

opps just noticed this is very old =) It was a ‘related post’ suggested on my own blog you see

Comment by Jax — December 25, 2009 @ 2:23 am |

[…] previously blogged about this Project Euler puzzle 6 years ago, using ColdFusion. This is my approach using PHP as a simple practical exercise for myself, and […]

Pingback by Project Euler: problem 6 (PHP) | Duncan's blog — September 24, 2014 @ 8:07 am |