问题
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);
}
}
}
来源:https://stackoverflow.com/questions/32531130/how-to-avoid-stackoverflow-at-collatz-for-high-values