BigInteger

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.std.math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

<p>Semantics of arithmetic operations exactly mimic those of Java's integer arithmetic operators, as defined in <i>The Java Language Specification</i>. For example, division by zero throws an {@code 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.

<p>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 ({@code >>>}) is omitted, as this operation makes little sense in combination with the "infinite word size" abstraction provided by this class.

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

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

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

<p>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.

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

<p>All methods and constructors in this class throw {@code NullPointerException} when passed a null object reference for any input parameter.

BigInteger must support values in the range -2<sup>{@code int.max}</sup> (exclusive) to +2<sup>{@code int.max}</sup> (exclusive) and may support values outside of that range.

The range of probable prime values is limited and may be less than the full supported positive range of {@code BigInteger}. The range must be at least 1 to 2<sup>500000000</sup>.

@implNote BigInteger constructors and operations throw {@code ArithmeticException} when the result is out of the supported range of -2<sup>{@code int.max}</sup> (exclusive) to +2<sup>{@code int.max}</sup> (exclusive).

@see BigDecimal @jls 4.2.2 Integer Operations @author Josh Bloch @author Michael McCloskey @author Alan Eliasen @author Timothy Buktu

class BigInteger : Number {}

Constructors

this
this(byte[] val, int off, int len)

Translates a byte sub-array containing the two's-complement binary representation of a BigInteger into a BigInteger. The sub-array is specified via an offset into the array and a length. The sub-array is assumed to be in <i>big-endian</i> byte-order: the most significant byte is the element at index {@code off}. The {@code val} array is assumed to be unchanged for the duration of the constructor call.

this
this(byte[] val)

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 <i>big-endian</i> byte-order: the most significant byte is in the zeroth element. The {@code val} array is assumed to be unchanged for the duration of the constructor call.

this
this(int signum, byte[] magnitude, int off, int len)

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 sub-array of a byte array in <i>big-endian</i> byte-order: the most significant byte is the element at index {@code off}. A zero value of the length {@code len} is permissible, and will result in a BigInteger value of 0, whether signum is -1, 0 or 1. The {@code magnitude} array is assumed to be unchanged for the duration of the constructor call.

this
this(int signum, byte[] magnitude)

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 <i>big-endian</i> byte-order: the most significant byte is the zeroth element. A zero-length magnitude array is permissible, and will result in a BigInteger value of 0, whether signum is -1, 0 or 1. The {@code magnitude} array is assumed to be unchanged for the duration of the constructor call.

this
this(string val, int radix)

Translates the string representation of a BigInteger in the specified radix into a BigInteger. The string representation consists of an optional minus or plus sign followed by a sequence of one or more digits in the specified radix. The character-to-digit mapping is provided by {@code CharacterHelper.digit}. The string may not contain any extraneous characters (whitespace, for example).

this
this(char[] val, int sign, int len)
Undocumented in source.
this
this(string val)

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 {@code CharacterHelper.digit}. The string may not contain any extraneous characters (whitespace, for example).

this
this(int numBits, Random* rnd)

Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2<sup>{@code numBits}</sup> - 1), inclusive. The uniformity of the distribution assumes that a fair source of random bits is provided in {@code rnd}. Note that this constructor always constructs a non-negative BigInteger.

this
this(int bitLength, int certainty, Random* rnd)

Constructs a randomly generated positive BigInteger that is probably prime, with the specified bitLength.

this
this(int[] magnitude, int signum)

This internal constructor differs from its cousin with the arguments reversed in two ways: it assumes that its arguments are correct, and it doesn't copy the magnitude array.

Members

Functions

abs
BigInteger abs()

Returns a BigInteger whose value is the absolute value of this BigInteger.

add
BigInteger add(BigInteger val)

Returns a BigInteger whose value is {@code (this + val)}.

add
BigInteger add(long val)

Package private methods used by BigDecimal code to add a BigInteger with a long. Assumes val is not equal to INFLATED.

and
BigInteger and(BigInteger val)

Returns a BigInteger whose value is {@code (this & val)}. (This method returns a negative BigInteger if and only if this and val are both negative.)

andNot
BigInteger andNot(BigInteger val)

