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);
        }
    }
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Rok Dolinar
  • 976
  • 3
  • 13
  • 29

0 Answers0