Guava - BigIntegerMath Class


BigIntegerMath provides utility methods on BigInteger.

Class Declaration

Following is the declaration for class −

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


Sr.No Method & Description

static BigInteger binomial(int n, int k)

Returns n choose k, also known as the binomial coefficient of n and k, that is, n! / (k! (n - k)!).


static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode)

Returns the result of dividing p by q, rounding using the specified RoundingMode.


static BigInteger factorial(int n)

Returns n!, that is, the product of the first n positive integers, or 1 if n == 0.


static boolean isPowerOfTwo(BigInteger x)

Returns true if x represents a power of two.


static int log10(BigInteger x, RoundingMode mode)

Returns the base-10 logarithm of x, rounded according to the specified rounding mode.


static int log2(BigInteger x, RoundingMode mode)

Returns the base-2 logarithm of x, rounded according to the specified rounding mode.


static BigInteger sqrt(BigInteger x, RoundingMode mode)

Returns the square root of x, rounded with the specified rounding mode.

Methods Inherited

This class inherits methods from the following class −

  • java.lang.Object

Example of BigIntegerMath Class

Create the following java program using any editor of your choice in say C:/> Guava.

import java.math.BigInteger;
import java.math.RoundingMode;


public class GuavaTester {

   public static void main(String args[]) {
      GuavaTester tester = new GuavaTester();
   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));

Verify the Result

Compile the class using javac compiler as follows −


Now run the GuavaTester to see the result.

C:\Guava>java GuavaTester

See the result.

Error: Rounding necessary
Log2(2): 1
Log10(10): 1
sqrt(100): 10
factorial(5): 120