jeudi 27 septembre 2012

Euler #125

The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 62 + 72 + 82 + 92 + 102 + 112 + 122...
#!/usr/bin/env python
from math import sqrt, floor
N = 100000000
def is_palindrome(n):
return str(n) == str(n)[::-1]
def sum_list(n):
res = set()
for i in xrange(n - 1, 0, -1):
l = [x*x for x in xrange(i, n + 1)]
t = sum(l)
if t > N:
break
if is_palindrome(t):
res.add(t)
return list(res)
if __name__ == '__main__':
t = int(sqrt(N/2)) + 1
l = [item for sublist in map(sum_list, xrange(2, t + 1)) for item in sublist]
print len(set(l)), sum(set(l))
view raw euler125.py hosted with ❤ by GitHub

Aucun commentaire:

Enregistrer un commentaire