2008年(47)
分类:
2008-11-12 15:27:21
The following iterative sequence is defined for the set of positive integers:
n n/2 (n is even)
n 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
求出每一个数字的生成的长度即可,用一个数组保存已经计算出的结果加快运算
a14 = {}
a14[1] = 1
def getA14(i):
if a.has_key(i):
return a[i]
else:
if i%2 == 0:
a[i] = 1+getA14(i/2)
else:
a[i] = 1+getA14(3*i+1)
return a[i]
def fun14():
global a14
chain = 0
num = 0
for start in range(1, 1000000):
if getA14(start) > chain:
chain = getA14(start)
num = start
return num, chain
answer is 837799, 长度为525
time:4.46900010109