【问题标题】:Can anybody explain to me why I am getting Stack Overflow Error?谁能向我解释为什么我会收到 Stack Overflow 错误?
【发布时间】:2014-01-09 17:57:12
【问题描述】:

我正在尝试完成Project Euler question 并尝试执行递归解决方案,但我收到堆栈溢出错误并且似乎无法弄清楚原因。

任何帮助都会很棒。

谢谢

public class Collatz {

public static void main(String[] args) {

    List<Integer> length = new ArrayList<Integer>();

    for(int i = 13; i < 1000000; i++){
        length.add(collat(i, 0));
    }
}

public static int collat(int x, int c){

    if(x == 1){
        return c;
    }

    if(x % 2 == 0){
        return collat(x/2, c + 1);
    }else{
        return collat((3 * x) + 1, c + 1);
    }
}
}

【问题讨论】:

  • 欧拉是哪个项目?
  • 试试这里发布的解决方案stackoverflow.com/questions/860550/…
  • 您是否尝试过使用调试器查看错误发生时i 是什么?
  • @HotLicks:该异常仅表示超出了固定堆栈大小。它并不表示存在无限递归。事实上,没有。对于这个 Project Euler 问题中的所有样本,已知 Collat​​z 序列是有限的。
  • @HotLicks:怎么没有无限递归这种东西?你觉得void foo(void) { foo(); } 是做什么的?

标签: java recursion


【解决方案1】:

Sean M. 是正确的;发生整数溢出。 That answer 应标记为已接受。

【讨论】:

  • 对于这种问题当然迭代比较好,但是栈溢出还是个谜。根据en.wikipedia.org/wiki/Collatz_conjecture,“任何小于 1 亿的初始起始数字的最长级数是 63,728,127,有 949 个步骤”。这不应该溢出堆栈。
  • 如果想实验性地增加栈空间可以设置-Xss,不过我原则上同意这个回复。
  • 只是为了笑,插入一个深度计数器,看看你为解决方案做了多深。
【解决方案2】:

您似乎遇到了整数溢出。我刚刚在您的 collat() 函数中添加了这个简单的检查。

if(x < 0) System.out.println("Overflow");

溢出发生在the sequence 中的第 121 步。使用更大的数据类型应该可以解决这个问题。

【讨论】:

    【解决方案3】:

    你需要长而不是整数

    Project Euler Question 14 (Collatz Problem)

    我建议的解决方案,使用 DP

    public class Collatz {
    
    
    public static void main(String[] args) {
    
        List<Long> length = new ArrayList<Long>();
    
        Map<Long,Long> dict = new HashMap<Long,Long>();
    
        for(int i = 13; i < 1000000; i++){
                length.add(collat(i, 0,dict));
    
        }
    }
    
    public static long collat(long x, long c, Map<Long,Long> dict){
    
    
        if(dict.containsKey(x))
        {
            return dict.get(x);
        }
    
        if(x == 1){
            dict.put(x, c);
            return c;
        }
    
        else
        {
            if(x % 2 == 0){
                dict.put(x, collat(x/2, c + 1,dict));
                return dict.get(x);
                }else{
                    dict.put(x,collat((3 * x) + 1, c + 1,dict));
                    return dict.get(x);
                }
            }
        }
    
    }
    

    【讨论】:

      【解决方案4】:

      因为您的默认堆栈大小已用完 128k? 增加堆栈大小可以解决此问题。

      阅读:http://goo.gl/iy77Pr

      【讨论】:

        猜你喜欢
        • 2021-11-27
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-23
        • 1970-01-01
        • 2020-11-05
        相关资源
        最近更新 更多