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.
Syntax:
public static BigInteger factorial(int n)
Parameters: This method takes the number n as parameter whose factorial is to be found.
Return Value: This method returns the factorial of the given number n.
Exceptions: This method throws IllegalArgumentException if n < 0.
Note:
- The method returns 1 if n == 0.
- The result takes O(n log n) space, so use cautiously.
- This uses an efficient binary recursive algorithm to compute the factorial with balanced multiplies.
Below examples illustrates the BigIntegerMath.factorial() method:
Example 1:
Java
import java.math.*;
import com.google.common.math.BigIntegerMath;
class GFG {
public static void main(String args[])
{
int n1 = 10 ;
BigInteger ans1 = BigIntegerMath.factorial(n1);
System.out.println( "Factorial of " + n1
+ " is: " + ans1);
int n2 = 12 ;
BigInteger ans2 = BigIntegerMath.factorial(n2);
System.out.println( "Factorial of " + n2
+ " is: " + ans2);
}
}
|
Output:
Factorial of 10 is: 3628800
Factorial of 12 is: 479001600
Example 2:
Java
import java.math.*;
import com.google.common.math.BigIntegerMath;
class GFG {
public static void main(String args[])
{
try {
int n1 = - 5 ;
BigInteger ans1 = BigIntegerMath.factorial(n1);
System.out.println( "Factorial of " + n1
+ " is: " + ans1);
}
catch (Exception e) {
System.out.println( "Exception: " + e);
}
}
}
|
Output:
Exception: java.lang.IllegalArgumentException: n (-5) must be >= 0
Reference: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#factorial-int-
Last Updated :
26 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...