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


Java Guava BigIntegerMath binomial()用法及代碼示例


Guava BigIntegerMath類的二項式(int n,int k)方法返回n選擇k,也稱為n和k的二項式係數,即

n! / (k! (n - k)!)

用法:

public static BigInteger binomial(int n, int k)

參數:此方法采用以下參數:


  • n:二項式展開的基礎。
  • k:二項式展開的力量。

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

異常:如果n <0,k <0或k> n,則此方法引發IllegalArgumentException。

注意:結果可能占用O(k log n)個空間。

以下示例說明了BifIntegerMath.binomial()方法:

範例1:

// Java code to show implementation of 
// binomial(int n, int k) 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 n = 5; 
        int k = 2; 
  
        // Using binomial(int n, int k) method of 
        // Guava's BigIntegerMath class 
        BigInteger ans = BigIntegerMath.binomial(n, k); 
  
        System.out.println("Binomial Coefficient of "
                           + n + " & " + k 
                           + " is:" + ans); 
  
        int n1 = 15; 
        int k1 = 9; 
  
        // Using binomial(int n, int k) method of 
        // Guava's BigIntegerMath class 
        BigInteger ans1 = BigIntegerMath.binomial(n1, k1); 
  
        System.out.println("Binomial Coefficient of "
                           + n1 + " & " + k1 
                           + " is:" + ans1); 
    } 
}
輸出:
Binomial Coefficient of 5 & 2 is:10
Binomial Coefficient of 15 & 9 is:5005

範例2:

// Java code to show implementation of 
// binomial(int n, int k) 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 n = 5; 
            int k = 7; 
  
            // Using binomial(int n, int k) method of 
            // Guava's BigIntegerMath class 
            // This should raise "IllegalArgumentException" 
            // as k > n 
            BigInteger ans = BigIntegerMath.binomial(n, k); 
  
            System.out.println("Binomial Coefficient of"
                               + n + " & " + k 
                               + " is:" + ans); 
        } 
        catch (Exception e) { 
            System.out.println("Exception:" + e); 
        } 
    } 
}
輸出:
Exception:java.lang.IllegalArgumentException:k (7) > n (5)

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



相關用法


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