I wrote a java program that finds the length of the chain of a number using the collatz sequence. The collatz sequence goes: if the number is even, divide it by two, if odd, multiply by 3 and add one. The sequence ends when the number reaches 1. Additional Info on Collatz Sequence. My program finds the chain length of the numbers from 1 to 1 million, but it stops at 113382. No error message is displayed, the program just stops printing out numbers.
*edit: I have tested it, and it turns out that when the program is on 113383, the chain converges to negative values. Can anyone explain this?
I have included the full code, as it is very short.
public static void main(String[] args) {
int max =0, maxChain=0;
for(int i = 2; i <1000000; i++ )
{
int c =i;
int counter = 0;
while(c != 1)
{
if(c%2 ==0) c/=2;
else c= 3*c+1;
counter++;
}
if(counter > maxChain)
{
maxChain =counter;
max = i;
}
System.out.println(i);
}
System.out.println(max +" has a chain length of " +maxChain);
}