Search code examples
javarecursionbigintegerfactorial

Finding the factorial using recursion with the BigInteger Class


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?


Solution

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

      BigInteger factz = BigInteger.valueOf(a);
    

    instead of BigInteger factz = BigInteger.ONE;