Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types). BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java.lang.Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

Semantics of arithmetic operations exactly mimic those of Java's integer arithmetic operators, as defined in The Java Language Specification. For example, division by zero throws an ArithmeticException, and division of a negative by a positive yields a negative (or zero) remainder. All of the details in the Spec concerning overflow are ignored, as BigIntegers are made as large as necessary to accommodate the results of an operation.

Semantics of shift operations extend those of Java's shift operators to allow for negative shift distances. A right-shift with a negative shift distance results in a left shift, and vice-versa. The unsigned right shift operator (>>>) is omitted, as this operation makes little sense in combination with the "infinite word size" abstraction provided by this class.

Semantics of bitwise logical operations exactly mimic those of Java's bitwise integer operators. The binary operators (and, or, xor) implicitly perform sign extension on the shorter of the two operands prior to performing the operation.

Comparison operations perform signed integer comparisons, analogous to those performed by Java's relational and equality operators.

Modular arithmetic operations are provided to compute residues, perform exponentiation, and compute multiplicative inverses. These methods always return a non-negative result, between 0 and (modulus - 1), inclusive.

Bit operations operate on a single bit of the two's-complement representation of their operand. If necessary, the operand is sign- extended so that it contains the designated bit. None of the single-bit operations can produce a BigInteger with a different sign from the BigInteger being operated on, as they affect only a single bit, and the "infinite word size" abstraction provided by this class ensures that there are infinitely many "virtual sign bits" preceding each BigInteger.

For the sake of brevity and clarity, pseudo-code is used throughout the descriptions of BigInteger methods. The pseudo-code expression (i + j) is shorthand for "a BigInteger whose value is that of the BigInteger i plus that of the BigInteger j." The pseudo-code expression (i == j) is shorthand for "true if and only if the BigInteger i represents the same value as the BigInteger j." Other pseudo-code expressions are interpreted similarly.

All methods and constructors in this class throw NullPointerException when passed a null object reference for any input parameter.

@version
1.70, 08/09/05
@author
Josh Bloch
@author
Michael McCloskey
@since
JDK1.1
See Also
Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger. The input array is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element.
Parameters
valbig-endian two's-complement binary representation of BigInteger.
Throws
NumberFormatExceptionval is zero bytes long.
Translates the sign-magnitude representation of a BigInteger into a BigInteger. The sign is represented as an integer signum value: -1 for negative, 0 for zero, or 1 for positive. The magnitude is a byte array in big-endian byte-order: the most significant byte is in the zeroth element. A zero-length magnitude array is permissible, and will result inin a BigInteger value of 0, whether signum is -1, 0 or 1.
Parameters
signumsignum of the number (-1 for negative, 0 for zero, 1 for positive).
magnitudebig-endian binary representation of the magnitude of the number.
Throws
NumberFormatExceptionsignum is not one of the three legal values (-1, 0, and 1), or signum is 0 and magnitude contains one or more non-zero bytes.
Translates the String representation of a BigInteger in the specified radix into a BigInteger. The String representation consists of an optional minus sign followed by a sequence of one or more digits in the specified radix. The character-to-digit mapping is provided by Character.digit. The String may not contain any extraneous characters (whitespace, for example).
Parameters
valString representation of BigInteger.
radixradix to be used in interpreting val.
Throws
NumberFormatExceptionval is not a valid representation of a BigInteger in the specified radix, or radix is outside the range from {@link Character#MIN_RADIX} to {@link Character#MAX_RADIX}, inclusive.
Translates the decimal String representation of a BigInteger into a BigInteger. The String representation consists of an optional minus sign followed by a sequence of one or more decimal digits. The character-to-digit mapping is provided by Character.digit. The String may not contain any extraneous characters (whitespace, for example).
Parameters
valdecimal String representation of BigInteger.
Throws
NumberFormatExceptionval is not a valid representation of a BigInteger.
Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2numBits - 1), inclusive. The uniformity of the distribution assumes that a fair source of random bits is provided in rnd. Note that this constructor always constructs a non-negative BigInteger.
Parameters
numBitsmaximum bitLength of the new BigInteger.
rndsource of randomness to be used in computing the new BigInteger.
Throws
IllegalArgumentExceptionnumBits is negative.
See Also
Constructs a randomly generated positive BigInteger that is probably prime, with the specified bitLength.

