Is there an upper bound to BigInteger?
JavaBigintegerJava Problem Overview
> Possible Duplicate:
> What does BigInteger having no limit mean?
The Javadoc for BigInteger
does not define any maximum or minimum. However, it does say:
(emphasis added) > Immutable arbitrary-precision integers
Is there such a maximum, even in theory? Or is the way BigInteger
operates fundamentally different, such that there is in reality no maximum except for the amount of memory available on the computer?
Java Solutions
Solution 1 - Java
The number is held in an int[]
- the maximum size of an array is Integer.MAX_VALUE
. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE
.
Admittedly, this is implementation dependent, not part of the specification.
In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:
> BigInteger
must support values in the range -2
Integer.MAX_VALUE
(exclusive) to +2
Integer.MAX_VALUE
(exclusive) and may support values outside of that range.
>
> Implementation note: BigInteger
constructors and operations throw ArithmeticException
when the result is out of the supported range of -2
Integer.MAX_VALUE
(exclusive) to +2
Integer.MAX_VALUE
(exclusive).
Solution 2 - Java
> BigInteger would only be used if you know it will not be a decimal and > there is a possibility of the long data type not being large enough. > BigInteger has no cap on its max size (as large as the RAM on the > computer can hold).
From here.
It is implemented using an int[]
:
110 /**
111 * The magnitude of this BigInteger, in <i>big-endian</i> order: the
112 * zeroth element of this array is the most-significant int of the
113 * magnitude. The magnitude must be "minimal" in that the most-significant
114 * int ({@code mag[0]}) must be non-zero. This is necessary to
115 * ensure that there is exactly one representation for each BigInteger
116 * value. Note that this implies that the BigInteger zero has a
117 * zero-length mag array.
118 */
119 final int[] mag;
From the source
From the Wikipedia article Arbitrary-precision arithmetic:
> Several modern programming languages have built-in support for > bignums, and others have libraries available for arbitrary-precision > integer and floating-point math. Rather than store values as a fixed > number of binary bits related to the size of the processor register, > these implementations typically use variable-length arrays of digits.
Solution 3 - Java
The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.