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
本文介绍了一个数学问题的编程解法——寻找小于一百万的正整数中,根据特定规则生成的Collatz序列最长的起始数。通过递归函数计算序列长度,并使用循环结构找出目标数字。
248

被折叠的 条评论
为什么被折叠?