Returns a BigInteger whose value is {@code (this & ~val)}. This method, which is equivalent to {@code and(val.not())}, is provided as a convenience for masking operations. (This method returns a negative BigInteger if and only if {@code this} is negative and {@code val} is positive.)

bitCount
int bitCount()

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.

bitLength
int bitLength()

Returns the number of bits in the minimal two's-complement representation of this BigInteger, <em>excluding</em> a sign bit. For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. (Computes {@code (ceil(log2(this < 0 ? -this : this+1)))}.)

byteValue
byte byteValue()
Undocumented in source. Be warned that the author may not have intended to support it.
byteValueExact
byte byteValueExact()

Converts this {@code BigInteger} to a {@code byte}, checking for lost information. If the value of this {@code BigInteger} is out of the range of the {@code byte} type, then an {@code ArithmeticException} is thrown.

clearBit
BigInteger clearBit(int n)

Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit cleared. (Computes {@code (this & ~(1<<n))}.)

compareMagnitude
int compareMagnitude(BigInteger val)

Compares the magnitude array of this BigInteger with the specified BigInteger's. This is the version of compareTo ignoring sign.

compareMagnitude
int compareMagnitude(long val)

Version of compareMagnitude that compares magnitude with long value. val can't be long.min.

compareTo
int compareTo(BigInteger val)