It is recommended that the probablePrime method be used in preference to this constructor unless there is a compelling need to specify a certainty.

Parameters
bitLengthbitLength of the returned BigInteger.
certaintya measure of the uncertainty that the caller is willing to tolerate. The probability that the new BigInteger represents a prime number will exceed (1 - 1/2certainty). The execution time of this constructor is proportional to the value of this parameter.
rndsource of random bits used to select candidates to be tested for primality.
Throws
ArithmeticExceptionbitLength < 2.
See Also
The BigInteger constant one.
@since
1.2
The BigInteger constant ten.
@since
1.5
The BigInteger constant zero.
@since
1.2
Returns a BigInteger whose value is the absolute value of this BigInteger.
Return
abs(this)
Returns a BigInteger whose value is (this + val).
Parameters
valvalue to be added to this BigInteger.
Return
this + val
Returns a BigInteger whose value is (this & val). (This method returns a negative BigInteger if and only if this and val are both negative.)
Parameters
valvalue to be AND'ed with this BigInteger.
Return
this & val
Returns a BigInteger whose value is (this & ~val). This method, which is equivalent to and(val.not()), is provided as a convenience for masking operations. (This method returns a negative BigInteger if and only if this is negative and val is positive.)
Parameters
valvalue to be complemented and AND'ed with this BigInteger.
Return
this & ~val
Returns the number of bits in the two's complement representation of this BigInteger that differ from its sign bit. This method is useful when implementing bit-vector style sets atop BigIntegers.
Return
number of bits in the two's complement representation of this BigInteger that differ from its sign bit.
Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit. For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. (Computes (ceil(log2(this < 0 ? -this : this+1))).)
Return
number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
Returns the value of the specified number as a byte. This may involve rounding or truncation.
Return
the numeric value represented by this object after conversion to type byte.
@since
JDK1.1
Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit cleared. (Computes (this & ~(1<<n)).)
Parameters
nindex of bit to clear.
Return
this & ~(1<<n)
Throws
ArithmeticExceptionn is negative.
Compares this BigInteger with the specified BigInteger. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.
Parameters
valBigInteger to which this BigInteger is to be compared.
Return
-1, 0 or 1 as this BigInteger is numerically less than, equal to, or greater than val.
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive. The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

Finally, the implementer must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

