05.29.08
Project Euler: Problem 6
These problems will show up according to “difficulty”, according to the Project Euler site. Difficulty, here, corresponds to number of people who have solved the problem. When a problem is solved by more people, it’s listed as an easier problem. Thus:
The sum of the squares of the first ten natural numbers is,
1² + 2² + … + 10² = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + … + 10)² = 55² = 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 solution:
n = 100 square_of_sum = (n*(n+1)/2)**2 sum_of_squares = n*(n+1)*(2*n+1)/6 diff = square_of_sum - sum_of_squares print 'sum of squares:', sum_of_squares print 'square of sum:', square_of_sum print 'difference:', diff
This is a second solution, the first was a brute-force looping through all the numbers to accumulate the sums. Then I got smart and remembered that there are formulae for these finite series; a quick google let me find them and write much better code.
