10
25
2012
0

欧拉项目第14题,PyPy速度挺快的

代码很简单:

 

#!/usr/bin/env python

cache={}
def get_chain_len(n):
	l=0
	while True:
		if n in cache:
			l+=cache[n]
		if n<=1:
			l+=1
			break
		if not n%2: #even
			n=n/2
		else:
			n=3*n+1
		l+=1
	return l

def get_max_chain(i):
	max_l=1
	max_n=i
	while i>0:
		l=get_chain_len(i)
		#print i,l
		if l>max_l:
			max_l=l
			max_n=i
		i-=1
	return (max_n,max_l)
	
	
def main():
	print get_max_chain(1000000)
	
	
if __name__=='__main__':
	main()
	
		

使用pypy执行

 

cj@cj-pc:$ time pypy euler14.py
(837799, 525)
 
real    0m1.162s
user    0m1.148s
sys     0m0.012s
 
这速度比Racket要快了
 
 
超郁闷的,使用Haskell不知道在我的机器上运行得超慢,根本等不到结果
Category: 未分类 | Tags: PyPy Python | Read Count: 961

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com