Parameters
othe Object to be compared.
Return
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Throws
ClassCastExceptionif the specified object's type prevents it from being compared to this Object.
Returns a BigInteger whose value is (this / val).
Parameters
valvalue by which this BigInteger is to be divided.
Return
this / val
Throws
ArithmeticExceptionval==0
Returns an array of two BigIntegers containing (this / val) followed by (this % val).
Parameters
valvalue by which this BigInteger is to be divided, and the remainder computed.
Return
an array of two BigIntegers: the quotient (this / val) is the initial element, and the remainder (this % val) is the final element.
Throws
ArithmeticExceptionval==0
Converts this BigInteger to a double. This conversion is similar to the narrowing primitive conversion from double to float defined in the Java Language Specification: if this BigInteger has too great a magnitude to represent as a double, it will be converted to Double#NEGATIVE_INFINITY or Double#POSITIVE_INFINITY as appropriate. Note that even when the return value is finite, this conversion can lose information about the precision of the BigInteger value.
Return
this BigInteger converted to a double.
Compares this BigInteger with the specified Object for equality.
Parameters
xObject to which this BigInteger is to be compared.
Return
true if and only if the specified Object is a BigInteger whose value is numerically equal to this BigInteger.
Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit flipped. (Computes (this ^ (1<<n)).)
Parameters
nindex of bit to flip.
Return
this ^ (1<<n)
Throws
ArithmeticExceptionn is negative.
Converts this BigInteger to a float. This conversion is similar to the narrowing primitive conversion from double to float defined in the Java Language Specification: if this BigInteger has too great a magnitude to represent as a float, it will be converted to Float#NEGATIVE_INFINITY or Float#POSITIVE_INFINITY as appropriate. Note that even when the return value is finite, this conversion can lose information about the precision of the BigInteger value.
Return
this BigInteger converted to a float.
Returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val). Returns 0 if this==0 && val==0.
Parameters
valvalue with which the GCD is to be computed.
Return
GCD(abs(this), abs(val))
Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Return
The java.lang.Class object that represents the runtime class of the object. The result is of type {@code Class} where X is the erasure of the static type of the expression on which getClass is called.
Returns the index of the rightmost (lowest-order) one bit in this BigInteger (the number of zero bits to the right of the rightmost one bit). Returns -1 if this BigInteger contains no one bits. (Computes (this==0? -1 : log2(this & -this)).)
Return
index of the rightmost one bit in this BigInteger.
Returns the hash code for this BigInteger.
Return
hash code for this BigInteger.
Converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int as defined in the Java Language Specification: if this BigInteger is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.
Return
this BigInteger converted to an int.
Returns true if this BigInteger is probably prime, false if it's definitely composite. If certainty is <= 0, true is returned.
Parameters
certaintya measure of the uncertainty that the caller is willing to tolerate: if the call returns true the probability that this BigInteger is prime exceeds (1 - 1/2certainty). The execution time of this method is proportional to the value of this parameter.
Return
true if this BigInteger is probably prime, false if it's definitely composite.
Converts this BigInteger to a long. This conversion is analogous to a narrowing primitive conversion from long to int as defined in the Java Language Specification: if this BigInteger is too big to fit in a long, only the low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.
Return
this BigInteger converted to a long.
Returns the maximum of this BigInteger and val.
Parameters
valvalue with which the maximum is to be computed.
Return
the BigInteger whose value is the greater of this and val. If they are equal, either may be returned.
Returns the minimum of this BigInteger and val.
Parameters
valvalue with which the minimum is to be computed.
Return
the BigInteger whose value is the lesser of this BigInteger and val. If they are equal, either may be returned.
Returns a BigInteger whose value is (this mod m). This method differs from remainder in that it always returns a non-negative BigInteger.
Parameters
mthe modulus.
Return
this mod m
Throws
ArithmeticExceptionm <= 0
See Also
Returns a BigInteger whose value is (this-1 mod m).
Parameters
mthe modulus.
Return
this-1 mod m.
Throws
ArithmeticException m <= 0, or this BigInteger has no multiplicative inverse mod m (that is, this BigInteger is not relatively prime to m).
Returns a BigInteger whose value is (thisexponent mod m). (Unlike pow, this method permits negative exponents.)
Parameters
exponentthe exponent.
mthe modulus.
Return
thisexponent mod m
Throws
ArithmeticExceptionm <= 0
See Also
Returns a BigInteger whose value is (this * val).
Parameters
valvalue to be multiplied by this BigInteger.
Return
this * val
Returns a BigInteger whose value is (-this).
Return
-this
Returns the first integer greater than this BigInteger that is probably prime. The probability that the number returned by this method is composite does not exceed 2-100. This method will never skip over a prime when searching: if it returns p, there is no prime q such that this < q < p.
Return
the first integer greater than this BigInteger that is probably prime.
Throws
ArithmeticExceptionthis < 0.
@since
1.5
Returns a BigInteger whose value is (~this). (This method returns a negative value if and only if this BigInteger is non-negative.)
Return
~this
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Returns a BigInteger whose value is (this | val). (This method returns a negative BigInteger if and only if either this or val is negative.)
Parameters
valvalue to be OR'ed with this BigInteger.
Return
this | val
Returns a BigInteger whose value is (thisexponent). Note that exponent is an integer rather than a BigInteger.
Parameters
exponentexponent to which this BigInteger is to be raised.
Return
thisexponent
Throws
ArithmeticExceptionexponent is negative. (This would cause the operation to yield a non-integer value.)
Returns a positive BigInteger that is probably prime, with the specified bitLength. The probability that a BigInteger returned by this method is composite does not exceed 2-100.
Parameters
bitLengthbitLength of the returned BigInteger.
rndsource of random bits used to select candidates to be tested for primality.
Return
a BigInteger of bitLength bits that is probably prime
Throws
ArithmeticExceptionbitLength < 2.
See Also
Returns a BigInteger whose value is (this % val).
Parameters
valvalue by which this BigInteger is to be divided, and the remainder computed.
Return
this % val
Throws
ArithmeticExceptionval==0
Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit set. (Computes (this | (1<<n)).)
Parameters
nindex of bit to set.
Return
this | (1<<n)
Throws
ArithmeticExceptionn is negative.
Returns a BigInteger whose value is (this << n). The shift distance, n, may be negative, in which case this method performs a right shift. (Computes floor(this * 2n).)
Parameters
nshift distance, in bits.
Return
this << n
See Also
Returns a BigInteger whose value is (this >> n). Sign extension is performed. The shift distance, n, may be negative, in which case this method performs a left shift. (Computes floor(this / 2n).)
Parameters
nshift distance, in bits.
Return
this >> n
See Also
Returns the value of the specified number as a short. This may involve rounding or truncation.
Return
the numeric value represented by this object after conversion to type short.
@since
JDK1.1
Returns the signum function of this BigInteger.
Return
-1, 0 or 1 as the value of this BigInteger is negative, zero or positive.
Returns a BigInteger whose value is (this - val).
Parameters
valvalue to be subtracted from this BigInteger.
Return
this - val
Returns true if and only if the designated bit is set. (Computes ((this & (1<<n)) != 0).)
Parameters
nindex of bit to test.
Return
true if and only if the designated bit is set.
Throws
ArithmeticExceptionn is negative.
Returns a byte array containing the two's-complement representation of this BigInteger. The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit, which is (ceil((this.bitLength() + 1)/8)). (This representation is compatible with the (byte[]) constructor.)
Return
a byte array containing the two's-complement representation of this BigInteger.
Returns the decimal String representation of this BigInteger. The digit-to-character mapping provided by Character.forDigit is used, and a minus sign is prepended if appropriate. (This representation is compatible with the (String) constructor, and allows for String concatenation with Java's + operator.)
Return
decimal String representation of this BigInteger.
Returns the String representation of this BigInteger in the given radix. If the radix is outside the range from Character#MIN_RADIX to Character#MAX_RADIX inclusive, it will default to 10 (as is the case for Integer.toString). The digit-to-character mapping provided by Character.forDigit is used, and a minus sign is prepended if appropriate. (This representation is compatible with the (String, int) constructor.)
Parameters
radixradix of the String representation.
Return
String representation of this BigInteger in the given radix.
Returns a BigInteger whose value is equal to that of the specified long. This "static factory method" is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers.
Parameters
valvalue of the BigInteger to return.
Return
a BigInteger with the specified value.
Causes current thread to wait until another thread invokes the method or the method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until either another thread invokes the method or the method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor.

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout);
         ... // Perform action appropriate to condition
     }
 
(For more information on this topic, see Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 2000), or Item 50 in Joshua Bloch's "Effective Java Programming Language Guide" (Addison-Wesley, 2001).

If the current thread is interrupted by another thread while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Parameters
timeoutthe maximum time to wait in milliseconds.
Throws
IllegalArgumentExceptionif the value of timeout is negative.
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until another thread invokes the method or the method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by:

 1000000*timeout+nanos

In all other respects, this method does the same thing as the method of one argument. In particular, wait(0, 0) means the same thing as wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

  • Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
  • The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout, nanos);
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Parameters
timeoutthe maximum time to wait in milliseconds.
nanosadditional time, in nanoseconds range 0-999999.
Throws
IllegalArgumentExceptionif the value of timeout is negative or the value of nanos is not in the range 0-999999.
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Returns a BigInteger whose value is (this ^ val). (This method returns a negative BigInteger if and only if exactly one of this and val are negative.)
Parameters
valvalue to be XOR'ed with this BigInteger.
Return
this ^ val