📌  相关文章
📜  Java番石榴 | IntMath 类的 binomial() 方法

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

Java番石榴 | IntMath 类的 binomial() 方法

Guava的IntMath类的binomial(int n, int k)方法接受nk两个参数,计算二项式系数的值{n}\choose{k} .

如果计算值溢出整数的最大值,则该方法返回 Integer.MAX_VALUE 或换句话说,整数的最大值。

句法 :

public static int binomial(int n, int k)

参数:此方法接受两个参数nk并计算二项式系数的值{n}\choose{k} .

返回值:该方法返回 n 和 k 的二项式系数。

异常:如果 n < 0、k < 0 或 k > n,方法 binomial(int n, int k) 将抛出IllegalArgumentException

下面的例子说明了 IntMath 类的 binomial() 方法:

示例 1:

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

示例 2:

// Java code to show implementation of
// binomial(int n, int k) method of Guava's
// IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
  
class GFG {
  
    static int findBinomial(int n, int k)
    {
  
        try {
            // Using binomial(int n, int k)
            // method of Guava's IntMath class
            // This should throw "IllegalArgumentException"
            // as k < 0
            int ans = IntMath.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/IntMath.html#binomial-int-int-