Method from java.math.BigInteger Detail: |
public BigInteger abs() {
return (signum >= 0 ? this : this.negate());
}
Returns a BigInteger whose value is the absolute value of this
BigInteger. |
public BigInteger add(BigInteger val) {
if (val.signum == 0)
return this;
if (signum == 0)
return val;
if (val.signum == signum)
return new BigInteger(add(mag, val.mag), signum);
int cmp = compareMagnitude(val);
if (cmp == 0)
return ZERO;
int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
: subtract(val.mag, mag));
resultMag = trustedStripLeadingZeroInts(resultMag);
return new BigInteger(resultMag, cmp == signum ? 1 : -1);
}
Returns a BigInteger whose value is {@code (this + val)}. |
static int addOne(int[] a,
int offset,
int mlen,
int carry) {
offset = a.length-1-mlen-offset;
long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);
a[offset] = (int)t;
if ((t > > > 32) == 0)
return 0;
while (--mlen >= 0) {
if (--offset < 0) { // Carry out of number
return 1;
} else {
a[offset]++;
if (a[offset] != 0)
return 0;
}
}
return 1;
}
Add one word to the number a mlen words into a. Return the resulting
carry. |
public BigInteger and(BigInteger val) {
int[] result = new int[Math.max(intLength(), val.intLength())];
for (int i=0; i< result.length; i++)
result[i] = (getInt(result.length-i-1)
& val.getInt(result.length-i-1));
return valueOf(result);
}
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.) |
public BigInteger andNot(BigInteger val) {
int[] result = new int[Math.max(intLength(), val.intLength())];
for (int i=0; i< result.length; i++)
result[i] = (getInt(result.length-i-1)
& ~val.getInt(result.length-i-1));
return valueOf(result);
}
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.) |
public int bitCount() {
@SuppressWarnings("deprecation") int bc = bitCount - 1;
if (bc == -1) { // bitCount not initialized yet
bc = 0; // offset by one to initialize
// Count the bits in the magnitude
for (int i=0; i< mag.length; i++)
bc += Integer.bitCount(mag[i]);
if (signum < 0) {
// Count the trailing zeros in the magnitude
int magTrailingZeroCount = 0, j;
for (j=mag.length-1; mag[j]==0; j--)
magTrailingZeroCount += 32;
magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
bc += magTrailingZeroCount - 1;
}
bitCount = bc + 1;
}
return bc;
}
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. |
public int bitLength() {
@SuppressWarnings("deprecation") int n = bitLength - 1;
if (n == -1) { // bitLength not initialized yet
int[] m = mag;
int len = m.length;
if (len == 0) {
n = 0; // offset by one to initialize
} else {
// Calculate the bit length of the magnitude
int magBitLength = ((len - 1) < < 5) + bitLengthForInt(mag[0]);
if (signum < 0) {
// Check if magnitude is a power of two
boolean pow2 = (Integer.bitCount(mag[0]) == 1);
for(int i=1; i< len && pow2; i++)
pow2 = (mag[i] == 0);
n = (pow2 ? magBitLength -1 : magBitLength);
} else {
n = magBitLength;
}
}
bitLength = n + 1;
}
return n;
}
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
{@code (ceil(log2(this < 0 ? -this : this+1)))}.) |
static int bitLengthForInt(int n) {
return 32 - Integer.numberOfLeadingZeros(n);
}
Package private method to return bit length for an integer. |
public BigInteger clearBit(int n) {
if (n< 0)
throw new ArithmeticException("Negative bit address");
int intNum = n > > > 5;
int[] result = new int[Math.max(intLength(), ((n + 1) > > > 5) + 1)];
for (int i=0; i< result.length; i++)
result[result.length-i-1] = getInt(i);
result[result.length-intNum-1] &= ~(1 < < (n & 31));
return valueOf(result);
}
Returns a BigInteger whose value is equivalent to this BigInteger
with the designated bit cleared.
(Computes {@code (this & ~(1< |
final int compareMagnitude(BigInteger val) {
int[] m1 = mag;
int len1 = m1.length;
int[] m2 = val.mag;
int len2 = m2.length;
if (len1 < len2)
return -1;
if (len1 > len2)
return 1;
for (int i = 0; i < len1; i++) {
int a = m1[i];
int b = m2[i];
if (a != b)
return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
}
return 0;
}
Compares the magnitude array of this BigInteger with the specified
BigInteger's. This is the version of compareTo ignoring sign. |
public int compareTo(BigInteger val) {
if (signum == val.signum) {
switch (signum) {
case 1:
return compareMagnitude(val);
case -1:
return val.compareMagnitude(this);
default:
return 0;
}
}
return signum > val.signum ? 1 : -1;
}
Compares this BigInteger with the specified BigInteger. This
method is provided in preference to individual methods for each
of the six boolean comparison operators ({@literal <}, ==,
{@literal >}, {@literal >=}, !=, {@literal <=}). The suggested
idiom for performing these comparisons is: {@code
(x.compareTo(y)} <op> {@code 0)}, where
<op> is one of the six comparison operators. |
public BigInteger divide(BigInteger val) {
MutableBigInteger q = new MutableBigInteger(),
a = new MutableBigInteger(this.mag),
b = new MutableBigInteger(val.mag);
a.divide(b, q);
return q.toBigInteger(this.signum == val.signum ? 1 : -1);
}
Returns a BigInteger whose value is {@code (this / val)}. |
public BigInteger[] divideAndRemainder(BigInteger val) {
BigInteger[] result = new BigInteger[2];
MutableBigInteger q = new MutableBigInteger(),
a = new MutableBigInteger(this.mag),
b = new MutableBigInteger(val.mag);
MutableBigInteger r = a.divide(b, q);
result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);
result[1] = r.toBigInteger(this.signum);
return result;
}
Returns an array of two BigIntegers containing {@code (this / val)}
followed by {@code (this % val)}. |
public double doubleValue() {
// Somewhat inefficient, but guaranteed to work.
return Double.parseDouble(this.toString());
}
Converts this BigInteger to a {@code double}. This
conversion is similar to the
narrowing primitive conversion from {@code double} to
{@code float} as defined in section 5.1.3 of
The Java™ Language Specification:
if this BigInteger has too great a magnitude
to represent as a {@code 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. |
public boolean equals(Object x) {
// This test is just an optimization, which may or may not help
if (x == this)
return true;
if (!(x instanceof BigInteger))
return false;
BigInteger xInt = (BigInteger) x;
if (xInt.signum != signum)
return false;
int[] m = mag;
int len = m.length;
int[] xm = xInt.mag;
if (len != xm.length)
return false;
for (int i = 0; i < len; i++)
if (xm[i] != m[i])
return false;
return true;
}
Compares this BigInteger with the specified Object for equality. |
public BigInteger flipBit(int n) {
if (n< 0)
throw new ArithmeticException("Negative bit address");
int intNum = n > > > 5;
int[] result = new int[Math.max(intLength(), intNum+2)];
for (int i=0; i< result.length; i++)
result[result.length-i-1] = getInt(i);
result[result.length-intNum-1] ^= (1 < < (n & 31));
return valueOf(result);
}
Returns a BigInteger whose value is equivalent to this BigInteger
with the designated bit flipped.
(Computes {@code (this ^ (1< |
public float floatValue() {
// Somewhat inefficient, but guaranteed to work.
return Float.parseFloat(this.toString());
}
Converts this BigInteger to a {@code float}. This
conversion is similar to the
narrowing primitive conversion from {@code double} to
{@code float} as defined in section 5.1.3 of
The Java™ Language Specification:
if this BigInteger has too great a magnitude
to represent as a {@code 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. |
public BigInteger gcd(BigInteger val) {
if (val.signum == 0)
return this.abs();
else if (this.signum == 0)
return val.abs();
MutableBigInteger a = new MutableBigInteger(this);
MutableBigInteger b = new MutableBigInteger(val);
MutableBigInteger result = a.hybridGCD(b);
return result.toBigInteger(1);
}
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}. |
public int getLowestSetBit() {
@SuppressWarnings("deprecation") int lsb = lowestSetBit - 2;
if (lsb == -2) { // lowestSetBit not initialized yet
lsb = 0;
if (signum == 0) {
lsb -= 1;
} else {
// Search for lowest order nonzero int
int i,b;
for (i=0; (b = getInt(i))==0; i++)
;
lsb += (i < < 5) + Integer.numberOfTrailingZeros(b);
}
lowestSetBit = lsb + 2;
}
return lsb;
}
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))}.) |
public int hashCode() {
int hashCode = 0;
for (int i=0; i< mag.length; i++)
hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));
return hashCode * signum;
}
Returns the hash code for this BigInteger. |
public int intValue() {
int result = 0;
result = getInt(0);
return result;
}
Converts this BigInteger to an {@code int}. This
conversion is analogous to a
narrowing primitive conversion from {@code long} to
{@code int} as defined in section 5.1.3 of
The Java™ Language Specification:
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. |
public boolean isProbablePrime(int certainty) {
if (certainty < = 0)
return true;
BigInteger w = this.abs();
if (w.equals(TWO))
return true;
if (!w.testBit(0) || w.equals(ONE))
return false;
return w.primeToCertainty(certainty, null);
}
Returns {@code true} if this BigInteger is probably prime,
{@code false} if it's definitely composite. If
{@code certainty} is ≤ 0, {@code true} is
returned. |
int[] javaIncrement(int[] val) {
int lastSum = 0;
for (int i=val.length-1; i >= 0 && lastSum == 0; i--)
lastSum = (val[i] += 1);
if (lastSum == 0) {
val = new int[val.length+1];
val[0] = 1;
}
return val;
}
|
public long longValue() {
long result = 0;
for (int i=1; i >=0; i--)
result = (result < < 32) + (getInt(i) & LONG_MASK);
return result;
}
Converts this BigInteger to a {@code long}. This
conversion is analogous to a
narrowing primitive conversion from {@code long} to
{@code int} as defined in section 5.1.3 of
The Java™ Language Specification:
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. |
public BigInteger max(BigInteger val) {
return (compareTo(val) >0 ? this : val);
}
Returns the maximum of this BigInteger and {@code val}. |
public BigInteger min(BigInteger val) {
return (compareTo(val)< 0 ? this : val);
}
Returns the minimum of this BigInteger and {@code val}. |
public BigInteger mod(BigInteger m) {
if (m.signum < = 0)
throw new ArithmeticException("BigInteger: modulus not positive");
BigInteger result = this.remainder(m);
return (result.signum >= 0 ? result : result.add(m));
}
Returns a BigInteger whose value is {@code (this mod m}). This method
differs from {@code remainder} in that it always returns a
non-negative BigInteger. |
public BigInteger modInverse(BigInteger m) {
if (m.signum != 1)
throw new ArithmeticException("BigInteger: modulus not positive");
if (m.equals(ONE))
return ZERO;
// Calculate (this mod m)
BigInteger modVal = this;
if (signum < 0 || (this.compareMagnitude(m) >= 0))
modVal = this.mod(m);
if (modVal.equals(ONE))
return ONE;
MutableBigInteger a = new MutableBigInteger(modVal);
MutableBigInteger b = new MutableBigInteger(m);
MutableBigInteger result = a.mutableModInverse(b);
return result.toBigInteger(1);
}
Returns a BigInteger whose value is {@code (this}-1 {@code mod m)}. |
public BigInteger modPow(BigInteger exponent,
BigInteger m) {
if (m.signum < = 0)
throw new ArithmeticException("BigInteger: modulus not positive");
// Trivial cases
if (exponent.signum == 0)
return (m.equals(ONE) ? ZERO : ONE);
if (this.equals(ONE))
return (m.equals(ONE) ? ZERO : ONE);
if (this.equals(ZERO) && exponent.signum >= 0)
return ZERO;
if (this.equals(negConst[1]) && (!exponent.testBit(0)))
return (m.equals(ONE) ? ZERO : ONE);
boolean invertResult;
if ((invertResult = (exponent.signum < 0)))
exponent = exponent.negate();
BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
? this.mod(m) : this);
BigInteger result;
if (m.testBit(0)) { // odd modulus
result = base.oddModPow(exponent, m);
} else {
/*
* Even modulus. Tear it into an "odd part" (m1) and power of two
* (m2), exponentiate mod m1, manually exponentiate mod m2, and
* use Chinese Remainder Theorem to combine results.
*/
// Tear m apart into odd part (m1) and power of 2 (m2)
int p = m.getLowestSetBit(); // Max pow of 2 that divides m
BigInteger m1 = m.shiftRight(p); // m/2**p
BigInteger m2 = ONE.shiftLeft(p); // 2**p
// Calculate new base from m1
BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0
? this.mod(m1) : this);
// Caculate (base ** exponent) mod m1.
BigInteger a1 = (m1.equals(ONE) ? ZERO :
base2.oddModPow(exponent, m1));
// Calculate (this ** exponent) mod m2
BigInteger a2 = base.modPow2(exponent, p);
// Combine results using Chinese Remainder Theorem
BigInteger y1 = m2.modInverse(m1);
BigInteger y2 = m1.modInverse(m2);
result = a1.multiply(m2).multiply(y1).add
(a2.multiply(m1).multiply(y2)).mod(m);
}
return (invertResult ? result.modInverse(m) : result);
}
Returns a BigInteger whose value is
(thisexponent mod m). (Unlike {@code pow}, this
method permits negative exponents.) |
static int mulAdd(int[] out,
int[] in,
int offset,
int len,
int k) {
long kLong = k & LONG_MASK;
long carry = 0;
offset = out.length-offset - 1;
for (int j=len-1; j >= 0; j--) {
long product = (in[j] & LONG_MASK) * kLong +
(out[offset] & LONG_MASK) + carry;
out[offset--] = (int)product;
carry = product > > > 32;
}
return (int)carry;
}
Multiply an array by one word k and add to result, return the carry |
public BigInteger multiply(BigInteger val) {
if (val.signum == 0 || signum == 0)
return ZERO;
int[] result = multiplyToLen(mag, mag.length,
val.mag, val.mag.length, null);
result = trustedStripLeadingZeroInts(result);
return new BigInteger(result, signum == val.signum ? 1 : -1);
}
Returns a BigInteger whose value is {@code (this * val)}. |
BigInteger multiply(long v) {
if (v == 0 || signum == 0)
return ZERO;
if (v == BigDecimal.INFLATED)
return multiply(BigInteger.valueOf(v));
int rsign = (v > 0 ? signum : -signum);
if (v < 0)
v = -v;
long dh = v > > > 32; // higher order bits
long dl = v & LONG_MASK; // lower order bits
int xlen = mag.length;
int[] value = mag;
int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]);
long carry = 0;
int rstart = rmag.length - 1;
for (int i = xlen - 1; i >= 0; i--) {
long product = (value[i] & LONG_MASK) * dl + carry;
rmag[rstart--] = (int)product;
carry = product > > > 32;
}
rmag[rstart] = (int)carry;
if (dh != 0L) {
carry = 0;
rstart = rmag.length - 2;
for (int i = xlen - 1; i >= 0; i--) {
long product = (value[i] & LONG_MASK) * dh +
(rmag[rstart] & LONG_MASK) + carry;
rmag[rstart--] = (int)product;
carry = product > > > 32;
}
rmag[0] = (int)carry;
}
if (carry == 0L)
rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
return new BigInteger(rmag, rsign);
}
Package private methods used by BigDecimal code to multiply a BigInteger
with a long. Assumes v is not equal to INFLATED. |
public BigInteger negate() {
return new BigInteger(this.mag, -this.signum);
}
Returns a BigInteger whose value is {@code (-this)}. |
public BigInteger nextProbablePrime() {
if (this.signum < 0)
throw new ArithmeticException("start < 0: " + this);
// Handle trivial cases
if ((this.signum == 0) || this.equals(ONE))
return TWO;
BigInteger result = this.add(ONE);
// Fastpath for small numbers
if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
// Ensure an odd number
if (!result.testBit(0))
result = result.add(ONE);
while(true) {
// Do cheap "pre-test" if applicable
if (result.bitLength() > 6) {
long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
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)) {
result = result.add(TWO);
continue; // Candidate is composite; try another
}
}
// All candidates of bitLength 2 and 3 are prime by this point
if (result.bitLength() < 4)
return result;
// The expensive test
if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))
return result;
result = result.add(TWO);
}
}
// Start at previous even number
if (result.testBit(0))
result = result.subtract(ONE);
// Looking for the next large prime
int searchLen = (result.bitLength() / 20) * 64;
while(true) {
BitSieve searchSieve = new BitSieve(result, searchLen);
BigInteger candidate = searchSieve.retrieve(result,
DEFAULT_PRIME_CERTAINTY, null);
if (candidate != null)
return candidate;
result = result.add(BigInteger.valueOf(2 * searchLen));
}
}
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-100. 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}. |
public BigInteger not() {
int[] result = new int[intLength()];
for (int i=0; i< result.length; i++)
result[i] = ~getInt(result.length-i-1);
return valueOf(result);
}
Returns a BigInteger whose value is {@code (~this)}. (This method
returns a negative value if and only if this BigInteger is
non-negative.) |
public BigInteger or(BigInteger val) {
int[] result = new int[Math.max(intLength(), val.intLength())];
for (int i=0; i< result.length; i++)
result[i] = (getInt(result.length-i-1)
| val.getInt(result.length-i-1));
return valueOf(result);
}
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.) |
public BigInteger pow(int exponent) {
if (exponent < 0)
throw new ArithmeticException("Negative exponent");
if (signum==0)
return (exponent==0 ? ONE : this);
// Perform exponentiation using repeated squaring trick
int newSign = (signum< 0 && (exponent&1)==1 ? -1 : 1);
int[] baseToPow2 = this.mag;
int[] result = {1};
while (exponent != 0) {
if ((exponent & 1)==1) {
result = multiplyToLen(result, result.length,
baseToPow2, baseToPow2.length, null);
result = trustedStripLeadingZeroInts(result);
}
if ((exponent > > >= 1) != 0) {
baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null);
baseToPow2 = trustedStripLeadingZeroInts(baseToPow2);
}
}
return new BigInteger(result, newSign);
}
Returns a BigInteger whose value is (thisexponent).
Note that {@code exponent} is an integer rather than a BigInteger. |
boolean primeToCertainty(int certainty,
Random random) {
int rounds = 0;
int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;
// The relationship between the certainty and the number of rounds
// we perform is given in the draft standard ANSI X9.80, "PRIME
// NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
int sizeInBits = this.bitLength();
if (sizeInBits < 100) {
rounds = 50;
rounds = n < rounds ? n : rounds;
return passesMillerRabin(rounds, random);
}
if (sizeInBits < 256) {
rounds = 27;
} else if (sizeInBits < 512) {
rounds = 15;
} else if (sizeInBits < 768) {
rounds = 8;
} else if (sizeInBits < 1024) {
rounds = 4;
} else {
rounds = 2;
}
rounds = n < rounds ? n : rounds;
return passesMillerRabin(rounds, random) && passesLucasLehmer();
}
Returns {@code true} if this BigInteger is probably prime,
{@code false} if it's definitely composite.
This method assumes bitLength > 2. |
static void primitiveLeftShift(int[] a,
int len,
int n) {
if (len == 0 || n == 0)
return;
int n2 = 32 - n;
for (int i=0, c=a[i], m=i+len-1; i< m; i++) {
int b = c;
c = a[i+1];
a[i] = (b < < n) | (c > > > n2);
}
a[len-1] < < = n;
}
|
static void primitiveRightShift(int[] a,
int len,
int n) {
int n2 = 32 - n;
for (int i=len-1, c=a[i]; i >0; i--) {
int b = c;
c = a[i-1];
a[i] = (c < < n2) | (b > > > n);
}
a[0] > > >= n;
}
|
public static BigInteger probablePrime(int bitLength,
Random rnd) {
if (bitLength < 2)
throw new ArithmeticException("bitLength < 2");
// The cutoff of 95 was chosen empirically for best performance
return (bitLength < SMALL_PRIME_THRESHOLD ?
smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
largePrime(bitLength, DEFAULT_PRIME_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. |
public BigInteger remainder(BigInteger val) {
MutableBigInteger q = new MutableBigInteger(),
a = new MutableBigInteger(this.mag),
b = new MutableBigInteger(val.mag);
return a.divide(b, q).toBigInteger(this.signum);
}
Returns a BigInteger whose value is {@code (this % val)}. |
public BigInteger setBit(int n) {
if (n< 0)
throw new ArithmeticException("Negative bit address");
int intNum = n > > > 5;
int[] result = new int[Math.max(intLength(), intNum+2)];
for (int i=0; i< result.length; i++)
result[result.length-i-1] = getInt(i);
result[result.length-intNum-1] |= (1 < < (n & 31));
return valueOf(result);
}
Returns a BigInteger whose value is equivalent to this BigInteger
with the designated bit set. (Computes {@code (this | (1< |
public BigInteger shiftLeft(int n) {
if (signum == 0)
return ZERO;
if (n==0)
return this;
if (n< 0) {
if (n == Integer.MIN_VALUE) {
throw new ArithmeticException("Shift distance of Integer.MIN_VALUE not supported.");
} else {
return shiftRight(-n);
}
}
int nInts = n > > > 5;
int nBits = n & 0x1f;
int magLen = mag.length;
int newMag[] = null;
if (nBits == 0) {
newMag = new int[magLen + nInts];
for (int i=0; i< magLen; i++)
newMag[i] = mag[i];
} else {
int i = 0;
int nBits2 = 32 - nBits;
int highBits = mag[0] > > > nBits2;
if (highBits != 0) {
newMag = new int[magLen + nInts + 1];
newMag[i++] = highBits;
} else {
newMag = new int[magLen + nInts];
}
int j=0;
while (j < magLen-1)
newMag[i++] = mag[j++] < < nBits | mag[j] > > > nBits2;
newMag[i] = mag[j] < < nBits;
}
return new BigInteger(newMag, signum);
}
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 floor(this * 2n).) |
public BigInteger shiftRight(int n) {
if (n==0)
return this;
if (n< 0) {
if (n == Integer.MIN_VALUE) {
throw new ArithmeticException("Shift distance of Integer.MIN_VALUE not supported.");
} else {
return shiftLeft(-n);
}
}
int nInts = n > > > 5;
int nBits = n & 0x1f;
int magLen = mag.length;
int newMag[] = null;
// Special case: entire contents shifted off the end
if (nInts >= magLen)
return (signum >= 0 ? ZERO : negConst[1]);
if (nBits == 0) {
int newMagLen = magLen - nInts;
newMag = new int[newMagLen];
for (int i=0; i< newMagLen; i++)
newMag[i] = mag[i];
} else {
int i = 0;
int highBits = mag[0] > > > nBits;
if (highBits != 0) {
newMag = new int[magLen - nInts];
newMag[i++] = highBits;
} else {
newMag = new int[magLen - nInts -1];
}
int nBits2 = 32 - nBits;
int j=0;
while (j < magLen - nInts - 1)
newMag[i++] = (mag[j++] < < nBits2) | (mag[j] > > > nBits);
}
if (signum < 0) {
// Find out whether any one-bits were shifted off the end.
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);
if (onesLost)
newMag = javaIncrement(newMag);
}
return new BigInteger(newMag, signum);
}
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 floor(this / 2n).) |
public int signum() {
return this.signum;
}
Returns the signum function of this BigInteger. |
public BigInteger subtract(BigInteger val) {
if (val.signum == 0)
return this;
if (signum == 0)
return val.negate();
if (val.signum != signum)
return new BigInteger(add(mag, val.mag), signum);
int cmp = compareMagnitude(val);
if (cmp == 0)
return ZERO;
int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
: subtract(val.mag, mag));
resultMag = trustedStripLeadingZeroInts(resultMag);
return new BigInteger(resultMag, cmp == signum ? 1 : -1);
}
Returns a BigInteger whose value is {@code (this - val)}. |
public boolean testBit(int n) {
if (n< 0)
throw new ArithmeticException("Negative bit address");
return (getInt(n > > > 5) & (1 < < (n & 31))) != 0;
}
Returns {@code true} if and only if the designated bit is set.
(Computes {@code ((this & (1< |
public byte[] toByteArray() {
int byteLen = bitLength()/8 + 1;
byte[] byteArray = new byte[byteLen];
for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >=0; i--) {
if (bytesCopied == 4) {
nextInt = getInt(intIndex++);
bytesCopied = 1;
} else {
nextInt > > >= 8;
bytesCopied++;
}
byteArray[i] = (byte)nextInt;
}
return byteArray;
}
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 {@code (ceil((this.bitLength() +
1)/8))}. (This representation is compatible with the
(byte[]) constructor.) |
public String toString() {
return toString(10);
}
Returns the decimal String representation of this BigInteger.
The digit-to-character mapping provided by
{@code 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.) |
public String toString(int radix) {
if (signum == 0)
return "0";
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
radix = 10;
// Compute upper bound on number of digit groups and allocate space
int maxNumDigitGroups = (4*mag.length + 6)/7;
String digitGroup[] = new String[maxNumDigitGroups];
// Translate number to string, a digit group at a time
BigInteger tmp = this.abs();
int numGroups = 0;
while (tmp.signum != 0) {
BigInteger d = longRadix[radix];
MutableBigInteger q = new MutableBigInteger(),
a = new MutableBigInteger(tmp.mag),
b = new MutableBigInteger(d.mag);
MutableBigInteger r = a.divide(b, q);
BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);
BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
tmp = q2;
}
// Put sign (if any) and first digit group into result buffer
StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1);
if (signum< 0)
buf.append('-');
buf.append(digitGroup[numGroups-1]);
// Append remaining digit groups padded with leading zeros
for (int i=numGroups-2; i >=0; i--) {
// Prepend (any) leading zeros for this digit group
int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
if (numLeadingZeros != 0)
buf.append(zeros[numLeadingZeros]);
buf.append(digitGroup[i]);
}
return buf.toString();
}
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
{@code Integer.toString}). The digit-to-character mapping
provided by {@code Character.forDigit} is used, and a minus
sign is prepended if appropriate. (This representation is
compatible with the int) (String,
int) constructor.) |
public static BigInteger valueOf(long val) {
// If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
if (val == 0)
return ZERO;
if (val > 0 && val < = MAX_CONSTANT)
return posConst[(int) val];
else if (val < 0 && val >= -MAX_CONSTANT)
return negConst[(int) -val];
return new BigInteger(val);
}
Returns a BigInteger whose value is equal to that of the
specified {@code long}. This "static factory method" is
provided in preference to a ({@code long}) constructor
because it allows for reuse of frequently used BigIntegers. |
public BigInteger xor(BigInteger val) {
int[] result = new int[Math.max(intLength(), val.intLength())];
for (int i=0; i< result.length; i++)
result[i] = (getInt(result.length-i-1)
^ val.getInt(result.length-i-1));
return valueOf(result);
}
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.) |