为什么这个Ackermann功能不起作用?

时间:2015-10-08 19:02:52

标签: java recursion

考虑到(2,2)的输入,我希望这会以7返回。程序在第16行返回java.lang.StackOverflowError,而不是获得正确的输出。

package main;

import java.math.BigInteger;

public class Ackermann {

    public static void main(String[] args) {
        System.out.println(ack(BigInteger.valueOf(2),BigInteger.valueOf(2)));

    }

    public static BigInteger ack(BigInteger a, BigInteger b) {
        BigInteger ans;
        if (a.equals(0)) ans = b.add(BigInteger.ONE);
        else if (b.equals(0)) ans = ack(a.subtract(BigInteger.ONE),BigInteger.valueOf(1));
        else ans = ack(a.subtract(BigInteger.ONE), ack(a,b.subtract(BigInteger.ONE))); //line 16
        return (ans);
    }

}

我已经将最大堆栈大小一直增加到2GB,但它仍然会在(2,2)的小输入处抛出错误。在我开始使用BigIntegers而不是Longs之前,输入(2,2)的一切都很好,但现在它变得一团糟。

1 个答案:

答案 0 :(得分:3)

而不是equals(0),您必须使用equals(BigInteger.ZERO)

否则你将BigInteger与整数(自动装箱)进行比较,它总是为假。

相关问题