📌  相关文章
📜  Java番石榴|带有示例的 IntMath 类的 factorial(int n) 方法

📅  最后修改于: 2022-05-13 01:57:12.987000             🧑  作者: Mango

Java番石榴|带有示例的 IntMath 类的 factorial(int n) 方法

Guava 的 IntMath 类的factorial(int n)方法返回前 n 个正整数的乘积,即 n!。

句法:

public static int factorial(int n)

参数:该方法只接受一个参数 n,它是整数类型,用于查找阶乘。

返回值:此方法返回以下值:

  • 如果 n 为 0,则此方法返回1
  • 如果结果适合 int ,则此方法返回前 n 个正整数的乘积
  • 如果结果不适合 int,则此方法返回Integer.MAX_VALUE

例外:如果 n 为负,则方法 factorial(int n) 抛出IllegalArgumentException



示例 1:

// Java code to show implementation of
// factorial(int n) method of Guava's
// IntMath class
  
import java.math.RoundingMode;
import com.google.common.math.IntMath;
  
class GFG {
  
    // Driver code
    public static void main(String args[])
    {
        int n1 = 10;
  
        // Using factorial(int n) method of
        // Guava's IntMath class
        int ans1 = IntMath.factorial(n1);
  
        System.out.println("factorial of "
                           + n1 + " is : "
                           + ans1);
  
        int n2 = 12;
  
        // Using factorial(int n) method of
        // Guava's IntMath class
        int ans2 = IntMath.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(int n) method of Guava's
// IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
  
class GFG {
  
    static int findFact(int n)
    {
        try {
  
            // Using factorial(int n) method of
            // Guava's IntMath class
            // This should throw "IllegalArgumentException"
            // as n < 0
            int ans = IntMath.factorial(n);
  
            // Return the answer
            return ans;
        }
        catch (Exception e) {
            System.out.println(e);
            return -1;
        }
    }
  
    // Driver code
    public static void main(String args[])
    {
        int n = -5;
  
        try {
  
            // Function calling
            findFact(n);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
java.lang.IllegalArgumentException: n (-5) must be >= 0

参考: https : //google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#factorial-int-