BigIntegerMath 阶乘()函数|番石榴 |Java
Guava 的 BigIntegerMath 类的方法factorial(int n)用于查找给定数字的阶乘。它返回 n!,即前 n 个正整数的乘积。
句法:
public static BigInteger factorial(int n)
参数:此方法将数字n作为要找到其阶乘的参数。
返回值:此方法返回给定数 n 的阶乘。
异常:如果 n < 0,此方法将引发IllegalArgumentException 。
笔记:
- 如果 n == 0,该方法返回 1。
- 结果占用 O(n log n) 空间,因此请谨慎使用。
- 这使用有效的二进制递归算法来计算具有平衡乘法的阶乘。
下面的示例说明了 BigIntegerMath.factorial() 方法:
示例 1:
Java
// Java code to show implementation of
// factorial() method of Guava's BigIntegerMath class
import java.math.*;
import com.google.common.math.BigIntegerMath;
class GFG {
// Driver code
public static void main(String args[])
{
int n1 = 10;
// Using factorial(int n) method of
// Guava's BigIntegerMath class
BigInteger ans1 = BigIntegerMath.factorial(n1);
System.out.println("Factorial of " + n1
+ " is: " + ans1);
int n2 = 12;
// Using factorial(int n) method of
// Guava's BigIntegerMath class
BigInteger ans2 = BigIntegerMath.factorial(n2);
System.out.println("Factorial of " + n2
+ " is: " + ans2);
}
}
Java
// Java code to show implementation of
// factorial() method of Guava's BigIntegerMath class
import java.math.*;
import com.google.common.math.BigIntegerMath;
class GFG {
// Driver code
public static void main(String args[])
{
try {
int n1 = -5;
// Using factorial(int n) method of
// Guava's BigIntegerMath class
// This should throw "IllegalArgumentException"
// as n < 0
BigInteger ans1 = BigIntegerMath.factorial(n1);
System.out.println("Factorial of " + n1
+ " is: " + ans1);
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出:
Factorial of 10 is: 3628800
Factorial of 12 is: 479001600
示例 2:
Java
// Java code to show implementation of
// factorial() method of Guava's BigIntegerMath class
import java.math.*;
import com.google.common.math.BigIntegerMath;
class GFG {
// Driver code
public static void main(String args[])
{
try {
int n1 = -5;
// Using factorial(int n) method of
// Guava's BigIntegerMath class
// This should throw "IllegalArgumentException"
// as n < 0
BigInteger ans1 = BigIntegerMath.factorial(n1);
System.out.println("Factorial of " + n1
+ " is: " + ans1);
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出:
Exception: java.lang.IllegalArgumentException: n (-5) must be >= 0
参考: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#factorial-int-