您的位置:首页 > 其它

我的欧拉工程之路_14

2014-04-07 17:30 225 查看

Longest Collatz sequence

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

1It 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.

最长的科拉茨序列

问题 14

定义一个运算,对一个正整数n有以下规则:
n

n/2 (n 偶数)
n

3n + 1 (n 正数)使用以上的规则并从 13 开始, 我们得出以下序列:
13

40

20

10

5

16

8

4

2

1我们看到,从13到1,总共有10个数字,尽管还没证明。但是一般都认为所有的数字最终都会得到1。
从哪个小于100万的正整数开始,可以获得最长的序列呢?
提示: 一旦序列开始序列中元素的值允许突破100万.
public class Euler14
{
public static void main(String[] args)
{
int chain=0,num=110000,maxNum=0;
for(;num<1000000;num++)
{
long numTemp=num;
int chainTemp=1;
while(numTemp!=1)
{
if(numTemp%2==0)
numTemp/=2;
else
numTemp=3*numTemp+1;
chainTemp++;
}
if(chainTemp>chain)
{
chain=chainTemp;
maxNum=num;
}
}
System.out.println("maxNum="+maxNum+" chain="+chain);
}
}


本文出自 “迁客的小屋” 博客,请务必保留此出处http://qianke.blog.51cto.com/5616176/1391692
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: