Guava BigIntegerMath類

BigIntegerMath提供BigInteger的實用方法。

類聲明

以下是com.google.common.math.BigIntegerMath類的聲明:

@GwtCompatible(emulated=true) public final class BigIntegerMath extends Object

方法

S.N.

方法及說明

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個正整數的乘積,或1如果n== 0。

4

static boolean isPowerOfTwo(BigInteger x)
返回true,如果x代表兩個冪。

5

static int log10(BigInteger x, RoundingMode mode)
返回基數爲10的對數x,根據指定的舍入模式範圍。

6

static int log2(BigInteger x, RoundingMode mode)
返回基數爲2-對數x,根據指定的舍入模式圓形。

7

static BigInteger sqrt(BigInteger x, RoundingMode mode)
返回x的平方根,大概指定的舍入模式。

繼承的方法

這個類繼承了以下類方法:

  • java.lang.Object

BigIntegerMath 示例

使用所選擇的任何編輯器創建下面的java程序 C:/> Guava

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