Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to work with very large integers

Short answer

int holds numbers up to about 2 billion, long up to 9.2 quintillion. Anything larger goes into BigInteger:

void main() {
    IO.println(Integer.MAX_VALUE);
    IO.println(Long.MAX_VALUE);
 
    var big = new BigInteger("123456789012345678901234567890");
    IO.println(big.multiply(big));
}

Output:

2147483647
9223372036854775807
15241578753238836750495351562536198787501905199875019052100

Arithmetic

BigInteger has no operators — methods replace +, -, * and /:

void main() {
    var a = BigInteger.valueOf(2).pow(100);
    var b = BigInteger.TEN;
 
    IO.println(a);
    IO.println(a.add(b));
    IO.println(a.mod(BigInteger.valueOf(7)));
}

Output:

1267650600228229401496703205376
1267650600228229401496703205386
2

Comparison

Compare with compareTo() or equals(), not < and ==:

void main() {
    var a = new BigInteger("1000000000000000000000");
    var b = a.add(BigInteger.ONE);
 
    IO.println(a.compareTo(b) < 0);
    IO.println(a.max(b));
}

Output:

true
1000000000000000000001

Back to long

longValueExact() returns a long if the value fits and throws otherwise — so a mistake does not go unnoticed:

void main() {
    IO.println(BigInteger.valueOf(42).longValueExact());
    IO.println(BigInteger.TWO.pow(70).longValueExact());
}

Output:

42
Exception in thread "main" java.lang.ArithmeticException: BigInteger out of long range

Common mistake

Writing a large number as a literal. An integer literal without a suffix is an int, and the compiler refuses it:

void main() {
    long big = 3000000000;
    IO.println(big);
}

Output:

Main.java:2: error: integer number too large

For a long add the L suffix: 3000000000L. For even larger numbers use new BigInteger("…").

Functions used in this recipe

  • BigInteger — An integer of any size — for when even long is not enough.
  • Integer.MAX_VALUE — The largest int value; its partner is Integer.MIN_VALUE.

Thanks for reading!

Donate to the site — we work hard for you.