2012-11-14

Project Euler - Problem 6


Here's my solution to Project Euler problem 6:

# where the numbers list ends
n = 100

# handy function to square a number
pow2 = lambda x: pow(x, 2)

# first compute the sum of the squares
sumsq = sum(map(pow2, range(1, n+1)))
# then the square of the sum
sqsum = pow2(sum(range(1, n+1)))

print sqsum - sumsq

4 comments:

Marius Gedminas said...

Why pow(x, 2) instead of x ** 2 or x * x?

Sandro Tosi said...

@Marius: no real reason, I wanted to use map() :)

Anonymous said...

2 * sum([i*j for i in range(1, 101) for j in range(i+1, 101)]

untested, however the idea is that the difference contains each product of two integers exactly twice.

the benefit of this method is that intermediate results are not greater that the final result (hence there is no risk of overflow)

Even better, using some classic math results:
1+2...+n = n * (n+1)/2
1²+2²+...+n² = n*(n+1)*(2n+1)/6

do the difference and you'ĺl find:
n(n+1)(n-1)(3n+2)/12

Sandro Tosi said...

@mpomme: that's what you get for working in the industry for such a long time: you forget the basic math - the series expansion solution is much better than doing all the calculation & summing