我正在研究一个欧拉问题,你必须得到最长的 collatz 链。问题是,你必须从 1 到 1 000 000 的序列中找到它。我的代码在 100 000 之前工作得很好,然后它会抛出StackOverFlowError
. 我可以避免它,还是我的代码是废话?
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);
}
}
}