0

I'm working on an eulers problem, where you have to get the longest collatz chain. The problem is, you have to find it in a sequence from 1 to 1 000 000. My code works great up to 100 000, then it throws StackOverFlowError. Can I avoid it, or is my code crap?

public class Collatz {
    private static final ArrayList<Integer> previous = new ArrayList<>();
    public static void main(String[] args) {

        for (int i = 1; i < 100000; i++){
            collatzLength(i, 1);
        }
        Integer i = Collections.max(previous);
        System.out.println(i);

    }

    public static void collatzLength(int n, int count){

        if (n == 1){
            previous.add(count);
        } else if (n%2 == 0){
             collatzLength(n/2, count+1);

        } else {
            collatzLength(3*n+1, count+1);
        }
    }
}
9
  • 1
    Eliminate recursion, or make the stack bigger. Sep 11, 2015 at 19:55
  • 1
    Or, use a stack object instead of a virtual memory stack Sep 11, 2015 at 19:56
  • Do not make your stack bigger. Eliminate recursion. Making the stack bigger is only fighting the symptoms of your bad code. Sep 11, 2015 at 20:03
  • But the iterative version will take 1 year to calculate? Sep 11, 2015 at 20:05
  • If you want to keep with the recursive method, use memoization to store the results of previous calculations, that will speed up the algorithm and lower the number of methods in the stack. Sep 11, 2015 at 20:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.