繁体   English   中英

为什么此Ackermann函数不起作用?

[英]Why isn't this Ackermann function working?

考虑到(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)都可以正常工作,但是现在很混乱。

代替equals(0)您必须使用equals(BigInteger.ZERO)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM