线程“main”java.lang.StackOverflowError中的异常

时间:2012-10-07 15:21:59

标签: java recursion hashmap stack-overflow

我有一段代码,我无法弄清楚为什么它在线程“main”java.lang.StackOverflowError中给出了Exception。

这就是问题:

Given a positive integer n, prints out the sum of the lengths of the Syracuse 
sequence starting in the range of 1 to n inclusive. So, for example, the call:
lengths(3)
will return the the combined length of the sequences:
1
2 1
3 10 5 16 8 4 2 1 
which is the value: 11. lengths must throw an IllegalArgumentException if 
its input value is less than one.

我的代码:

import java.util.HashMap;

public class Test {

HashMap<Integer,Integer> syraSumHashTable = new HashMap<Integer,Integer>();

public Test(){

}

public int lengths(int n)throws IllegalArgumentException{

    int sum =0;

    if(n < 1){
        throw new IllegalArgumentException("Error!! Invalid Input!");
    }   

    else{


        for(int i =1; i<=n;i++){

            if(syraSumHashTable.get(i)==null)
            {
                syraSumHashTable.put(i, printSyra(i,1));
                sum += (Integer)syraSumHashTable.get(i);

            }

            else{

                sum += (Integer)syraSumHashTable.get(i);
            }



        }

        return sum;

    }



}

private int printSyra(int num, int count){

    int n = num;

    if(n == 1){

        return count;
    }

    else{   
            if(n%2==0){

                return printSyra(n/2, ++count);
            }

            else{

                return printSyra((n*3)+1, ++count) ;

            }

    }


}
}

驱动程序代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Test s1 = new Test();
    System.out.println(s1.lengths(90090249));
    //System.out.println(s1.lengths(5));
}

。 我知道问题在于递归。如果输入是一个小值,则不会发生错误,例如:5。但是当数字很大时,如90090249,我在线程“main”java.lang.StackOverflowError中得到了Exception。感谢你的帮助。 :)

我几乎忘记了错误消息:

Exception in thread "main" java.lang.StackOverflowError
at Test.printSyra(Test.java:60)
at Test.printSyra(Test.java:65)
at Test.printSyra(Test.java:60)
at Test.printSyra(Test.java:65)
at Test.printSyra(Test.java:60)
at Test.printSyra(Test.java:60)
at Test.printSyra(Test.java:60)
at Test.printSyra(Test.java:60)

3 个答案:

答案 0 :(得分:7)

你的算法很好。但是int对于您的计算来说太小了,它输入失败了:

printSyra(113383, 1);

在某些时候整数溢出到负值,你的实现变得疯狂,无限递归。将int num更改为long num,你会没事的 - 有一段时间了。稍后您需要BigInteger

请注意,根据维基百科Collatz conjecture(大胆的我的):

  

任何初始起始数小于1亿的最长进展为63,728,127, 949步。对于少于10亿的起始数字,它是670,617,279,有986步,对于数字少于100亿,它是9,780,657,630, 1132步

总步数相当于您可以预期的最大嵌套级别(堆栈深度)。因此即使对于相对较大的数字StackOverflowError也不应该发生。使用BigInteger

查看此实现
private static int printSyra(BigInteger num, int count) {
    if (num.equals(BigInteger.ONE)) {
        return count;
    }
    if (num.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) {
        return printSyra(num.divide(BigInteger.valueOf(2)), count + 1);
    } else {
        return printSyra(num.multiply(BigInteger.valueOf(3)).add(BigInteger.ONE), count + 1);
    }
}

它甚至适用于非常大的值:

printSyra(new BigInteger("9780657630"), 0)  //1132
printSyra(new BigInteger("104899295810901231"), 0)  //2254

答案 1 :(得分:1)

这是递归算法的固有问题。使递归的数量足够大并且您无法真正避免堆栈溢出,除非该语言可以保证尾调用优化(Java和大多数类C语言不能)。真正修复它的唯一方法是“展开”递归,迭代地重写算法或使用辅助函数来模拟递归调用的状态传递,而不实际嵌套调用。

答案 2 :(得分:1)

一种解决方案是允许JVM使用java -Xss参数为堆栈递归占用更多空间。它的默认值小于1兆字节,IIRC,最多可以限制几百次递归。

更好的解决方案是在不递归的情况下重写练习:

private int printSyra(int num){
    int count = 1;    
    int n = num;    
    while(n != 1){

            if(n%2==0){    
                n = n/2;
                ++count;
            }    
            else{    
                n=(n*3)+1;
                ++count;    
            }    
    }
    return count;
}
相关问题