Compares this BigInteger with the specified BigInteger. This method is provided in preference to individual methods for each of the six bool comparison operators ({@literal <}, ==, {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested idiom for performing these comparisons is: {@code (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where &lt;<i>op</i>&gt; is one of the six comparison operators.

divide
BigInteger divide(BigInteger val)

Returns a BigInteger whose value is {@code (this / val)}.

divideAndRemainder
BigInteger[] divideAndRemainder(BigInteger val)

Returns an array of two BigIntegers containing {@code (this / val)} followed by {@code (this % val)}.

doubleValue
double doubleValue()

Converts this BigInteger to a {@code double}. This conversion is similar to the <i>narrowing primitive conversion</i> from {@code double} to {@code float} as defined in <cite>The Java&trade; Language Specification</cite>: if this BigInteger has too great a magnitude to represent as a {@code double}, it will be converted to {@link Double#NEGATIVE_INFINITY} or {@link 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.

equals
bool equals(Object x)

Compares this BigInteger with the specified Object for equality.

flipBit
BigInteger flipBit(int n)

Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit flipped. (Computes {@code (this ^ (1<<n))}.)

floatValue
float floatValue()

Converts this BigInteger to a {@code float}. This conversion is similar to the <i>narrowing primitive conversion</i> from {@code double} to {@code float} as defined in <cite>The Java&trade; Language Specification</cite>: if this BigInteger has too great a magnitude to represent as a {@code float}, it will be converted to {@link Float#NEGATIVE_INFINITY} or {@link 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.

gcd
BigInteger gcd(BigInteger val)

Returns a BigInteger whose value is the greatest common divisor of {@code abs(this)} and {@code abs(val)}. Returns 0 if {@code this == 0 && val == 0}.

getLowestSetBit
int getLowestSetBit()

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 {@code (this == 0? -1 : log2(this & -this))}.)

hashCode
size_t hashCode()

Returns the hash code for this BigInteger.

intValue
int intValue()

Converts this BigInteger to an {@code int}. This conversion is analogous to a <i>narrowing primitive conversion</i> from {@code long} to {@code int} as defined in <cite>The Java&trade; Language Specification</cite>: if this BigInteger is too big to fit in an {@code 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.

intValueExact
int intValueExact()

Converts this {@code BigInteger} to an {@code int}, checking for lost information. If the value of this {@code BigInteger} is out of the range of the {@code int} type, then an {@code ArithmeticException} is thrown.

isProbablePrime
bool isProbablePrime(int certainty)

Returns {@code true} if this BigInteger is probably prime, {@code false} if it's definitely composite. If {@code certainty} is &le; 0, {@code true} is returned.

javaIncrement
int[] javaIncrement(int[] val)
Undocumented in source. Be warned that the author may not have intended to support it.
longValue
long longValue()

Converts this BigInteger to a {@code long}. This conversion is analogous to a <i>narrowing primitive conversion</i> from {@code long} to {@code int} as defined in <cite>The Java&trade; Language Specification</cite>: if this BigInteger is too big to fit in a {@code 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.

longValueExact
long longValueExact()

Converts this {@code BigInteger} to a {@code long}, checking for lost information. If the value of this {@code BigInteger} is out of the range of the {@code long} type, then an {@code ArithmeticException} is thrown.

max
BigInteger max(BigInteger val)

Returns the maximum of this BigInteger and {@code val}.

min
BigInteger min(BigInteger val)

Returns the minimum of this BigInteger and {@code val}.

mod
BigInteger mod(BigInteger m)

Returns a BigInteger whose value is {@code (this mod m}). This method differs from {@code remainder} in that it always returns a <i>non-negative</i> BigInteger.

modInverse
BigInteger modInverse(BigInteger m)

Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}.

modPow
BigInteger modPow(BigInteger exponent, BigInteger m)

Returns a BigInteger whose value is <code>(this<sup>exponent</sup> mod m)</code>. (Unlike {@code pow}, this method permits negative exponents.)

multiply
BigInteger multiply(BigInteger val)

Returns a BigInteger whose value is {@code (this * val)}.

multiply
BigInteger multiply(long v)

Package private methods used by BigDecimal code to multiply a BigInteger with a long. Assumes v is not equal to INFLATED.

negate
BigInteger negate()

Returns a BigInteger whose value is {@code (-this)}.

nextProbablePrime
BigInteger nextProbablePrime()

Returns the first integer greater than this {@code BigInteger} that is probably prime. The probability that the number returned by this method is composite does not exceed 2<sup>-100</sup>. This method will never skip over a prime when searching: if it returns {@code p}, there is no prime {@code q} such that {@code this < q < p}.

not
BigInteger not()

Returns a BigInteger whose value is {@code (~this)}. (This method returns a negative value if and only if this BigInteger is non-negative.)

opEquals
bool opEquals(Object x)
Undocumented in source. Be warned that the author may not have intended to support it.
or
BigInteger or(BigInteger val)

Returns a BigInteger whose value is {@code (this | val)}. (This method returns a negative BigInteger if and only if either this or val is negative.)

pow
BigInteger pow(int exponent)

Returns a BigInteger whose value is <code>(this<sup>exponent</sup>)</code>. Note that {@code exponent} is an integer rather than a BigInteger.

primeToCertainty
bool primeToCertainty(int certainty, Random* random)

Returns {@code true} if this BigInteger is probably prime, {@code false} if it's definitely composite.

remainder
BigInteger remainder(BigInteger val)

Returns a BigInteger whose value is {@code (this % val)}.

setBit
BigInteger setBit(int n)

Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit set. (Computes {@code (this | (1<<n))}.)

shiftLeft
BigInteger shiftLeft(int n)

Returns a BigInteger whose value is {@code (this << n)}. The shift distance, {@code n}, may be negative, in which case this method performs a right shift. (Computes <code>floor(this * 2<sup>n</sup>)</code>.)

shiftRight
BigInteger shiftRight(int n)

Returns a BigInteger whose value is {@code (this >> n)}. Sign extension is performed. The shift distance, {@code n}, may be negative, in which case this method performs a left shift. (Computes <code>floor(this / 2<sup>n</sup>)</code>.)

shortValue
short shortValue()
Undocumented in source. Be warned that the author may not have intended to support it.
shortValueExact
short shortValueExact()

Converts this {@code BigInteger} to a {@code short}, checking for lost information. If the value of this {@code BigInteger} is out of the range of the {@code short} type, then an {@code ArithmeticException} is thrown.

signum
int signum()

Returns the signum function of this BigInteger.

sqrt
BigInteger sqrt()

Returns the integer square root of this BigInteger. The integer square root of the corresponding mathematical integer {@code n} is the largest mathematical integer {@code s} such that {@code s*s <= n}. It is equal to the value of {@code floor(sqrt(n))}, where {@code sqrt(n)} denotes the real square root of {@code n} treated as a real. Note that the integer square root will be less than the real square root if the latter is not representable as an integral value.

sqrtAndRemainder
BigInteger[] sqrtAndRemainder()

Returns an array of two BigIntegers containing the integer square root {@code s} of {@code this} and its remainder {@code this - s*s}, respectively.

subtract
BigInteger subtract(BigInteger val)

Returns a BigInteger whose value is {@code (this - val)}.

testBit
bool testBit(int n)

Returns {@code true} if and only if the designated bit is set. (Computes {@code ((this & (1<<n)) != 0)}.)

toByteArray
byte[] toByteArray()

Returns a byte array containing the two's-complement representation of this BigInteger. The byte array will be in <i>big-endian</i> 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 {@code (ceil((this.bitLength() + 1)/8))}. (This representation is compatible with the {@link #BigInteger(byte[]) (byte[])} constructor.)

toHash
size_t toHash()
Undocumented in source. Be warned that the author may not have intended to support it.
toString
string toString(int radix)

Returns the string representation of this BigInteger in the given radix. If the radix is outside the range from {@link Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive, it will default to 10 (as is the case for {@code Integer.toString}). The digit-to-character mapping provided by {@code Char.forDigit} is used, and a minus sign is prepended if appropriate. (This representation is compatible with the {@link #BigInteger(string, int) (string, int)} constructor.)

toString
string toString()

Returns the decimal string representation of this BigInteger. The digit-to-character mapping provided by {@code Char.forDigit} is used, and a minus sign is prepended if appropriate. (This representation is compatible with the {@link #BigInteger(string) (string)} constructor, and allows for string concatenation with Java's + operator.)

xor
BigInteger xor(BigInteger val)

Returns a BigInteger whose value is {@code (this ^ val)}. (This method returns a negative BigInteger if and only if exactly one of this and val are negative.)

Static functions

addOne
int addOne(int[] a, int offset, int mlen, int carry)

Add one word to the number a mlen words into a. Return the resulting carry.

bitLengthForInt
int bitLengthForInt(int n)

Package private method to return bit length for an integer.

mulAdd
int mulAdd(int[] ot, int[] input, int offset, int len, int k)

Multiply an array by one word k and add to result, return the carry

primitiveLeftShift
void primitiveLeftShift(int[] a, int len, int n)
Undocumented in source. Be warned that the author may not have intended to support it.
primitiveRightShift
void primitiveRightShift(int[] a, int len, int n)
Undocumented in source. Be warned that the author may not have intended to support it.
valueOf
BigInteger valueOf(long val)

Returns a BigInteger whose value is equal to that of the specified {@code long}.

Static variables

ONE
BigInteger ONE;

The BigInteger constant one.

TEN
BigInteger TEN;

The BigInteger constant ten.

TWO
BigInteger TWO;

The BigInteger constant two.

ZERO
BigInteger ZERO;

The BigInteger constant zero.

Variables

BURNIKEL_ZIEGLER_OFFSET
enum int BURNIKEL_ZIEGLER_OFFSET;

The offset value for using Burnikel-Ziegler division. If the number of ints in the divisor exceeds the Burnikel-Ziegler threshold, and the number of ints in the dividend is greater than the number of ints in the divisor plus this value, Burnikel-Ziegler division will be used. This value is found experimentally to work well.

BURNIKEL_ZIEGLER_THRESHOLD
enum int BURNIKEL_ZIEGLER_THRESHOLD;

The threshold value for using Burnikel-Ziegler division. If the number of ints in the divisor are larger than this value, Burnikel-Ziegler division may be used. This value is found experimentally to work well.

LONG_MASK
enum long LONG_MASK;

This mask is used to obtain the value of an int as if it were unsigned.

bnExpModThreshTable
enum int[] bnExpModThreshTable;
Undocumented in source.

Inherited Members

From Number

intValue
int intValue()

Returns the value of the specified number as an {@code int}.

longValue
long longValue()

Returns the value of the specified number as a {@code long}.

floatValue
float floatValue()

Returns the value of the specified number as a {@code float}.

doubleValue
double doubleValue()

Returns the value of the specified number as a {@code double}.

byteValue
byte byteValue()

Returns the value of the specified number as a {@code byte}.

shortValue
short shortValue()

Returns the value of the specified number as a {@code short}.

toString
string toString()
Undocumented in source.

Meta