Ruby代码:
t1 = Time.now.to_i min = Math.sqrt(1).to_i max = Math.sqrt(10**14).to_i def isH(num) return num.to_s == num.to_s.reverse end for num in (min..max) if isH num z = num**2 if isH z puts z end end end t2 = Time.now.to_i puts t2-t1python代码:
from time import time t1 = time() def isP(num): return str(num)==str(num)[::-1] def main(): m1 = int(1**0.5) m2 = int((10**14)**0.5) for i in range(m1,m2): if isP(i): t=i*i if isP(t): print t, main() print print time() - t1
ruby、python、pypy均系ubuntu12.04默认版本(拿不在统一发布时间的版本比有失公平)。
运行结果:
ruby:python:pypy = 12 : 6.72839808464 : 2.16342711449
(点击查看大图)
有个更快的python版本,代码:
import math import time def is_palindrome(num): str_num = str(num) if(str_num[0] == str_num[-1]): i_len = len(str_num)/2 for i in xrange(i_len): if(str_num[i] != str_num[-(i+1)]): return False return True if __name__ == '__main__': t = time.clock(); x = 1 y = 100000000000000 sqr_x = int(math.sqrt(x)) sqr_y = int(math.sqrt(y)) aa = [{x: x*x} for x in xrange(sqr_x, sqr_y) if is_palindrome(x) and is_palindrome(x*x)] print aa print time.clock() - t
renwofei@renwofei-Inspiron-560:~$ pypy slow.py
[{1: 1}, {2: 4}, {3: 9}, {11: 121}, {22: 484}, {101: 10201}, {111: 12321}, {121: 14641}, {202: 40804}, {212: 44944}, {1001: 1002001}, {1111: 1234321}, {2002: 4008004}, {10001: 100020001}, {10101: 102030201}, {10201: 104060401}, {11011: 121242121}, {11111: 123454321}, {11211: 125686521}, {20002: 400080004}, {20102: 404090404}, {100001: 10000200001}, {101101: 10221412201}, {110011: 12102420121}, {111111: 12345654321}, {200002: 40000800004}, {1000001: 1000002000001}, {1001001: 1002003002001}, {1002001: 1004006004001}, {1010101: 1020304030201}, {1011101: 1022325232201}, {1012101: 1024348434201}, {1100011: 1210024200121}, {1101011: 1212225222121}, {1102011: 1214428244121}, {1110111: 1232346432321}, {1111111: 1234567654321}, {2000002: 4000008000004}, {2001002: 4004009004004}]
1.020064