Project Euler 6: Square of Sums Minus Sum of Squares
The sum of the squares of the first ten natural numbers is,
12 + 22 + … + 102 = 385The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)2 = 552 = 3025Hence 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.
Using the brute-force method, this problem is very straight-forward to solve:
1 2 3 4 5 | for ( my $n = 1; $n <= 100; $n++ ) { $s1 += $n*$n; $s2 += $n; } print ( $s2 * $s2 - $s1 ); |
The first line initiates the loop. It will be run from 1 to 100, i.e. the first one hundred natural numbers. The second line accumulates the sum of the squares, one by one, while the third line just keeps track of the sum of the integers. After the loop, the difference between the sum squared and the squars summed is printed. The script runs in less than a second.
