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

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

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/117677.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号