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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。