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?
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).
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.
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.
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).
There's an error in the code, you should put
BigInteger factz = BigInteger.valueOf(a);
instead of BigInteger factz = BigInteger.ONE;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With