Guava BigIntegerMath类
BigIntegerMath为BigInteger提供了实用方法。
类声明
以下是 com.google.common.math.BigIntegerMath 类的声明 –
@GwtCompatible(emulated = true) public final class BigIntegerMath extends Object
方法
序号 | 方法与描述 |
---|---|
1 | static BigInteger binomial(int n, int k) 返回 n choose k,也即n和k的二项式系数,即 n! / (k! (n – k)!). |
2 | static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) 返回将p除以q的结果,使用指定的舍入模式进行四舍五入。 |
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
BigIntegerMath类的示例
使用您选择的任何编辑器,在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
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com