So here is my code for the 3n+1 problem on UVa. It runs perfectly on my PC in Eclipse AFAIK, however, I keep getting a runtime error against the UVa judge. Unfortunately, the judge does not tell me what inputs it uses, nor provide any information beyond "RuntimeException" when it fails. This is the same structure as the ACM's ICPC, for the curious.
I am pretty sure that the recursion shall not overflow the stack as the maximum cycle length of all numbers from 1 to 1000000 is only 525. Also, the cache of 1000000 integers shall be only 4Mb large.
package Collatz;
import java.util.Arrays;
import java.util.Scanner;
class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] cache = buildCache(1000000);
while (in.hasNextLine()) {
Scanner line = new Scanner(in.nextLine());
if (!line.hasNextInt()) continue;
int a = line.nextInt();
int b = line.nextInt();
int c = a;
int d = b;
if (c > d) {
int temp = c;
c = d;
d = temp;
}
int max = 0;
for (int i = c - 1; i <= d - 1; i++) {
max = Math.max(max, cache[i]);
}
System.out.format("%d %d %d\n", a, b, max);
line.close();
}
in.close();
}
public static int[] buildCache(int n) {
int[] cache = new int[n];
Arrays.fill(cache, 0);
cache[0] = 1;
for (int i = 1; i < n; i++) {
search(i + 1, cache);
}
return cache;
}
public static int search(long i, int[] cache) {
int n = cache.length;
if (i == 1) {
return 1;
} else if (i <= n && cache[(int)(i - 1)] > 0) {
return cache[(int)(i - 1)];
} else {
long j = (i % 2 == 1) ? (3 * i + 1) : (i / 2);
int result = search(j, cache) + 1;
if (i <= n) {
cache[(int)(i - 1)] = result;
}
return result;
}
}
}