当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Guava IntMath binomial()用法及代码示例


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

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

用法:


public static int binomial(int n, int k)

参数:此方法接受两个参数n和k并计算二项式系数的值{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-



相关用法


注:本文由纯净天空筛选整理自bansal_rtk_大神的英文原创作品 Java Guava | binomial() method of IntMath Class。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。