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.
- Author(s):
- Josh Bloch
- Michael McCloskey
- Since:
- JDK1.1
- See also:
BigDecimal
The signum of this BigInteger: -1 for negative, 0 for zero, or
1 for positive. Note that the BigInteger zero
must have
a signum of 0. This is necessary to ensures that there is exactly one
representation for each BigInteger value.
The magnitude of this BigInteger, in
big-endian order: the
zeroth element of this array is the most-significant int of the
magnitude. The magnitude must be "minimal" in that the most-significant
int (
mag[0]) must be non-zero. This is necessary to
ensure that there is exactly one representation for each BigInteger
value. Note that this implies that the BigInteger zero has a
zero-length mag array.
The bitCount of this BigInteger, as returned by bitCount(), or -1
(either value is acceptable).
The bitLength of this BigInteger, as returned by bitLength(), or -1
(either value is acceptable).
The lowest set bit of this BigInteger, as returned by getLowestSetBit(),
or -2 (either value is acceptable).
The index of the lowest-order byte in the magnitude of this BigInteger
that contains a nonzero byte, or -2 (either value is acceptable). The
least significant byte has int-number 0, the next byte in order of
increasing significance has byte-number 1, and so forth.
The index of the lowest-order int in the magnitude of this BigInteger
that contains a nonzero int, or -2 (either value is acceptable). The
least significant int has int-number 0, the next int in order of
increasing significance has int-number 1, and so forth.
This mask is used to obtain the value of an int as if it were unsigned.
private final static long LONG_MASK = 0xffffffffL;
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.
This private constructor translates an int array containing the
two's-complement binary representation of a BigInteger into a
BigInteger. The input array is assumed to be in
big-endian
int-order: the most significant int is in the zeroth element.
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 in a BigInteger value of 0, whether signum is -1, 0 or 1.
- Parameters:
signum signum of the number (-1 for negative, 0 for zero, 1
for positive).magnitude big-endian binary representation of the magnitude of
the number.- Throws:
java.lang.NumberFormatException signum 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.
if (signum < -1 || signum > 1)
if (this.mag.length==0) { A constructor for internal use that translates the sign-magnitude
representation of a BigInteger into a BigInteger. It checks the
arguments and copies the magnitude so this constructor would be
safe for external use.
if (signum < -1 || signum > 1)
if (this.mag.length==0) { Translates the String representation of a BigInteger in the
specified radix into a BigInteger. The String representation
consists of an optional minus 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).
int cursor = 0, numDigits;
numDigits = len - cursor;
int numBits = (int)(((numDigits * bitsPerDigit[radix]) >>> 10) + 1);
int numWords = (numBits + 31) /32;
while (cursor < val.length()) { groupVal = Integer.parseInt(group, radix);
int cursor = 0, numDigits;
while (cursor < len && Character.digit(val[cursor], 10) == 0)
numDigits = len - cursor;
int numBits = (int)(((numDigits * bitsPerDigit[10]) >>> 10) + 1);
numWords = (numBits + 31) /32;
private int parseInt(char[] source, int start, int end) { int result = Character.digit(source[start++], 10);
for (int index = start; index<end; index++) { int nextVal = Character.digit(source[index], 10);
result = 10*result + nextVal;
1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
for (int i = len-1; i >= 0; i--) { product = ylong * (x[i] & LONG_MASK) + carry;
for (int i = len-2; i >= 0; i--) { 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).
Constructs a randomly generated BigInteger, uniformly distributed over
the range
0 to (2
numBits - 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.
int numBytes = (int)(((long)numBits+7)/8);
byte[] randomBits = new byte[numBytes];
int excessBits = 8*numBytes - numBits;
randomBits[0] &= (1 << (8-excessBits)) - 1;
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:
bitLength bitLength of the returned BigInteger.certainty a 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.rnd source of random bits used to select candidates to be
tested for primality.- Throws:
java.lang.ArithmeticException bitLength < 2.- See also:
bitLength()
prime = (bitLength < 95 ? smallPrime(bitLength, certainty, rnd)
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:
bitLength bitLength of the returned BigInteger.rnd source of random bits used to select candidates to be
tested for primality.- Returns:
- a BigInteger of
bitLength bits that is probably prime - Throws:
java.lang.ArithmeticException bitLength < 2.- Since:
- 1.4
- See also:
bitLength()
Find a random number of the specified bitLength that is probably prime.
This method is used for smaller primes, its performance degrades on
larger bitlengths.
This method assumes bitLength > 1.
int magLen = (bitLength + 31) >>> 5;
int temp[] = new int[magLen];
int highBit = 1 << ((bitLength+31) & 0x1f);
int highMask = (highBit << 1) - 1;
for (int i=0; i<magLen; i++)
temp[0] = (temp[0] & highMask) | highBit;
if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
(r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
(r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
= valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
Find a random number of the specified bitLength that is probably prime.
This method is more appropriate for larger bitlengths since it uses
a sieve to eliminate most composites before using a more expensive
test.
p.mag[p.mag.length-1] &= 0xfffffffe;
int searchLen = (bitLength / 20) * 64;
while ((candidate == null) || (candidate.bitLength() != bitLength)) { p.mag[p.mag.length-1] &= 0xfffffffe;
searchSieve = new BitSieve(p, searchLen);
candidate = searchSieve.retrieve(p, certainty, rnd);
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.
if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
(r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
(r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) { int searchLen = (result.bitLength() / 20) * 64;
result = result.add(BigInteger.valueOf(2 * searchLen));
Returns
true if this BigInteger is probably prime,
false if it's definitely composite.
This method assumes bitLength > 2.
- Parameters:
certainty a 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/2<sup>certainty</sup>). The execution time of
this method is proportional to the value of this parameter.- Returns:
true if this BigInteger is probably prime,
false if it's definitely composite.
rounds = n < rounds ? n : rounds;
} else if (sizeInBits < 512) { } else if (sizeInBits < 768) { } else if (sizeInBits < 1024) { rounds = n < rounds ? n : rounds;
Returns true iff this BigInteger is a Lucas-Lehmer probable prime.
The following assumptions are made:
This BigInteger is a positive, odd number.
d = (d<0) ? Math.abs(d)+2 : -(d+2);
Computes Jacobi(p,n).
Assumes n positive, odd, n>=3.
int u = n.mag[n.mag.length-1];
if ((n8 == 3) || (n8 == 7))
if (((u ^ (u>>1)) & 2) != 0)
if (((p ^ (p>>1)) & 2) != 0)
Returns true iff this BigInteger passes the specified number of
Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
186-2).
The following assumptions are made:
This BigInteger is a positive, odd number greater than 2.
iterations<=50.
for (int i=0; i<iterations; i++) { This private constructor differs from its public cousin
with the arguments reversed in two ways: it assumes that its
arguments are correct, and it doesn't copy the magnitude array.
this.signum = (magnitude.length==0 ? 0 : signum);
This private constructor is for internal use and assumes that its
arguments are correct.
private BigInteger(byte[] magnitude, int signum) { this.signum = (magnitude.length==0 ? 0 : signum);
This private constructor is for internal use in converting
from a MutableBigInteger object into a BigInteger.
if (val.offset > 0 || val.value.length != val.intLen) { mag = new int[val.intLen];
for(int i=0; i<val.intLen; i++)
mag[i] = val.value[val.offset+i];
this.signum = (val.intLen == 0) ? 0 : sign;
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:
val value of the BigInteger to return.- Returns:
- a BigInteger with the specified value.
Constructs a BigInteger with the specified value, which may not be zero.
int highWord = (int)(val >>> 32);
Returns a BigInteger with the given two's complement representation.
Assumes that the input array will not be modified (the returned
BigInteger will reference the input array if feasible).
Initialize static constant array when class is loaded.
int[] magnitude = new int[1];
The BigInteger constant zero.
The BigInteger constant one.
The BigInteger constant two. (Not exported.)
The BigInteger constant ten.
Returns a BigInteger whose value is
(this + val).
- Parameters:
val value to be added to this BigInteger.- Returns:
this + val
Adds the contents of the int arrays x and y. This method allocates
a new int array to hold the answer and returns a reference to that
array.
private static int[] add(int[] x, int[] y) { if (x.length < y.length) { int result[] = new int[xIndex];
result[xIndex] = (int)sum;
boolean carry = (sum >>> 32 != 0);
while (xIndex > 0 && carry)
carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
result[--xIndex] = x[xIndex];
int newLen = result.length + 1;
int temp[] = new int[newLen];
for (int i = 1; i<newLen; i++)
Returns a BigInteger whose value is
(this - val).
- Parameters:
val value to be subtracted from this BigInteger.- Returns:
this - val
Subtracts the contents of the second int arrays (little) from the
first (big). The first int array (big) must represent a larger number
than the second. This method allocates the space necessary to hold the
answer.
private static int[] subtract(int[] big, int[] little) { int bigIndex = big.length;
int result[] = new int[bigIndex];
int littleIndex = little.length;
result[bigIndex] = (int)difference;
boolean borrow = (difference >> 32 != 0);
while (bigIndex > 0 && borrow)
borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
result[--bigIndex] = big[bigIndex];
Returns a BigInteger whose value is
(this * val).
- Parameters:
val value to be multiplied by this BigInteger.- Returns:
this * val
if (val.signum == 0 || signum == 0)
val.mag, val.mag.length, null);
Multiplies int arrays x and y to the specified lengths and places
the result into z.
private int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) { if (z == null || z.length < (xlen+ ylen))
for (int j=ystart, k=ystart+1+xstart; j>=0; j--, k--) { for (int i = xstart-1; i >= 0; i--) { for (int j=ystart, k=ystart+1+i; j>=0; j--, k--) { Returns a BigInteger whose value is
(this<sup>2</sup>).
Squares the contents of the int array x. The result is placed into the
int array z. The contents of x are not changed.
private static final int[] squareToLen(int[] x, int len, int[] z) { if (z == null || z.length < zlen)
int lastProductLowWord = 0;
for (int j=0, i=0; j<len; j++) { long product = piece * piece;
z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);
z[i++] = (int)(product >>> 1);
lastProductLowWord = (int)product;
for (int i=len, offset=1; i>0; i--, offset+=2) { t = mulAdd(z, x, offset, i-1, t);
z[zlen-1] |= x[len-1] & 1;
Returns a BigInteger whose value is
(this / val).
Returns an array of two BigIntegers containing
(this / val)
followed by
(this % val).
- Parameters:
val value by which this BigInteger is to be divided, and the
remainder computed.- Returns:
- an array of two BigIntegers: the quotient
(this / val)
is the initial element, and the remainder (this % val)
is the final element. - Throws:
java.lang.ArithmeticException val==0
Returns a BigInteger whose value is
(this % val).
- Parameters:
val value by which this BigInteger is to be divided, and the
remainder computed.- Returns:
this % val- Throws:
java.lang.ArithmeticException val==0
Returns a BigInteger whose value is
(thisexponent).
Note that
exponent is an integer rather than a BigInteger.
- Parameters:
exponent exponent to which this BigInteger is to be raised.- Returns:
- thisexponent
- Throws:
java.lang.ArithmeticException exponent is negative. (This would
cause the operation to yield a non-integer value.)
return (exponent==0 ? ONE : this);
int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
int[] baseToPow2 = this.mag;
baseToPow2, baseToPow2.length, null);
if ((exponent >>>= 1) != 0) { baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null);
Returns a BigInteger whose value is the greatest common divisor of
abs(this) and
abs(val). Returns 0 if
this==0 && val==0.
- Parameters:
val value with which the GCD is to be computed.- Returns:
GCD(abs(this), abs(val))
Left shift int array a up to len by n bits. Returns the array that
results from the shift since space may have to be reallocated.
private static int[] leftShift(int[] a, int len, int n) { int bitsInHighWord = bitLen(a[0]);
if (n <= (32-bitsInHighWord)) { if (nBits <= (32-bitsInHighWord)) { int result[] = new int[nInts+len];
for (int i=0; i<len; i++)
int result[] = new int[nInts+len+1];
for (int i=0; i<len; i++)
for (int i=len-1, c=a[i]; i>0; i--) { a[i] = (c << n2) | (b >>> n);
for (int i=0, c=a[i], m=i+len-1; i<m; i++) { a[i] = (b << n) | (c >>> n2);
Calculate bitlength of contents of the first len elements an int array,
assuming there are no leading zero ints.
private static int bitLength(int[] val, int len) { return ((len-1)<<5) + bitLen(val[0]);
Returns a BigInteger whose value is the absolute value of this
BigInteger.
Returns a BigInteger whose value is
(-this).
Returns the signum function of this BigInteger.
- Returns:
- -1, 0 or 1 as the value of this BigInteger is negative, zero or
positive.
Returns a BigInteger whose value is
(this mod m). This method
differs from
remainder in that it always returns a
non-negative BigInteger.
return (result.signum >= 0 ? result : result.add(m));
Returns a BigInteger whose value is
(thisexponent mod m). (Unlike
pow, this
method permits negative exponents.)
if (exponent.signum == 0)
if ((invertResult = (exponent.signum < 0)))
return (invertResult ? result.modInverse(m) : result);
Returns a BigInteger whose value is x to the power of y mod z.
Assumes: z is odd && x < z.
if ((ebits != 17) || (exp[0] != 65537)) { int tblmask = 1 << wbits;
int[][] table = new int[tblmask][];
for (int i=0; i<tblmask; i++)
table[i] = new int[modLen];
int[] a = leftShift(base, base.length, modLen << 5);
if (table[0].length < modLen) { int offset = modLen - table[0].length;
int[] t2 = new int[modLen];
for (int i=0; i<table[0].length; i++)
t2[i+offset] = table[0][i];
int[] t = new int[modLen];
for(int i=0; i<modLen; i++)
for (int i=1; i<tblmask; i++) { int bitpos = 1 << ((ebits-1) & (32-1));
for (int i = 0; i <= wbits; i++) { buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);
int[] mult = table[buf >>> 1];
buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
if ((buf & tblmask) != 0) { int[] t2 = new int[2*modLen];
for(int i=0; i<modLen; i++)
for(int i=0; i<modLen; i++)
Montgomery reduce n, modulo mod. This reduces modulo mod and divides
by 2^(32*mlen). Adapted from Colin Plumb's C library.
private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) { int nEnd = n[n.length-1-offset];
int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
c += addOne(n, offset, mlen, carry);
for (int i=0; i<len; i++) { Subtracts two numbers of same length, returning borrow.
private static int subN(int[] a, int[] b, int len) { Multiply an array by one word k and add to result, return the carry
static int mulAdd(int[] out, int[] in, int offset, int len, int k) { offset = out.length-offset - 1;
for (int j=len-1; j >= 0; j--) { out[offset--] = (int)product;
Add one word to the number a mlen words into a. Return the resulting
carry.
static int addOne(int[] a, int offset, int mlen, int carry) { offset = a.length-1-mlen-offset;
Returns a BigInteger whose value is (this ** exponent) mod (2**p)
limit = (p-1) < limit ? (p-1) : limit;
while (expOffset < limit) { Returns a BigInteger whose value is this mod(2**p).
Assumes that this
BigInteger >= 0 and
p > 0.
int[] mag = new int[numInts];
for (int i=0; i<numInts; i++)
mag[i] = this.mag[i + (this.mag.length - numInts)];
int excessBits = (numInts << 5) - p;
mag[0] &= (1L << (32-excessBits)) - 1;
Returns a BigInteger whose value is
(this-1 mod m).
- Parameters:
m the modulus.- Returns:
this-1 mod m.- Throws:
java.lang.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
(this << n).
The shift distance,
n, may be negative, in which case
this method performs a right shift.
(Computes
floor(this * 2n).)
- Parameters:
n shift distance, in bits.- Returns:
this << n- See also:
shiftRight(int)
newMag = new int[magLen + nInts];
for (int i=0; i<magLen; i++)
int highBits = mag[0] >>> nBits2;
newMag = new int[magLen + nInts + 1];
newMag = new int[magLen + nInts];
newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2;
newMag[i] = mag[j] << nBits;
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:
n shift distance, in bits.- Returns:
this >> n- See also:
shiftLeft(int)
int newMagLen = magLen - nInts;
newMag = new int[newMagLen];
for (int i=0; i<newMagLen; i++)
int highBits = mag[0] >>> nBits;
newMag = new int[magLen - nInts];
newMag = new int[magLen - nInts -1];
while (j < magLen - nInts - 1)
newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits);
boolean onesLost = false;
for (int i=magLen-1, j=magLen-nInts; i>=j && !onesLost; i--)
onesLost = (mag[i] != 0);
if (!onesLost && nBits != 0)
onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
for (int i=val.length-1; i >= 0 && lastSum == 0; i--)
val = new int[val.length+1];
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:
val value to be AND'ed with this BigInteger.- Returns:
this & val
for (int i=0; i<result.length; i++)
result[i] = (getInt(result.length-i-1)
& val.getInt(result.length-i-1));
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:
val value to be OR'ed with this BigInteger.- Returns:
this | val
for (int i=0; i<result.length; i++)
result[i] = (getInt(result.length-i-1)
| val.getInt(result.length-i-1));
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:
val value to be XOR'ed with this BigInteger.- Returns:
this ^ val
for (int i=0; i<result.length; i++)
result[i] = (getInt(result.length-i-1)
^ val.getInt(result.length-i-1));
Returns a BigInteger whose value is
(~this). (This method
returns a negative value if and only if this BigInteger is
non-negative.)
for (int i=0; i<result.length; i++)
result[i] = ~getInt(result.length-i-1);
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:
val value to be complemented and AND'ed with this BigInteger.- Returns:
this & ~val
for (int i=0; i<result.length; i++)
result[i] = (getInt(result.length-i-1)
& ~val.getInt(result.length-i-1));
Returns
true if and only if the designated bit is set.
(Computes
((this & (1<<n)) != 0).)
return (getInt(n/32) & (1 << (n%32))) != 0;
Returns a BigInteger whose value is equivalent to this BigInteger
with the designated bit set. (Computes
(this | (1<<n)).)
for (int i=0; i<result.length; i++)
result[result.length-i-1] = getInt(i);
result[result.length-intNum-1] |= (1 << (n%32));
Returns a BigInteger whose value is equivalent to this BigInteger
with the designated bit cleared.
(Computes
(this & ~(1<<n)).)
for (int i=0; i<result.length; i++)
result[result.length-i-1] = getInt(i);
result[result.length-intNum-1] &= ~(1 << (n%32));
Returns a BigInteger whose value is equivalent to this BigInteger
with the designated bit flipped.
(Computes
(this ^ (1<<n)).)
for (int i=0; i<result.length; i++)
result[result.length-i-1] = getInt(i);
result[result.length-intNum-1] ^= (1 << (n%32));
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)).)
- Returns:
- index of the rightmost one bit in this BigInteger.
for (i=0; (b = getInt(i))==0; i++)
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))).)
- Returns:
- number of bits in the minimal two's-complement
representation of this BigInteger, excluding a sign bit.
bitLength = (pow2 ? magBitLength-1 : magBitLength);
bitLen(val) is the number of bits in val.
(w < 1<<1 ? (w < 1<<0 ? (w<0 ? 32 : 0) : 1) : (w < 1<<2 ? 2 : 3)) :
(w < 1<<5 ? (w < 1<<4 ? 4 : 5) : (w < 1<<6 ? 6 : 7))) :
(w < 1<<9 ? (w < 1<<8 ? 8 : 9) : (w < 1<<10 ? 10 : 11)) :
(w < 1<<13 ? (w < 1<<12 ? 12 : 13) : (w < 1<<14 ? 14 : 15)))) :
(w < 1<<17 ? (w < 1<<16 ? 16 : 17) : (w < 1<<18 ? 18 : 19)) :
(w < 1<<21 ? (w < 1<<20 ? 20 : 21) : (w < 1<<22 ? 22 : 23))) :
(w < 1<<25 ? (w < 1<<24 ? 24 : 25) : (w < 1<<26 ? 26 : 27)) :
(w < 1<<29 ? (w < 1<<28 ? 28 : 29) : (w < 1<<30 ? 30 : 31)))));
-25, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
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.
- Returns:
- number of bits in the two's complement representation
of this BigInteger that differ from its sign bit.
int magTrailingZeroCount = 0, j;
magTrailingZeroCount += 32;
bitCount = magBitCount + magTrailingZeroCount - 1;
val -= (0xaaaaaaaa & val) >>> 1;
val = (val & 0x33333333) + ((val >>> 2) & 0x33333333);
val = val + (val >>> 4) & 0x0f0f0f0f;
int byteVal = val & 0xff;
byteVal = (val >>> 8) & 0xff;
byteVal = (val >>> 16) & 0xff;
byteVal = (val >>> 24) & 0xff;
Returns
true if this BigInteger is probably prime,
false if it's definitely composite. If
certainty is
<= 0,
true is
returned.
- Parameters:
certainty a 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.- Returns:
true if this BigInteger is probably prime,
false if it's definitely composite.
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:
val BigInteger to which this BigInteger is to be compared.- Returns:
- -1, 0 or 1 as this BigInteger is numerically less than, equal
to, or greater than
val.
: (signum>val.signum ? 1 : -1));
private static int intArrayCmp(int[] arg1, int[] arg2) { if (arg1.length < arg2.length)
if (arg1.length > arg2.length)
for (int i=0; i<arg1.length; i++) { Compares this BigInteger with the specified Object for equality.
- Parameters:
x Object to which this BigInteger is to be compared.- Returns:
true if and only if the specified Object is a
BigInteger whose value is numerically equal to this BigInteger.
if (xInt.mag[i] != mag[i])
Returns the minimum of this BigInteger and
val.
- Parameters:
val value with which the minimum is to be computed.- Returns:
- the BigInteger whose value is the lesser of this BigInteger and
val. If they are equal, either may be returned.
Returns the maximum of this BigInteger and
val.
- Parameters:
val value with which the maximum is to be computed.- Returns:
- the BigInteger whose value is the greater of this and
val. If they are equal, either may be returned.
Returns the hash code for this BigInteger.
- Returns:
- hash code for this BigInteger.
Returns the String representation of this BigInteger in the
given radix. If the radix is outside the range from
java.lang.Character.MIN_RADIX to
java.lang.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.)
int maxNumDigitGroups = (4*mag.length + 6)/7;
while (tmp.signum != 0) { buf.append(digitGroup[numGroups-1]);
for (int i=numGroups-2; i>=0; i--) { if (numLeadingZeros != 0)
"000000000000000000000000000000000000000000000000000000000000000";
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.)
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.)
- Returns:
- a byte array containing the two's-complement representation of
this BigInteger.
- See also:
BigInteger(byte[])
byte[] byteArray = new byte[byteLen];
for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i>=0; i--) { byteArray[i] = (byte)nextInt;
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.
- Returns:
- this BigInteger converted to an
int.
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.
- Returns:
- this BigInteger converted to a
long.
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
java.lang.Float.NEGATIVE_INFINITY or
java.lang.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.
- Returns:
- this BigInteger converted to a
float.
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
java.lang.Double.NEGATIVE_INFINITY or
java.lang.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.
- Returns:
- this BigInteger converted to a
double.
Returns a copy of the input array stripped of any leading zero bytes.
int byteLength = val.length;
for (keep=0; keep<val.length && val[keep]==0; keep++)
int result[] = new int[val.length - keep];
for(int i=0; i<val.length - keep; i++)
Returns the input array stripped of any leading zero bytes.
Since the source is trusted the copying may be skipped.
int byteLength = val.length;
for (keep=0; keep<val.length && val[keep]==0; keep++)
int result[] = new int[val.length - keep];
for(int i=0; i<val.length - keep; i++)
Returns a copy of the input array stripped of any leading zero bytes.
int byteLength = a.length;
for (keep=0; keep<a.length && a[keep]==0; keep++)
int intLength = ((byteLength - keep) + 3)/4;
int[] result = new int[intLength];
for (int i = intLength-1; i >= 0; i--) { result[i] = a[b--] & 0xff;
int bytesRemaining = b - keep + 1;
int bytesToTransfer = Math.min(3, bytesRemaining);
for (int j=8; j <= 8*bytesToTransfer; j += 8)
result[i] |= ((a[b--] & 0xff) << j);
Takes an array a representing a negative 2's-complement number and
returns the minimal (no leading zero bytes) unsigned whose value is -a.
int byteLength = a.length;
for (keep=0; keep<byteLength && a[keep]==-1; keep++)
for (k=keep; k<byteLength && a[k]==0; k++)
int extraByte = (k==byteLength) ? 1 : 0;
int intLength = ((byteLength - keep + extraByte) + 3)/4;
int result[] = new int[intLength];
for (int i = intLength-1; i >= 0; i--) { result[i] = a[b--] & 0xff;
int numBytesToTransfer = Math.min(3, b-keep+1);
if (numBytesToTransfer < 0)
for (int j=8; j <= 8*numBytesToTransfer; j += 8)
result[i] |= ((a[b--] & 0xff) << j);
int mask = -1 >>> (8*(3-numBytesToTransfer));
result[i] = ~result[i] & mask;
for (int i=result.length-1; i>=0; i--) { result[i] = (int)((result[i] & LONG_MASK) + 1);
Takes an array a representing a negative 2's-complement number and
returns the minimal (no leading zero ints) unsigned whose value is -a.
for (keep=0; keep<a.length && a[keep]==-1; keep++)
for (j=keep; j<a.length && a[j]==0; j++)
int extraInt = (j==a.length ? 1 : 0);
int result[] = new int[a.length - keep + extraInt];
for (int i = keep; i<a.length; i++)
result[i - keep + extraInt] = ~a[i];
for (int i=result.length-1; ++result[i]==0; i--)
62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11, 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};
0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000,
0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40,
0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
These routines provide access to the two's complement representation
of BigIntegers.
Returns the length of the two's complement representation in ints,
including space for at least one sign bit.
Returns the specified int of the little-endian two's complement
representation (int 0 is the least significant). The int number can
be arbitrarily high (values are logically preceded by infinitely many
sign ints).
return (signum >= 0 ? magInt :
Returns the index of the int that contains the first nonzero int in the
little-endian binary representation of the magnitude (int 0 is the
least significant). If the magnitude is zero, return value is undefined.
use serialVersionUID from JDK 1.1. for interoperability
Serializable fields for BigInteger.
- SerialField:
- signum int
signum of this BigInteger.
- SerialField:
- magnitude int[]
magnitude array of this BigInteger.
- SerialField:
- bitCount int
number of bits in this BigInteger
- SerialField:
- bitLength int
the number of bits in the minimal two's-complement
representation of this BigInteger
- SerialField:
- lowestSetBit int
lowest set bit in the twos complement representation
Reconstitute the
BigInteger instance from a stream (that is,
deserialize it). The magnitude is read in as an array of bytes
for historical reasons, but it is converted to an array of ints
and the byte array is discarded.
byte[] magnitude = (byte[])fields.get("magnitude", null); String message = "BigInteger: Invalid signum value";
message = "BigInteger: Signum not present in stream";
if ((magnitude.length==0) != (signum==0)) { String message = "BigInteger: signum-magnitude mismatch";
message = "BigInteger: Magnitude not present in stream";
Save the
BigInteger instance to a stream.
The magnitude of a BigInteger is serialized as a byte array for
historical reasons.
- SerialData:
- two necessary fields are written as well as obsolete
fields for compatibility with older versions.
fields.put("bitCount", -1); fields.put("bitLength", -1); fields.put("lowestSetBit", -2); fields.put("firstNonzeroByteNum", -2); Returns the mag array as an array of bytes.
int byteLen = (bitLen + 7)/8;
byte[] result = new byte[byteLen];
for (int i=byteLen-1, bytesCopied=4, intIndex=mag.length-1, nextInt=0;
nextInt = mag[intIndex--];
result[i] = (byte)nextInt;