The following iterative sequence is defined for the set of positive integers:
nn/2 (n is even)
n 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
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.
定义一个运算,对一个正整数n有以下规则:
nn/2 (n 偶数)
n 3n + 1 (n 正数)
使用以上的规则并从 13 开始, 我们得出以下序列:
我们看到,从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
原文:http://qianke.blog.51cto.com/5616176/1391692