Problema:
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.
Meu codigo pra resolver ficou assim:
public class p14 {
public static void main(String[]args){
int num, tam=1, resp = 0,tamAnt = 0;
for(int i=999999;i>=0;i--){ //i é o maior numero a ser calculado
num=i;
//System.out.print(num);
do{
if(isPar(num)){
num/=2;
tam++;
}else{
num=(num*3)+1;
tam++;
}
//System.out.print(" - "+num);
}while(num>1);
//System.out.println(" tam:"+tam);
if(tam>tamAnt){
resp=i;
tamAnt=tam;
}
tam=1;
}
System.out.println("\ninicial da maior cadeia: "+resp+" de tamanho "+tamAnt);
}
static boolean isPar(int n){
String s = String.valueOf(n);
if(Integer.parseInt(s.substring(s.length()-1))%2==0) return true;
return false;
}
}
Saída:
run-single:inicial da maior cadeia: 910107 de tamanho 476
CONSTRUÍDO COM SUCESSO (tempo total: 24 segundos)
Mesmo assim ta errado!
Alguem me ajuda.