题目14:找出以100万以下的数字开始的最长序列。
n n/2 (当n是偶数时)
n 3n + 1 (当n是奇数时)
应用以上规则,并且以数字13开始,我们得到以下序列:
13
40
20
10
5
16
8
4
2
1
可以看出这个以13开始以1结束的序列包含10个项。虽然还没有被证明(Collatz问题),但是人们认为在这个规则下,以任何数字开始都会以1结束。
以哪个不超过100万的数字开始,能给得到最长的序列?
注意: 一旦序列开始之后,也就是从第二项开始,项是可以超过100万的。
注意: 一旦序列开始之后,也就是从第二项开始,项是可以超过100万的。
问题解决方案:
public class num14 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int i,max=1;
double j=0;
double p=0;
int[] count=new int[1000000];
for(i=0;i<1000000;i++){
for(j=i+1;;){
if(j%2==0){
j=j/2;
count[i]++;
}else{
j=3*j+1;
count[i]++;
}
if(j==1.0)
break;
}
if(count[i]>max){
max=count[i];
p=i+1;
}
}
System.out.println(p);
}
//答案:837799
}
问题答案:837799