I want to apply the Collatz Sequence and apply it to all numbers from 1 to 10^6, and return the number with the largest chain needed to reach 1. However, I have the problem that my loops dont seem to terminate in Eclipse and I can't figure out why, I can't even get all my prints shown in the console despite wanting it out every step.
The collatz sequence is is computed by the following rules:
if n is odd, the next number is n/2
if n is even, the next number is 3n + 1
This is what I have so far:
public static long collatz() {
long res = 0;
long n = 1;
long count = 0;
long largestCount = 0;
long t = 0;
for (long k = 1; k <= 20; k++) {
n = k;
while (n != 1) {
if ((n % 2) == 0) {
n = n / 2;
count = count + 1;
}
else {
n = (3 * n) + 1;
count = count + 1;
}
if (count > largestCount) {
largestCount = count;
res = k;
}
}
}
System.out.println(res);
return res;
}