Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 747
Srikanta R Gunner Somayaji Avatar asked Jul 28 '13 12:07

Srikanta R Gunner Somayaji


People also ask

How do you find the recursive factorial?

The factorial function can be written as a recursive function call. Recall that factorial(n) = n × (n – 1) × (n – 2) × … × 2 × 1. The factorial function can be rewritten recursively as factorial(n) = n × factorial(n – 1).

How do you find the factorial of a number using recursion in Java?

Example: Factorial of a Number Using RecursionInitially, the multiplyNumbers() is called from the main() function with 6 passed as an argument. Since 6 is greater than or equal to 1, 6 is multiplied to the result of multiplyNumbers() where 5 (num -1) is passed.

Is there a built in function for factorial in Java?

BigIntegerMath factorial() function | Guava | Java The method factorial(int n) of Guava's BigIntegerMath class is used to find the factorial of the given number. It returns n!, that is, the product of the first n positive integers. Parameters: This method takes the number n as parameter whose factorial is to be found.

How many times will the function fact () be called when the following code is executed?

10. How many times will the function fact() be called when the following code is executed? Explanation: The fact() function will be called 6 times with the following arguments: fact(5), fact(4), fact(3), fact(2), fact(1), fact(0).


1 Answers

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

  BigInteger factz = BigInteger.valueOf(a);

instead of BigInteger factz = BigInteger.ONE;

like image 165
Dmitry Bychenko Avatar answered Sep 27 '22 23:09

Dmitry Bychenko