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


Java Guava LongMath binomial(int n, int k)用法及代碼示例


Guava LongMath類的二項式(int n,int k)方法接受兩個參數n和k並計算二項式係數的值{n}\choose{k}。如果計算的值超出long的最大值,則該方法返回Long.MAX_VALUE,即long的最大值。

用法:

public static long binomial(int n, int k)

參數:此方法接受兩個參數n和k並計算二項式係數的值{n}\choose{k}


返回值:該方法返回n和k的二項式係數。

異常:如果n為負數,或k為負數或k大於n,則方法binomial(int n,int k)引發IllegalArgumentException。

下麵的示例說明LongMath類的binomial()方法:

範例1:

// Java code to show implementation of 
// binomial(int n, int k) 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 n = 4; 
        int k = 3; 
  
        // Using binomial(int n, int k) method of 
        // Guava's LongMath class 
        long ans = LongMath.binomial(n, k); 
  
        System.out.println("Binomial Coefficient of "
                           + n + " and " + k 
                           + " is:" + ans); 
  
        int n1 = 20; 
        int k1 = 4; 
  
        // Using binomial(int n, int k) method of 
        // Guava's LongMath class 
        long ans1 = LongMath.binomial(n1, k1); 
  
        System.out.println("Binomial Coefficient of "
                           + n1 + " and " + k1 
                           + " is:" + ans1); 
    } 
}
輸出:
Binomial Coefficient of 4 and 3 is:4
Binomial Coefficient of 20 and 4 is:4845

範例2:

// Java code to show implementation of 
// binomial(int n, int k) method of Guava's 
// LongMath class 
  
import java.math.RoundingMode; 
import com.google.common.math.LongMath; 
  
class GFG { 
  
    static long findBinomial(int n, int k) 
    { 
        try { 
            // Using binomial(int n, int k) 
            // method of Guava's LongMath class 
            // This should throw "IllegalArgumentException" 
            // as k < 0 
            long ans = LongMath.binomial(n, k); 
  
            // 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; 
        int k = 7; 
  
        try { 
            // Function calling 
            findBinomial(n, k); 
        } 
        catch (Exception e) { 
            System.out.println(e); 
        } 
    } 
}
輸出:
java.lang.IllegalArgumentException:k (7) > n (5)

參考: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/LongMath.html#binomial-int-int-



相關用法


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