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

来源:互联网 发布:免费网站群发软件 编辑:程序博客网 时间:2024/06/14 07:50

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 timedef 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 1m,value=0,0begin=time.time()for i in range(1,1000000):    tmp=f(i)    if tmp>m:        value=i        m=tmpprint time.time()-beginprint m,value



0 0
原创粉丝点击