Problem 14
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:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
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.
# n → n/2 (若n为偶数)n → 3n + 1 (若n为奇数),最终都会变成 1
# 从小于一百万的哪个数开始,能够生成最长的序列呢?
def collatz_length(n,length):
if n == 1:
return length+1
if n % 2 == 0:
length += 1
return collatz_length(int(n/2),length)
else:
length += 1
return collatz_length(3*n+1,length)
def longest_chain(n):
length = 1
longest = 0
number = 0
i = 1
while i <= n:
temp = collatz_length(i,length)
if temp > longest:
longest = temp
number = i
i += 1
return longest,number
print(longest_chain(1000000))
结果:837799 , 序列长度526,运行时间40s