Finding the factorial using recursion with the BigInteger Class

Srikanta R Gunner Somayaji picture Srikanta R Gunner Somayaji · Jul 28, 2013 · Viewed 8.1k times · Source

So consider the following program-segment! I've tried to use the basic recursion function to determine the factorial of a number, but now using the BigInteger class.

public static BigInteger fact(int a)
{
    BigInteger factorial = BigInteger.ONE;

    BigInteger factz = BigInteger.ONE;

    if(a == 1)
    {
        return factorial;
    }

    else
    {
        return factz.multiply(fact(a-1));
    }
}

So when I try implementing this in a program, it returns the output as 1. Is it because BigInteger objects are immutable? Or am I missing something here?

Answer

Dmitry Bychenko picture Dmitry Bychenko · Jul 28, 2013

There's an error in the code, you should put

  BigInteger factz = BigInteger.valueOf(a);

instead of BigInteger factz = BigInteger.ONE;