Guava - BigIntegerMath 类
BigIntegerMath 提供 BigInteger 上的实用方法。
类声明
以下是 com.google.common.math.BigIntegerMath 类的声明 −
@GwtCompatible(emulated = true) public final class BigIntegerMath extends Object
方法
Sr.No | 方法及描述 |
---|---|
1 |
static BigInteger binomial(int n, int k) 返回n选择的k,也称为n和k的二项式系数,即n! /(k!(n - k)!)。 |
2 | static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) 返回 p 除以 q 的结果,使用指定的 RoundingMode 进行舍入。 |
3 |
static BigInteger factorial(int n) 返回 n!,即前 n 个正整数的乘积,如果 n == 0,则返回 1。 |
4 |
static boolean isPowerOfTwo(BigInteger x) 如果 x 代表 2 的幂,则返回 true。 |
5 |
static int log10(BigInteger x, RoundingMode mode) 返回 x 以 10 为底的对数,根据指定的舍入模式进行舍入。 |
6 |
static int log2(BigInteger x, RoundingMode mode) 返回 x 以 2 为底的对数,根据指定的舍入模式进行舍入。 |
7 |
static BigInteger sqrt(BigInteger x, RoundingMode mode) 返回 x 的平方根,并使用指定的舍入模式进行舍入。 |
继承的方法
该类继承了以下类的方法 −
- java.lang.Object
Example of BigIntegerMath Class
使用您在 C:/> Guava 中选择的任何编辑器创建以下 java 程序。
GuavaTester.java
import java.math.BigInteger; import java.math.RoundingMode; import com.google.common.math.BigIntegerMath; public class GuavaTester { public static void main(String args[]) { GuavaTester tester = new GuavaTester(); tester.testBigIntegerMath(); } private void testBigIntegerMath() { System.out.println(BigIntegerMath.divide(BigInteger.TEN, new BigInteger("2"), RoundingMode.UNNECESSARY)); try { //exception will be thrown as 100 is not completely divisible by 3 // thus rounding is required, and RoundingMode is set as UNNESSARY System.out.println(BigIntegerMath.divide(BigInteger.TEN, new BigInteger("3"), RoundingMode.UNNECESSARY)); } catch(ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } System.out.println("Log2(2): " + BigIntegerMath.log2(new BigInteger("2"), RoundingMode.HALF_EVEN)); System.out.println("Log10(10): " + BigIntegerMath.log10(BigInteger.TEN, RoundingMode.HALF_EVEN)); System.out.println("sqrt(100): " + BigIntegerMath.sqrt(BigInteger.TEN.multiply(BigInteger.TEN), RoundingMode.HALF_EVEN)); System.out.println("factorial(5): "+BigIntegerMath.factorial(5)); } }
验证结果
使用javac编译器编译类,如下所示 −
C:\Guava>javac GuavaTester.java
现在运行 GuavaTester 查看结果。
C:\Guava>java GuavaTester
查看结果。
5 Error: Rounding necessary Log2(2): 1 Log10(10): 1 sqrt(100): 10 factorial(5): 120