Guava-bigintegermath

提供:Dev Guides
移動先:案内検索

グアバ-BigIntegerMathクラス

BigIntegerMathは、BigIntegerのユーティリティメソッドを提供します。

クラス宣言

以下は com.google.common.math.BigIntegerMath クラスの宣言です-

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

方法

Sr.No Method & Description
1

static BigInteger binomial(int n, int k)

nを返します。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

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