Guava IntMath類的二項式(int n,int k)方法接受兩個參數n和k並計算二項式係數的值。
如果計算得出的值超出整數的最大值,則該方法將返回Integer.MAX_VALUE或換句話說,返回整數的最大值。
用法:
public static int binomial(int n, int k)
參數:此方法接受兩個參數n和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)
相關用法
- Java Guava IntMath mod()用法及代碼示例
- Java Guava IntMath gcd(int a, int b)用法及代碼示例
- Java Guava IntMath pow(int b, int k)用法及代碼示例
- Java Guava IntMath mean()用法及代碼示例
- Java Guava IntMath isPowerOfTwo()用法及代碼示例
- Java Guava IntMath floorPowerOfTwo()用法及代碼示例
- Java Guava IntMath ceilingPowerOfTwo()用法及代碼示例
- Java Guava IntMath isPrime()用法及代碼示例
- Java Guava IntMath sqrt(int x, RoundingMode mode)用法及代碼示例
- Java Guava LongMath binomial(int n, int k)用法及代碼示例
- Java IntMath.checkedSubtract(int a, int b)用法及代碼示例
- Java IntMath.checkedMultiply(int a, int b)用法及代碼示例
- Java IntMath.checkedAdd(int a, int b)用法及代碼示例
注:本文由純淨天空篩選整理自bansal_rtk_大神的英文原創作品 Java Guava | binomial() method of IntMath Class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。