Java BigIntegerMath factorial() 函数

Java BigIntegerMath factorial() 函数

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 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);
    }
}

输出

Factorial of 10 is: 3628800
Factorial of 12 is: 479001600

例2:

// 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-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程