How to avoid stackoverflow at collatz for high values?

本小妞迷上赌 提交于 2019-12-12 03:38:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!