006 - sum of squares less square of sums
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
See Problem 6.
There are several stupid, straightforward ways of doing this. The following is one:
upper_bound = 100
sum_squares = 0
for i in xrange (1, upper_bound+1):
sum_squares += i**2
square_sum = 0
for i in xrange (1, upper_bound+1):
square_sum += i
square_sum *= square_sum
print sum_squares - square_sum
Execution time: < 1ms. xrange is used to decrease memory usage, and upper_bound is defined to make the solution generalisable. The solution could be physically shorter by combining the two loops, which shaves around a quarter of execution time.
Alternatively, we can calculate the sum of the sum of the terms without looping: if a series ranges from l to h, the average value of series member is (l+h)/2 and the sum of the series is thus n(l+h)/2. Further, the sum of an integer series from 1 to n can be calculated as n(n+1)(2n+1)/6. Thus:
upper_bound = 100 sum_squares = upper_bound * (upper_bound+1)*(2*upper_bound+1) / 6 square_sum = upper_bound * (1.0 + upper_bound) / 2.0 square_sum *= square_sum print sum_squares - square_sum
which completes in half of the original. You could go even further and work out with a bit of algebra that the result should be -3n^4 - 2n^3 + 3n^2 + 2n.
