- import math, time
- X = 1
- Y = 0xffffffffffffffff # 64 bits
- palindromes = []
- def isPalindrome(n):
- s = str(n)
- return s == s[::-1]
- def genPalindrome(n):
- s_ = str(n) # 123
- _s = s_[::-1] # 321
- # 123 -> 12321
- p = int(s_ + _s[1:]) # 12321
- pp = p * p # 12321 * 12321
- if pp > Y:
- return False
- if pp >= X and isPalindrome(pp):
- palindromes.append(p)
- # 123 -> 123321
- p = int(s_ + _s) # 123321
- pp = p * p # 123321 * 123321
- if pp >= X and pp <= Y and isPalindrome(pp):
- palindromes.append(p)
- return True
- def getStart(n):
- s = str(int(math.sqrt(n)))
- l = len(s)
- return int(s[:l/2+l%2]) # 1 -> 1, 12 -> 1, 123 -> 12, 1234 -> 12
- st = time.time()
- i = getStart(X)
- while genPalindrome(i):
- i += 1
- palindromes.sort()
- for p in palindromes:
- print '%d(%d)' % (p * p, p)
- print time.time() - st
- #该片段来自于http://www.codesnippet.cn/detail/170920135952.html
来源: http://www.codesnippet.cn/detail/170920135952.html