當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Longs.factorial(int n)用法及代碼示例


Guava LongMath類的factorial(int n)方法返回前n個正整數的乘積,即n!。

用法:

public static long factorial(int n)

參數:該方法僅接受一個整數類型的參數n,用於查找階乘。


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

  • 如果n為0,則此方法返回1。
  • 如果結果適合長整數,則此方法返回前n個正整數的乘積。
  • 如果結果不適合長時間,則此方法返回Long.MAX_VALUE。

異常:如果n為負數,則factorial(int n)方法將引發IllegalArgumentException。

下麵的程序說明LongMath.factorial()方法的使用:

範例1:

// Java code to show implementation of 
// factorial(int n) method of Guava's 
// LongMath Class 
  
import java.math.RoundingMode; 
import com.google.common.math.LongMath; 
  
class GFG { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        int n1 = 10; 
  
        // Using factorial(int n) method of 
        // Guava's LongMath class 
        long ans1 = LongMath.factorial(n1); 
  
        System.out.println("factorial of "
                           + n1 + " is:"
                           + ans1); 
  
        int n2 = 12; 
  
        // Using factorial(int n) method of 
        // Guava's LongMath class 
        long ans2 = LongMath.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 
// LongMath Class 
  
import java.math.RoundingMode; 
import com.google.common.math.LongMath; 
  
class GFG { 
  
    static long findFact(int n) 
    { 
        try { 
            // Using factorial(int n) method of 
            // Guava's LongMath class 
            // This should throw "IllegalArgumentException" 
            // as n < 0 
            long ans = LongMath.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/LongMath.html#factorial-int-



相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Java Guava | Longs.factorial(int n) method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。