为什么这个阿克曼函数不起作用?



我希望它返回7,给定输入(2,2)。程序没有得到正确的输出,而是在第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)的小输入上抛出错误。在我开始使用biginteger而不是Longs之前,输入(2,2)一切都很好,但现在它变得一团糟。

equals(BigInteger.ZERO)代替equals(0)

将BigInteger与Integer(自动装箱)进行比较,后者将始终为false。

最新更新