aebkea
aebkea

Reputation: 23

Why isn't this Ackermann function working?

I would expect this to return with 7, given the input of (2,2). Instead of getting a proper output, the program returns a java.lang.StackOverflowError at line 16.

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);
    }

}

I've increased the maximum stack size all the way up to 2GB, but it's still throwing the error at the small input of (2,2). Before I started using the BigIntegers instead of Longs, everything worked out fine with the input (2,2), but now it's a mess.

Upvotes: 0

Views: 336

Answers (1)

Henry
Henry

Reputation: 43738

Instead of equals(0) you have to use equals(BigInteger.ZERO).

Otherwise you compare a BigInteger to an Integer (auto boxing) which will always be false.

Upvotes: 3

Related Questions