Java番石榴 |带示例的 LongMath 类的二项式(int n,int k)
Guava 的 LongMath 类的binomial(int n, int k)方法接受两个参数n和k并计算二项式系数的值 .如果计算的值超出了 long 的最大值,则该方法返回 Long.MAX_VALUE,即 long 的最大值。
句法 :
public static long binomial(int n, int k)
参数:此方法接受两个参数n和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-