Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท java.lang

The BigInteger class

Reference for java.math.BigInteger: arbitrary-precision integers, arithmetic, modular math, primes, bit operations, exact conversions and common pitfalls.

BigInteger (in the package java.math) represents an integer of any size. Where long overflows silently at about 9.2 x 10^18, a BigInteger simply grows until memory runs out. It is the right tool for factorials, cryptography, exact counting and any calculation where an overflow would be a bug.

Instances are immutable: every operation returns a new object and the original never changes. There are no operators, so you write a.add(b) instead of a + b, and you compare values with compareTo() or equals(), never ==.

Java
import java.math.BigInteger;

BigInteger big = new BigInteger("123456789012345678901234567890");
BigInteger sum = big.add(BigInteger.ONE);

Try it

Java Factorials beyond long

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Division, modular math and primes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public class BigInteger extends Number implements Comparable<BigInteger>
Member Description
BigInteger(String val) Parses a decimal string with an optional leading - or +. Throws NumberFormatException for anything else.
BigInteger(String val, int radix) Parses digits in the given radix (2 to 36).
static BigInteger valueOf(long val) Converts a long. The usual way to turn a number into a BigInteger.
ZERO, ONE, TWO, TEN Constants (TWO since Java 9).
add, subtract, multiply Basic arithmetic.
divide(BigInteger) Integer division, truncating toward zero. Throws ArithmeticException on division by zero.
remainder(BigInteger) Remainder with the sign of the dividend, like %.
mod(BigInteger m) Always non-negative; m must be positive, otherwise ArithmeticException.
pow(int exponent) Raises to a non-negative int power.
modPow, modInverse, gcd Number-theory helpers.
sqrt() Integer square root, rounded down (since Java 9).
compareTo, equals, signum, abs, negate, min, max Comparison and sign helpers.
isProbablePrime(int certainty), nextProbablePrime() Probabilistic primality.
shiftLeft, shiftRight, and, or, xor, not, testBit, bitLength, bitCount Bit operations with two's-complement semantics.
intValue, longValue, doubleValue Lossy conversions: high-order bits are discarded without warning.
intValueExact, longValueExact (and shortValueExact, byteValueExact) Throw ArithmeticException when the value does not fit.
toString(), toString(int radix) Text in decimal or another radix.

Usage notes

  • Immutable. x.add(y); on its own does nothing useful; assign the result.
  • Use equals() or compareTo(). == compares references. equals() is true only for equal numeric values, and since there is no scale (unlike BigDecimal), new BigInteger("5").equals(BigInteger.valueOf(5)) is true. Prefer compareTo(...) == 0 when comparing in a sorting context.
  • mod versus remainder. For negative operands remainder follows % (sign of the dividend) while mod is mathematical and never negative.
  • longValue() truncates silently. Use longValueExact() when overflow should be an error.
  • Performance. Operations are slower than primitives by one to two orders of magnitude. Multiplication switches to Karatsuba and Toom-Cook algorithms for large numbers. Avoid creating BigInteger objects inside hot loops for values that fit in a long; consider Math.multiplyExact first.
  • Cost of toString(). Converting a huge number to decimal is much slower than arithmetic on it.
  • Thread safety. Immutable, so instances can be shared freely between threads.
  • Hash keys. BigInteger has a consistent equals() and hashCode(), so it works as a HashMap key.
  • Not in java.lang. Despite living next to the core classes in documentation indexes, you must import java.math.BigInteger;.
  • Random values. new BigInteger(int numBits, Random rnd) builds a random non-negative number. Use SecureRandom for anything security-related.