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 → 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.

最长的科拉茨序列

问题 14

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

n→n/2 (n 偶数)
n→ 3n + 1 (n 正数)

使用以上的规则并从 13 开始, 我们得出以下序列:

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

我们看到131总共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);
    }
}