Guava – LongMath.binomial方法与实例

来源:这里教程网 时间:2026-02-17 21:41:42 作者:

Guava – LongMath.binomial方法与实例

Guava的LongMath类的binomial(int n, int k)方法接受两个参数 n and k ,并计算二项式系数的值 。如果计算值超过长的最大值,则该方法返回Long.MAX_VALUE即长的最大值。

语法:

public static long binomial(int n, int k)

参数 : 该方法接受两个参数 n and 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 classimport 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 : 4Binomial 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-

相关推荐