BigInteger is Java's class for representing arbitrarily large integers — numbers with no practical upper or lower limit. It lives in java.math and is the right tool whenever your values can overflow int or long.
Why int and long Aren't Always Enough
Java's primitive integer types have hard limits:
| Type | Min Value | Max Value |
|---|---|---|
int | -2,147,483,648 | 2,147,483,647 (~2.1 billion) |
long | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 (~9.2 quintillion) |
When a computation exceeds these bounds, the result silently wraps around — no exception, just a wrong answer:
int x = Integer.MAX_VALUE;
System.out.println(x + 1); // -2147483648 — silent overflow!
long y = Long.MAX_VALUE;
System.out.println(y + 1); // -9223372036854775808 — silent overflow!
BigInteger has no such limit. It allocates as much memory as needed to represent the value exactly.
Creating BigInteger Values
import java.math.BigInteger;
// From a long value
BigInteger a = BigInteger.valueOf(15);
// From a string — the only way for numbers larger than long
BigInteger huge = new BigInteger("123456789012345678901234567890");
// Built-in constants
BigInteger zero = BigInteger.ZERO;
BigInteger one = BigInteger.ONE;
BigInteger two = BigInteger.TWO;
BigInteger ten = BigInteger.TEN;
Arithmetic Operations
BigInteger is immutable — every operation returns a new object. Use the result, don't just call the method:
BigInteger a = BigInteger.valueOf(15);
BigInteger b = BigInteger.valueOf(4);
System.out.println(a.add(b)); // 19
System.out.println(a.subtract(b)); // 11
System.out.println(a.multiply(b)); // 60
System.out.println(a.divide(b)); // 3 (integer division)
System.out.println(a.remainder(b));// 3 (a % b)
System.out.println(a.pow(3)); // 3375 (15^3)
System.out.println(a.abs()); // 15
System.out.println(a.negate()); // -15
System.out.println(a.gcd(b)); // 1 (greatest common divisor)
Real-World Example: Large Factorial
Computing 50! overflows long at around 20!. BigInteger handles it without issue:
public static BigInteger factorial(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
System.out.println(factorial(20));
// 2432902008176640000 — fits in long
System.out.println(factorial(50));
// 30414093201713378043612608166979581188299763898377856000000000000
// — impossible in long, exact in BigInteger
Comparison and Equality
Never use == to compare BigInteger values — it compares object references, not numeric values. Use compareTo() or equals():
BigInteger x = BigInteger.valueOf(100);
BigInteger y = BigInteger.valueOf(100);
BigInteger z = BigInteger.valueOf(200);
System.out.println(x == y); // false (different objects)
System.out.println(x.equals(y)); // true
System.out.println(x.compareTo(y)); // 0 (equal)
System.out.println(x.compareTo(z)); // -1 (x < z)
System.out.println(z.compareTo(x)); // 1 (z > x)
System.out.println(x.max(z)); // 200
System.out.println(x.min(z)); // 100
Converting Between Types
BigInteger big = BigInteger.valueOf(42);
int asInt = big.intValue(); // 42 (throws if value doesn't fit)
long asLong = big.longValue(); // 42L
double asDouble = big.doubleValue(); // 42.0 (may lose precision)
String asString = big.toString(); // "42"
String asHex = big.toString(16); // "2a" (hexadecimal)
String asBinary = big.toString(2); // "101010" (binary)
Use intValueExact() or longValueExact() (Java 8+) if you want an ArithmeticException instead of silent truncation when the value doesn't fit.
When to Use BigInteger
- Factorial and combinatorics — values grow faster than
longcan hold - Cryptographic algorithms — RSA, DSA, and Diffie-Hellman operate on numbers hundreds of digits long
- Financial calculations — when precision with very large sums is required (though
BigDecimalis better for fractions) - Competitive programming — problems that explicitly work with arbitrarily large integers
- Hash and ID generation — when encoding large identifiers that span more than 64 bits
Performance Consideration
BigInteger operations are significantly slower than primitive arithmetic — each operation involves heap allocation and multi-word arithmetic. For numbers that fit in long, always prefer long. Use BigInteger only when values genuinely exceed the long range or when exact arbitrarily-large arithmetic is required.
Summary
Use BigInteger when values can overflow long — factorials, cryptographic keys, and combinatorial counts are classic examples. Create values with BigInteger.valueOf() for numbers within long range, or the String constructor for larger values. Remember that BigInteger is immutable: every arithmetic method returns a new object. Compare with equals() or compareTo(), never with ==.
No comments :
Post a Comment
Please leave your message queries or suggetions.
Note: Only a member of this blog may post a comment.