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 選 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 類的示例

使用您選擇的任何編輯器建立以下 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
guava_math_utilities.htm
廣告

© . All rights reserved.