Question

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;
        }
    }
}
Was it helpful?

Solution

OK. I finally found the problem. It is the package statement. The program is accepted after removing it... A bit mistake for me when copy-paste code from my IDE to submission form.. But there are some interesting discussions here and thank everyone!

OTHER TIPS

The logic here will overflow the stack. It goes searching for the next number in the sequence before caching the result of the function on the current one.

    int result = search(j, cache) + 1;
    if (i <= n) {
        cache[(int)(i - 1)] = result;
    }
    return result;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top