It took less than a minute to complete puzzle number 6 from
Project Euler:
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.
This simply required working up from 1 to 100 and keeping a sum and a sum of their squares. Finally, I squared the sum and substracted the summed squares:
<?
/******************************************************************
* ProjectEuler.net * Problem 6 * 2010-05-31 * Martin Caine *
******************************************************************/
$totalSum = 0;
$totalSquares = 0;
for( $i=1; $i<101; $i++ )
{
$totalSum += $i;
$totalSquares += ($i*$i);
}
$totalSum *= $totalSum;
echo $totalSum-$totalSquares;
?>
If you found this post helpful please leave a comment below: