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 ==.
import java.math.BigInteger; BigInteger big = new BigInteger("123456789012345678901234567890"); BigInteger sum = big.add(BigInteger.ONE);
Try it
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.
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
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()orcompareTo().==compares references.equals()is true only for equal numeric values, and since there is no scale (unlikeBigDecimal),new BigInteger("5").equals(BigInteger.valueOf(5))is true. PrefercompareTo(...) == 0when comparing in a sorting context. modversusremainder. For negative operandsremainderfollows%(sign of the dividend) whilemodis mathematical and never negative.longValue()truncates silently. UselongValueExact()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
BigIntegerobjects inside hot loops for values that fit in along; considerMath.multiplyExactfirst. - 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.
BigIntegerhas a consistentequals()andhashCode(), so it works as aHashMapkey. - Not in
java.lang. Despite living next to the core classes in documentation indexes, you mustimport java.math.BigInteger;. - Random values.
new BigInteger(int numBits, Random rnd)builds a random non-negative number. UseSecureRandomfor anything security-related.
Related
BigDecimal,Integer,Math- Lessons: Big numbers, Math, Wrapper classes