projecteuler---->problem=14----Longest Collatz sequence

title:

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.

翻译:

以下的循环数列是由正整数依据以下规则构成的:

nn/2 (若n是偶数)

n → 3n + 1 (若n是奇数)

若数列从13開始,就生成了例如以下数列:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

显然以上数列有10个数字,尽管未经证明(著名的Collatz猜想),但我们觉得不管由什么数字開始。数列都会在1处结束。故数列一旦产生了1这一项,就觉得数列结束。

这次的问题是:依据以上规则。由100万下面的哪个数字開始。能够产生最长的数列?

请注意:产生的数列可能会包括数字超过100万的项。

import time
def f(n):
    if n%2==1 and n>1:
       return f(3*n+1)+1
    elif n%2==0:
       return f(n/2)+1
    return 1
m,value=0,0
begin=time.time()
for i in range(1,1000000):
    tmp=f(i)
    if tmp>m:
        value=i
        m=tmp
print time.time()-begin
print m,value



版权声明:本文博客原创文章。博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/yxwkf/p/4617697.html