jaroslav@1258: /*
jaroslav@1258: * Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved.
jaroslav@1258: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1258: *
jaroslav@1258: * This code is free software; you can redistribute it and/or modify it
jaroslav@1258: * under the terms of the GNU General Public License version 2 only, as
jaroslav@1258: * published by the Free Software Foundation. Oracle designates this
jaroslav@1258: * particular file as subject to the "Classpath" exception as provided
jaroslav@1258: * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1258: *
jaroslav@1258: * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1258: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1258: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
jaroslav@1258: * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1258: * accompanied this code).
jaroslav@1258: *
jaroslav@1258: * You should have received a copy of the GNU General Public License version
jaroslav@1258: * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1258: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1258: *
jaroslav@1258: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1258: * or visit www.oracle.com if you need additional information or have any
jaroslav@1258: * questions.
jaroslav@1258: */
jaroslav@1258:
jaroslav@1258: /*
jaroslav@1258: * Portions Copyright (c) 1995 Colin Plumb. All rights reserved.
jaroslav@1258: */
jaroslav@1258:
jaroslav@1258: package java.math;
jaroslav@1258:
jaroslav@1258: import java.util.Random;
jaroslav@1258: import java.io.*;
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Immutable arbitrary-precision integers. All operations behave as if
jaroslav@1258: * BigIntegers were represented in two's-complement notation (like Java's
jaroslav@1258: * primitive integer types). BigInteger provides analogues to all of Java's
jaroslav@1258: * primitive integer operators, and all relevant methods from java.lang.Math.
jaroslav@1258: * Additionally, BigInteger provides operations for modular arithmetic, GCD
jaroslav@1258: * calculation, primality testing, prime generation, bit manipulation,
jaroslav@1258: * and a few other miscellaneous operations.
jaroslav@1258: *
jaroslav@1258: *
Semantics of arithmetic operations exactly mimic those of Java's integer
jaroslav@1258: * arithmetic operators, as defined in The Java Language Specification.
jaroslav@1258: * For example, division by zero throws an {@code ArithmeticException}, and
jaroslav@1258: * division of a negative by a positive yields a negative (or zero) remainder.
jaroslav@1258: * All of the details in the Spec concerning overflow are ignored, as
jaroslav@1258: * BigIntegers are made as large as necessary to accommodate the results of an
jaroslav@1258: * operation.
jaroslav@1258: *
jaroslav@1258: *
Semantics of shift operations extend those of Java's shift operators
jaroslav@1258: * to allow for negative shift distances. A right-shift with a negative
jaroslav@1258: * shift distance results in a left shift, and vice-versa. The unsigned
jaroslav@1258: * right shift operator ({@code >>>}) is omitted, as this operation makes
jaroslav@1258: * little sense in combination with the "infinite word size" abstraction
jaroslav@1258: * provided by this class.
jaroslav@1258: *
jaroslav@1258: *
Semantics of bitwise logical operations exactly mimic those of Java's
jaroslav@1258: * bitwise integer operators. The binary operators ({@code and},
jaroslav@1258: * {@code or}, {@code xor}) implicitly perform sign extension on the shorter
jaroslav@1258: * of the two operands prior to performing the operation.
jaroslav@1258: *
jaroslav@1258: *
Comparison operations perform signed integer comparisons, analogous to
jaroslav@1258: * those performed by Java's relational and equality operators.
jaroslav@1258: *
jaroslav@1258: *
Modular arithmetic operations are provided to compute residues, perform
jaroslav@1258: * exponentiation, and compute multiplicative inverses. These methods always
jaroslav@1258: * return a non-negative result, between {@code 0} and {@code (modulus - 1)},
jaroslav@1258: * inclusive.
jaroslav@1258: *
jaroslav@1258: *
Bit operations operate on a single bit of the two's-complement
jaroslav@1258: * representation of their operand. If necessary, the operand is sign-
jaroslav@1258: * extended so that it contains the designated bit. None of the single-bit
jaroslav@1258: * operations can produce a BigInteger with a different sign from the
jaroslav@1258: * BigInteger being operated on, as they affect only a single bit, and the
jaroslav@1258: * "infinite word size" abstraction provided by this class ensures that there
jaroslav@1258: * are infinitely many "virtual sign bits" preceding each BigInteger.
jaroslav@1258: *
jaroslav@1258: *
For the sake of brevity and clarity, pseudo-code is used throughout the
jaroslav@1258: * descriptions of BigInteger methods. The pseudo-code expression
jaroslav@1258: * {@code (i + j)} is shorthand for "a BigInteger whose value is
jaroslav@1258: * that of the BigInteger {@code i} plus that of the BigInteger {@code j}."
jaroslav@1258: * The pseudo-code expression {@code (i == j)} is shorthand for
jaroslav@1258: * "{@code true} if and only if the BigInteger {@code i} represents the same
jaroslav@1258: * value as the BigInteger {@code j}." Other pseudo-code expressions are
jaroslav@1258: * interpreted similarly.
jaroslav@1258: *
jaroslav@1258: *
All methods and constructors in this class throw
jaroslav@1258: * {@code NullPointerException} when passed
jaroslav@1258: * a null object reference for any input parameter.
jaroslav@1258: *
jaroslav@1258: * @see BigDecimal
jaroslav@1258: * @author Josh Bloch
jaroslav@1258: * @author Michael McCloskey
jaroslav@1258: * @since JDK1.1
jaroslav@1258: */
jaroslav@1258:
jaroslav@1258: public class BigInteger extends Number implements Comparable {
jaroslav@1258: /**
jaroslav@1258: * The signum of this BigInteger: -1 for negative, 0 for zero, or
jaroslav@1258: * 1 for positive. Note that the BigInteger zero must have
jaroslav@1258: * a signum of 0. This is necessary to ensures that there is exactly one
jaroslav@1258: * representation for each BigInteger value.
jaroslav@1258: *
jaroslav@1258: * @serial
jaroslav@1258: */
jaroslav@1258: final int signum;
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * The magnitude of this BigInteger, in big-endian order: the
jaroslav@1258: * zeroth element of this array is the most-significant int of the
jaroslav@1258: * magnitude. The magnitude must be "minimal" in that the most-significant
jaroslav@1258: * int ({@code mag[0]}) must be non-zero. This is necessary to
jaroslav@1258: * ensure that there is exactly one representation for each BigInteger
jaroslav@1258: * value. Note that this implies that the BigInteger zero has a
jaroslav@1258: * zero-length mag array.
jaroslav@1258: */
jaroslav@1258: final int[] mag;
jaroslav@1258:
jaroslav@1258: // These "redundant fields" are initialized with recognizable nonsense
jaroslav@1258: // values, and cached the first time they are needed (or never, if they
jaroslav@1258: // aren't needed).
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * One plus the bitCount of this BigInteger. Zeros means unitialized.
jaroslav@1258: *
jaroslav@1258: * @serial
jaroslav@1258: * @see #bitCount
jaroslav@1258: * @deprecated Deprecated since logical value is offset from stored
jaroslav@1258: * value and correction factor is applied in accessor method.
jaroslav@1258: */
jaroslav@1258: @Deprecated
jaroslav@1258: private int bitCount;
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * One plus the bitLength of this BigInteger. Zeros means unitialized.
jaroslav@1258: * (either value is acceptable).
jaroslav@1258: *
jaroslav@1258: * @serial
jaroslav@1258: * @see #bitLength()
jaroslav@1258: * @deprecated Deprecated since logical value is offset from stored
jaroslav@1258: * value and correction factor is applied in accessor method.
jaroslav@1258: */
jaroslav@1258: @Deprecated
jaroslav@1258: private int bitLength;
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Two plus the lowest set bit of this BigInteger, as returned by
jaroslav@1258: * getLowestSetBit().
jaroslav@1258: *
jaroslav@1258: * @serial
jaroslav@1258: * @see #getLowestSetBit
jaroslav@1258: * @deprecated Deprecated since logical value is offset from stored
jaroslav@1258: * value and correction factor is applied in accessor method.
jaroslav@1258: */
jaroslav@1258: @Deprecated
jaroslav@1258: private int lowestSetBit;
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Two plus the index of the lowest-order int in the magnitude of this
jaroslav@1258: * BigInteger that contains a nonzero int, or -2 (either value is acceptable).
jaroslav@1258: * The least significant int has int-number 0, the next int in order of
jaroslav@1258: * increasing significance has int-number 1, and so forth.
jaroslav@1258: * @deprecated Deprecated since logical value is offset from stored
jaroslav@1258: * value and correction factor is applied in accessor method.
jaroslav@1258: */
jaroslav@1258: @Deprecated
jaroslav@1258: private int firstNonzeroIntNum;
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * This mask is used to obtain the value of an int as if it were unsigned.
jaroslav@1258: */
jaroslav@1258: final static long LONG_MASK = 0xffffffffL;
jaroslav@1258:
jaroslav@1258: //Constructors
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Translates a byte array containing the two's-complement binary
jaroslav@1258: * representation of a BigInteger into a BigInteger. The input array is
jaroslav@1258: * assumed to be in big-endian byte-order: the most significant
jaroslav@1258: * byte is in the zeroth element.
jaroslav@1258: *
jaroslav@1258: * @param val big-endian two's-complement binary representation of
jaroslav@1258: * BigInteger.
jaroslav@1258: * @throws NumberFormatException {@code val} is zero bytes long.
jaroslav@1258: */
jaroslav@1258: public BigInteger(byte[] val) {
jaroslav@1258: if (val.length == 0)
jaroslav@1258: throw new NumberFormatException("Zero length BigInteger");
jaroslav@1258:
jaroslav@1258: if (val[0] < 0) {
jaroslav@1258: mag = makePositive(val);
jaroslav@1258: signum = -1;
jaroslav@1258: } else {
jaroslav@1258: mag = stripLeadingZeroBytes(val);
jaroslav@1258: signum = (mag.length == 0 ? 0 : 1);
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * This private constructor translates an int array containing the
jaroslav@1258: * two's-complement binary representation of a BigInteger into a
jaroslav@1258: * BigInteger. The input array is assumed to be in big-endian
jaroslav@1258: * int-order: the most significant int is in the zeroth element.
jaroslav@1258: */
jaroslav@1258: private BigInteger(int[] val) {
jaroslav@1258: if (val.length == 0)
jaroslav@1258: throw new NumberFormatException("Zero length BigInteger");
jaroslav@1258:
jaroslav@1258: if (val[0] < 0) {
jaroslav@1258: mag = makePositive(val);
jaroslav@1258: signum = -1;
jaroslav@1258: } else {
jaroslav@1258: mag = trustedStripLeadingZeroInts(val);
jaroslav@1258: signum = (mag.length == 0 ? 0 : 1);
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Translates the sign-magnitude representation of a BigInteger into a
jaroslav@1258: * BigInteger. The sign is represented as an integer signum value: -1 for
jaroslav@1258: * negative, 0 for zero, or 1 for positive. The magnitude is a byte array
jaroslav@1258: * in big-endian byte-order: the most significant byte is in the
jaroslav@1258: * zeroth element. A zero-length magnitude array is permissible, and will
jaroslav@1258: * result in a BigInteger value of 0, whether signum is -1, 0 or 1.
jaroslav@1258: *
jaroslav@1258: * @param signum signum of the number (-1 for negative, 0 for zero, 1
jaroslav@1258: * for positive).
jaroslav@1258: * @param magnitude big-endian binary representation of the magnitude of
jaroslav@1258: * the number.
jaroslav@1258: * @throws NumberFormatException {@code signum} is not one of the three
jaroslav@1258: * legal values (-1, 0, and 1), or {@code signum} is 0 and
jaroslav@1258: * {@code magnitude} contains one or more non-zero bytes.
jaroslav@1258: */
jaroslav@1258: public BigInteger(int signum, byte[] magnitude) {
jaroslav@1258: this.mag = stripLeadingZeroBytes(magnitude);
jaroslav@1258:
jaroslav@1258: if (signum < -1 || signum > 1)
jaroslav@1258: throw(new NumberFormatException("Invalid signum value"));
jaroslav@1258:
jaroslav@1258: if (this.mag.length==0) {
jaroslav@1258: this.signum = 0;
jaroslav@1258: } else {
jaroslav@1258: if (signum == 0)
jaroslav@1258: throw(new NumberFormatException("signum-magnitude mismatch"));
jaroslav@1258: this.signum = signum;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * A constructor for internal use that translates the sign-magnitude
jaroslav@1258: * representation of a BigInteger into a BigInteger. It checks the
jaroslav@1258: * arguments and copies the magnitude so this constructor would be
jaroslav@1258: * safe for external use.
jaroslav@1258: */
jaroslav@1258: private BigInteger(int signum, int[] magnitude) {
jaroslav@1258: this.mag = stripLeadingZeroInts(magnitude);
jaroslav@1258:
jaroslav@1258: if (signum < -1 || signum > 1)
jaroslav@1258: throw(new NumberFormatException("Invalid signum value"));
jaroslav@1258:
jaroslav@1258: if (this.mag.length==0) {
jaroslav@1258: this.signum = 0;
jaroslav@1258: } else {
jaroslav@1258: if (signum == 0)
jaroslav@1258: throw(new NumberFormatException("signum-magnitude mismatch"));
jaroslav@1258: this.signum = signum;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Translates the String representation of a BigInteger in the
jaroslav@1258: * specified radix into a BigInteger. The String representation
jaroslav@1258: * consists of an optional minus or plus sign followed by a
jaroslav@1258: * sequence of one or more digits in the specified radix. The
jaroslav@1258: * character-to-digit mapping is provided by {@code
jaroslav@1258: * Character.digit}. The String may not contain any extraneous
jaroslav@1258: * characters (whitespace, for example).
jaroslav@1258: *
jaroslav@1258: * @param val String representation of BigInteger.
jaroslav@1258: * @param radix radix to be used in interpreting {@code val}.
jaroslav@1258: * @throws NumberFormatException {@code val} is not a valid representation
jaroslav@1258: * of a BigInteger in the specified radix, or {@code radix} is
jaroslav@1258: * outside the range from {@link Character#MIN_RADIX} to
jaroslav@1258: * {@link Character#MAX_RADIX}, inclusive.
jaroslav@1258: * @see Character#digit
jaroslav@1258: */
jaroslav@1258: public BigInteger(String val, int radix) {
jaroslav@1258: int cursor = 0, numDigits;
jaroslav@1258: final int len = val.length();
jaroslav@1258:
jaroslav@1258: if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
jaroslav@1258: throw new NumberFormatException("Radix out of range");
jaroslav@1258: if (len == 0)
jaroslav@1258: throw new NumberFormatException("Zero length BigInteger");
jaroslav@1258:
jaroslav@1258: // Check for at most one leading sign
jaroslav@1258: int sign = 1;
jaroslav@1258: int index1 = val.lastIndexOf('-');
jaroslav@1258: int index2 = val.lastIndexOf('+');
jaroslav@1258: if ((index1 + index2) <= -1) {
jaroslav@1258: // No leading sign character or at most one leading sign character
jaroslav@1258: if (index1 == 0 || index2 == 0) {
jaroslav@1258: cursor = 1;
jaroslav@1258: if (len == 1)
jaroslav@1258: throw new NumberFormatException("Zero length BigInteger");
jaroslav@1258: }
jaroslav@1258: if (index1 == 0)
jaroslav@1258: sign = -1;
jaroslav@1258: } else
jaroslav@1258: throw new NumberFormatException("Illegal embedded sign character");
jaroslav@1258:
jaroslav@1258: // Skip leading zeros and compute number of digits in magnitude
jaroslav@1258: while (cursor < len &&
jaroslav@1258: Character.digit(val.charAt(cursor), radix) == 0)
jaroslav@1258: cursor++;
jaroslav@1258: if (cursor == len) {
jaroslav@1258: signum = 0;
jaroslav@1258: mag = ZERO.mag;
jaroslav@1258: return;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: numDigits = len - cursor;
jaroslav@1258: signum = sign;
jaroslav@1258:
jaroslav@1258: // Pre-allocate array of expected size. May be too large but can
jaroslav@1258: // never be too small. Typically exact.
jaroslav@1258: int numBits = (int)(((numDigits * bitsPerDigit[radix]) >>> 10) + 1);
jaroslav@1258: int numWords = (numBits + 31) >>> 5;
jaroslav@1258: int[] magnitude = new int[numWords];
jaroslav@1258:
jaroslav@1258: // Process first (potentially short) digit group
jaroslav@1258: int firstGroupLen = numDigits % digitsPerInt[radix];
jaroslav@1258: if (firstGroupLen == 0)
jaroslav@1258: firstGroupLen = digitsPerInt[radix];
jaroslav@1258: String group = val.substring(cursor, cursor += firstGroupLen);
jaroslav@1258: magnitude[numWords - 1] = Integer.parseInt(group, radix);
jaroslav@1258: if (magnitude[numWords - 1] < 0)
jaroslav@1258: throw new NumberFormatException("Illegal digit");
jaroslav@1258:
jaroslav@1258: // Process remaining digit groups
jaroslav@1258: int superRadix = intRadix[radix];
jaroslav@1258: int groupVal = 0;
jaroslav@1258: while (cursor < len) {
jaroslav@1258: group = val.substring(cursor, cursor += digitsPerInt[radix]);
jaroslav@1258: groupVal = Integer.parseInt(group, radix);
jaroslav@1258: if (groupVal < 0)
jaroslav@1258: throw new NumberFormatException("Illegal digit");
jaroslav@1258: destructiveMulAdd(magnitude, superRadix, groupVal);
jaroslav@1258: }
jaroslav@1258: // Required for cases where the array was overallocated.
jaroslav@1258: mag = trustedStripLeadingZeroInts(magnitude);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Constructs a new BigInteger using a char array with radix=10
jaroslav@1258: BigInteger(char[] val) {
jaroslav@1258: int cursor = 0, numDigits;
jaroslav@1258: int len = val.length;
jaroslav@1258:
jaroslav@1258: // Check for leading minus sign
jaroslav@1258: int sign = 1;
jaroslav@1258: if (val[0] == '-') {
jaroslav@1258: if (len == 1)
jaroslav@1258: throw new NumberFormatException("Zero length BigInteger");
jaroslav@1258: sign = -1;
jaroslav@1258: cursor = 1;
jaroslav@1258: } else if (val[0] == '+') {
jaroslav@1258: if (len == 1)
jaroslav@1258: throw new NumberFormatException("Zero length BigInteger");
jaroslav@1258: cursor = 1;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Skip leading zeros and compute number of digits in magnitude
jaroslav@1258: while (cursor < len && Character.digit(val[cursor], 10) == 0)
jaroslav@1258: cursor++;
jaroslav@1258: if (cursor == len) {
jaroslav@1258: signum = 0;
jaroslav@1258: mag = ZERO.mag;
jaroslav@1258: return;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: numDigits = len - cursor;
jaroslav@1258: signum = sign;
jaroslav@1258:
jaroslav@1258: // Pre-allocate array of expected size
jaroslav@1258: int numWords;
jaroslav@1258: if (len < 10) {
jaroslav@1258: numWords = 1;
jaroslav@1258: } else {
jaroslav@1258: int numBits = (int)(((numDigits * bitsPerDigit[10]) >>> 10) + 1);
jaroslav@1258: numWords = (numBits + 31) >>> 5;
jaroslav@1258: }
jaroslav@1258: int[] magnitude = new int[numWords];
jaroslav@1258:
jaroslav@1258: // Process first (potentially short) digit group
jaroslav@1258: int firstGroupLen = numDigits % digitsPerInt[10];
jaroslav@1258: if (firstGroupLen == 0)
jaroslav@1258: firstGroupLen = digitsPerInt[10];
jaroslav@1258: magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen);
jaroslav@1258:
jaroslav@1258: // Process remaining digit groups
jaroslav@1258: while (cursor < len) {
jaroslav@1258: int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
jaroslav@1258: destructiveMulAdd(magnitude, intRadix[10], groupVal);
jaroslav@1258: }
jaroslav@1258: mag = trustedStripLeadingZeroInts(magnitude);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Create an integer with the digits between the two indexes
jaroslav@1258: // Assumes start < end. The result may be negative, but it
jaroslav@1258: // is to be treated as an unsigned value.
jaroslav@1258: private int parseInt(char[] source, int start, int end) {
jaroslav@1258: int result = Character.digit(source[start++], 10);
jaroslav@1258: if (result == -1)
jaroslav@1258: throw new NumberFormatException(new String(source));
jaroslav@1258:
jaroslav@1258: for (int index = start; index= 0; i--) {
jaroslav@1258: product = ylong * (x[i] & LONG_MASK) + carry;
jaroslav@1258: x[i] = (int)product;
jaroslav@1258: carry = product >>> 32;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Perform the addition
jaroslav@1258: long sum = (x[len-1] & LONG_MASK) + zlong;
jaroslav@1258: x[len-1] = (int)sum;
jaroslav@1258: carry = sum >>> 32;
jaroslav@1258: for (int i = len-2; i >= 0; i--) {
jaroslav@1258: sum = (x[i] & LONG_MASK) + carry;
jaroslav@1258: x[i] = (int)sum;
jaroslav@1258: carry = sum >>> 32;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Translates the decimal String representation of a BigInteger into a
jaroslav@1258: * BigInteger. The String representation consists of an optional minus
jaroslav@1258: * sign followed by a sequence of one or more decimal digits. The
jaroslav@1258: * character-to-digit mapping is provided by {@code Character.digit}.
jaroslav@1258: * The String may not contain any extraneous characters (whitespace, for
jaroslav@1258: * example).
jaroslav@1258: *
jaroslav@1258: * @param val decimal String representation of BigInteger.
jaroslav@1258: * @throws NumberFormatException {@code val} is not a valid representation
jaroslav@1258: * of a BigInteger.
jaroslav@1258: * @see Character#digit
jaroslav@1258: */
jaroslav@1258: public BigInteger(String val) {
jaroslav@1258: this(val, 10);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Constructs a randomly generated BigInteger, uniformly distributed over
jaroslav@1258: * the range 0 to (2{@code numBits} - 1), inclusive.
jaroslav@1258: * The uniformity of the distribution assumes that a fair source of random
jaroslav@1258: * bits is provided in {@code rnd}. Note that this constructor always
jaroslav@1258: * constructs a non-negative BigInteger.
jaroslav@1258: *
jaroslav@1258: * @param numBits maximum bitLength of the new BigInteger.
jaroslav@1258: * @param rnd source of randomness to be used in computing the new
jaroslav@1258: * BigInteger.
jaroslav@1258: * @throws IllegalArgumentException {@code numBits} is negative.
jaroslav@1258: * @see #bitLength()
jaroslav@1258: */
jaroslav@1258: public BigInteger(int numBits, Random rnd) {
jaroslav@1258: this(1, randomBits(numBits, rnd));
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: private static byte[] randomBits(int numBits, Random rnd) {
jaroslav@1258: if (numBits < 0)
jaroslav@1258: throw new IllegalArgumentException("numBits must be non-negative");
jaroslav@1258: int numBytes = (int)(((long)numBits+7)/8); // avoid overflow
jaroslav@1258: byte[] randomBits = new byte[numBytes];
jaroslav@1258:
jaroslav@1258: // Generate random bytes and mask out any excess bits
jaroslav@1258: if (numBytes > 0) {
jaroslav@1258: rnd.nextBytes(randomBits);
jaroslav@1258: int excessBits = 8*numBytes - numBits;
jaroslav@1258: randomBits[0] &= (1 << (8-excessBits)) - 1;
jaroslav@1258: }
jaroslav@1258: return randomBits;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Constructs a randomly generated positive BigInteger that is probably
jaroslav@1258: * prime, with the specified bitLength.
jaroslav@1258: *
jaroslav@1258: * It is recommended that the {@link #probablePrime probablePrime}
jaroslav@1258: * method be used in preference to this constructor unless there
jaroslav@1258: * is a compelling need to specify a certainty.
jaroslav@1258: *
jaroslav@1258: * @param bitLength bitLength of the returned BigInteger.
jaroslav@1258: * @param certainty a measure of the uncertainty that the caller is
jaroslav@1258: * willing to tolerate. The probability that the new BigInteger
jaroslav@1258: * represents a prime number will exceed
jaroslav@1258: * (1 - 1/2{@code certainty}). The execution time of
jaroslav@1258: * this constructor is proportional to the value of this parameter.
jaroslav@1258: * @param rnd source of random bits used to select candidates to be
jaroslav@1258: * tested for primality.
jaroslav@1258: * @throws ArithmeticException {@code bitLength < 2}.
jaroslav@1258: * @see #bitLength()
jaroslav@1258: */
jaroslav@1258: public BigInteger(int bitLength, int certainty, Random rnd) {
jaroslav@1258: BigInteger prime;
jaroslav@1258:
jaroslav@1258: if (bitLength < 2)
jaroslav@1258: throw new ArithmeticException("bitLength < 2");
jaroslav@1258: // The cutoff of 95 was chosen empirically for best performance
jaroslav@1258: prime = (bitLength < 95 ? smallPrime(bitLength, certainty, rnd)
jaroslav@1258: : largePrime(bitLength, certainty, rnd));
jaroslav@1258: signum = 1;
jaroslav@1258: mag = prime.mag;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Minimum size in bits that the requested prime number has
jaroslav@1258: // before we use the large prime number generating algorithms
jaroslav@1258: private static final int SMALL_PRIME_THRESHOLD = 95;
jaroslav@1258:
jaroslav@1258: // Certainty required to meet the spec of probablePrime
jaroslav@1258: private static final int DEFAULT_PRIME_CERTAINTY = 100;
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a positive BigInteger that is probably prime, with the
jaroslav@1258: * specified bitLength. The probability that a BigInteger returned
jaroslav@1258: * by this method is composite does not exceed 2-100.
jaroslav@1258: *
jaroslav@1258: * @param bitLength bitLength of the returned BigInteger.
jaroslav@1258: * @param rnd source of random bits used to select candidates to be
jaroslav@1258: * tested for primality.
jaroslav@1258: * @return a BigInteger of {@code bitLength} bits that is probably prime
jaroslav@1258: * @throws ArithmeticException {@code bitLength < 2}.
jaroslav@1258: * @see #bitLength()
jaroslav@1258: * @since 1.4
jaroslav@1258: */
jaroslav@1258: public static BigInteger probablePrime(int bitLength, Random rnd) {
jaroslav@1258: if (bitLength < 2)
jaroslav@1258: throw new ArithmeticException("bitLength < 2");
jaroslav@1258:
jaroslav@1258: // The cutoff of 95 was chosen empirically for best performance
jaroslav@1258: return (bitLength < SMALL_PRIME_THRESHOLD ?
jaroslav@1258: smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
jaroslav@1258: largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Find a random number of the specified bitLength that is probably prime.
jaroslav@1258: * This method is used for smaller primes, its performance degrades on
jaroslav@1258: * larger bitlengths.
jaroslav@1258: *
jaroslav@1258: * This method assumes bitLength > 1.
jaroslav@1258: */
jaroslav@1258: private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
jaroslav@1258: int magLen = (bitLength + 31) >>> 5;
jaroslav@1258: int temp[] = new int[magLen];
jaroslav@1258: int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int
jaroslav@1258: int highMask = (highBit << 1) - 1; // Bits to keep in high int
jaroslav@1258:
jaroslav@1258: while(true) {
jaroslav@1258: // Construct a candidate
jaroslav@1258: for (int i=0; i 2)
jaroslav@1258: temp[magLen-1] |= 1; // Make odd if bitlen > 2
jaroslav@1258:
jaroslav@1258: BigInteger p = new BigInteger(temp, 1);
jaroslav@1258:
jaroslav@1258: // Do cheap "pre-test" if applicable
jaroslav@1258: if (bitLength > 6) {
jaroslav@1258: long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
jaroslav@1258: if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
jaroslav@1258: (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
jaroslav@1258: (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
jaroslav@1258: continue; // Candidate is composite; try another
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // All candidates of bitLength 2 and 3 are prime by this point
jaroslav@1258: if (bitLength < 4)
jaroslav@1258: return p;
jaroslav@1258:
jaroslav@1258: // Do expensive test if we survive pre-test (or it's inapplicable)
jaroslav@1258: if (p.primeToCertainty(certainty, rnd))
jaroslav@1258: return p;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: private static final BigInteger SMALL_PRIME_PRODUCT
jaroslav@1258: = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Find a random number of the specified bitLength that is probably prime.
jaroslav@1258: * This method is more appropriate for larger bitlengths since it uses
jaroslav@1258: * a sieve to eliminate most composites before using a more expensive
jaroslav@1258: * test.
jaroslav@1258: */
jaroslav@1258: private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
jaroslav@1258: BigInteger p;
jaroslav@1258: p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
jaroslav@1258: p.mag[p.mag.length-1] &= 0xfffffffe;
jaroslav@1258:
jaroslav@1258: // Use a sieve length likely to contain the next prime number
jaroslav@1258: int searchLen = (bitLength / 20) * 64;
jaroslav@1258: BitSieve searchSieve = new BitSieve(p, searchLen);
jaroslav@1258: BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);
jaroslav@1258:
jaroslav@1258: while ((candidate == null) || (candidate.bitLength() != bitLength)) {
jaroslav@1258: p = p.add(BigInteger.valueOf(2*searchLen));
jaroslav@1258: if (p.bitLength() != bitLength)
jaroslav@1258: p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
jaroslav@1258: p.mag[p.mag.length-1] &= 0xfffffffe;
jaroslav@1258: searchSieve = new BitSieve(p, searchLen);
jaroslav@1258: candidate = searchSieve.retrieve(p, certainty, rnd);
jaroslav@1258: }
jaroslav@1258: return candidate;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the first integer greater than this {@code BigInteger} that
jaroslav@1258: * is probably prime. The probability that the number returned by this
jaroslav@1258: * method is composite does not exceed 2-100. This method will
jaroslav@1258: * never skip over a prime when searching: if it returns {@code p}, there
jaroslav@1258: * is no prime {@code q} such that {@code this < q < p}.
jaroslav@1258: *
jaroslav@1258: * @return the first integer greater than this {@code BigInteger} that
jaroslav@1258: * is probably prime.
jaroslav@1258: * @throws ArithmeticException {@code this < 0}.
jaroslav@1258: * @since 1.5
jaroslav@1258: */
jaroslav@1258: public BigInteger nextProbablePrime() {
jaroslav@1258: if (this.signum < 0)
jaroslav@1258: throw new ArithmeticException("start < 0: " + this);
jaroslav@1258:
jaroslav@1258: // Handle trivial cases
jaroslav@1258: if ((this.signum == 0) || this.equals(ONE))
jaroslav@1258: return TWO;
jaroslav@1258:
jaroslav@1258: BigInteger result = this.add(ONE);
jaroslav@1258:
jaroslav@1258: // Fastpath for small numbers
jaroslav@1258: if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
jaroslav@1258:
jaroslav@1258: // Ensure an odd number
jaroslav@1258: if (!result.testBit(0))
jaroslav@1258: result = result.add(ONE);
jaroslav@1258:
jaroslav@1258: while(true) {
jaroslav@1258: // Do cheap "pre-test" if applicable
jaroslav@1258: if (result.bitLength() > 6) {
jaroslav@1258: long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
jaroslav@1258: if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
jaroslav@1258: (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
jaroslav@1258: (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {
jaroslav@1258: result = result.add(TWO);
jaroslav@1258: continue; // Candidate is composite; try another
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // All candidates of bitLength 2 and 3 are prime by this point
jaroslav@1258: if (result.bitLength() < 4)
jaroslav@1258: return result;
jaroslav@1258:
jaroslav@1258: // The expensive test
jaroslav@1258: if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))
jaroslav@1258: return result;
jaroslav@1258:
jaroslav@1258: result = result.add(TWO);
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Start at previous even number
jaroslav@1258: if (result.testBit(0))
jaroslav@1258: result = result.subtract(ONE);
jaroslav@1258:
jaroslav@1258: // Looking for the next large prime
jaroslav@1258: int searchLen = (result.bitLength() / 20) * 64;
jaroslav@1258:
jaroslav@1258: while(true) {
jaroslav@1258: BitSieve searchSieve = new BitSieve(result, searchLen);
jaroslav@1258: BigInteger candidate = searchSieve.retrieve(result,
jaroslav@1258: DEFAULT_PRIME_CERTAINTY, null);
jaroslav@1258: if (candidate != null)
jaroslav@1258: return candidate;
jaroslav@1258: result = result.add(BigInteger.valueOf(2 * searchLen));
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns {@code true} if this BigInteger is probably prime,
jaroslav@1258: * {@code false} if it's definitely composite.
jaroslav@1258: *
jaroslav@1258: * This method assumes bitLength > 2.
jaroslav@1258: *
jaroslav@1258: * @param certainty a measure of the uncertainty that the caller is
jaroslav@1258: * willing to tolerate: if the call returns {@code true}
jaroslav@1258: * the probability that this BigInteger is prime exceeds
jaroslav@1258: * {@code (1 - 1/2certainty)}. The execution time of
jaroslav@1258: * this method is proportional to the value of this parameter.
jaroslav@1258: * @return {@code true} if this BigInteger is probably prime,
jaroslav@1258: * {@code false} if it's definitely composite.
jaroslav@1258: */
jaroslav@1258: boolean primeToCertainty(int certainty, Random random) {
jaroslav@1258: int rounds = 0;
jaroslav@1258: int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;
jaroslav@1258:
jaroslav@1258: // The relationship between the certainty and the number of rounds
jaroslav@1258: // we perform is given in the draft standard ANSI X9.80, "PRIME
jaroslav@1258: // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
jaroslav@1258: int sizeInBits = this.bitLength();
jaroslav@1258: if (sizeInBits < 100) {
jaroslav@1258: rounds = 50;
jaroslav@1258: rounds = n < rounds ? n : rounds;
jaroslav@1258: return passesMillerRabin(rounds, random);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: if (sizeInBits < 256) {
jaroslav@1258: rounds = 27;
jaroslav@1258: } else if (sizeInBits < 512) {
jaroslav@1258: rounds = 15;
jaroslav@1258: } else if (sizeInBits < 768) {
jaroslav@1258: rounds = 8;
jaroslav@1258: } else if (sizeInBits < 1024) {
jaroslav@1258: rounds = 4;
jaroslav@1258: } else {
jaroslav@1258: rounds = 2;
jaroslav@1258: }
jaroslav@1258: rounds = n < rounds ? n : rounds;
jaroslav@1258:
jaroslav@1258: return passesMillerRabin(rounds, random) && passesLucasLehmer();
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns true iff this BigInteger is a Lucas-Lehmer probable prime.
jaroslav@1258: *
jaroslav@1258: * The following assumptions are made:
jaroslav@1258: * This BigInteger is a positive, odd number.
jaroslav@1258: */
jaroslav@1258: private boolean passesLucasLehmer() {
jaroslav@1258: BigInteger thisPlusOne = this.add(ONE);
jaroslav@1258:
jaroslav@1258: // Step 1
jaroslav@1258: int d = 5;
jaroslav@1258: while (jacobiSymbol(d, this) != -1) {
jaroslav@1258: // 5, -7, 9, -11, ...
jaroslav@1258: d = (d<0) ? Math.abs(d)+2 : -(d+2);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Step 2
jaroslav@1258: BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);
jaroslav@1258:
jaroslav@1258: // Step 3
jaroslav@1258: return u.mod(this).equals(ZERO);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Computes Jacobi(p,n).
jaroslav@1258: * Assumes n positive, odd, n>=3.
jaroslav@1258: */
jaroslav@1258: private static int jacobiSymbol(int p, BigInteger n) {
jaroslav@1258: if (p == 0)
jaroslav@1258: return 0;
jaroslav@1258:
jaroslav@1258: // Algorithm and comments adapted from Colin Plumb's C library.
jaroslav@1258: int j = 1;
jaroslav@1258: int u = n.mag[n.mag.length-1];
jaroslav@1258:
jaroslav@1258: // Make p positive
jaroslav@1258: if (p < 0) {
jaroslav@1258: p = -p;
jaroslav@1258: int n8 = u & 7;
jaroslav@1258: if ((n8 == 3) || (n8 == 7))
jaroslav@1258: j = -j; // 3 (011) or 7 (111) mod 8
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Get rid of factors of 2 in p
jaroslav@1258: while ((p & 3) == 0)
jaroslav@1258: p >>= 2;
jaroslav@1258: if ((p & 1) == 0) {
jaroslav@1258: p >>= 1;
jaroslav@1258: if (((u ^ (u>>1)) & 2) != 0)
jaroslav@1258: j = -j; // 3 (011) or 5 (101) mod 8
jaroslav@1258: }
jaroslav@1258: if (p == 1)
jaroslav@1258: return j;
jaroslav@1258: // Then, apply quadratic reciprocity
jaroslav@1258: if ((p & u & 2) != 0) // p = u = 3 (mod 4)?
jaroslav@1258: j = -j;
jaroslav@1258: // And reduce u mod p
jaroslav@1258: u = n.mod(BigInteger.valueOf(p)).intValue();
jaroslav@1258:
jaroslav@1258: // Now compute Jacobi(u,p), u < p
jaroslav@1258: while (u != 0) {
jaroslav@1258: while ((u & 3) == 0)
jaroslav@1258: u >>= 2;
jaroslav@1258: if ((u & 1) == 0) {
jaroslav@1258: u >>= 1;
jaroslav@1258: if (((p ^ (p>>1)) & 2) != 0)
jaroslav@1258: j = -j; // 3 (011) or 5 (101) mod 8
jaroslav@1258: }
jaroslav@1258: if (u == 1)
jaroslav@1258: return j;
jaroslav@1258: // Now both u and p are odd, so use quadratic reciprocity
jaroslav@1258: assert (u < p);
jaroslav@1258: int t = u; u = p; p = t;
jaroslav@1258: if ((u & p & 2) != 0) // u = p = 3 (mod 4)?
jaroslav@1258: j = -j;
jaroslav@1258: // Now u >= p, so it can be reduced
jaroslav@1258: u %= p;
jaroslav@1258: }
jaroslav@1258: return 0;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
jaroslav@1258: BigInteger d = BigInteger.valueOf(z);
jaroslav@1258: BigInteger u = ONE; BigInteger u2;
jaroslav@1258: BigInteger v = ONE; BigInteger v2;
jaroslav@1258:
jaroslav@1258: for (int i=k.bitLength()-2; i>=0; i--) {
jaroslav@1258: u2 = u.multiply(v).mod(n);
jaroslav@1258:
jaroslav@1258: v2 = v.square().add(d.multiply(u.square())).mod(n);
jaroslav@1258: if (v2.testBit(0))
jaroslav@1258: v2 = v2.subtract(n);
jaroslav@1258:
jaroslav@1258: v2 = v2.shiftRight(1);
jaroslav@1258:
jaroslav@1258: u = u2; v = v2;
jaroslav@1258: if (k.testBit(i)) {
jaroslav@1258: u2 = u.add(v).mod(n);
jaroslav@1258: if (u2.testBit(0))
jaroslav@1258: u2 = u2.subtract(n);
jaroslav@1258:
jaroslav@1258: u2 = u2.shiftRight(1);
jaroslav@1258: v2 = v.add(d.multiply(u)).mod(n);
jaroslav@1258: if (v2.testBit(0))
jaroslav@1258: v2 = v2.subtract(n);
jaroslav@1258: v2 = v2.shiftRight(1);
jaroslav@1258:
jaroslav@1258: u = u2; v = v2;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258: return u;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: private static volatile Random staticRandom;
jaroslav@1258:
jaroslav@1258: private static Random getSecureRandom() {
jaroslav@1258: if (staticRandom == null) {
jaroslav@1258: staticRandom = new java.security.SecureRandom();
jaroslav@1258: }
jaroslav@1258: return staticRandom;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns true iff this BigInteger passes the specified number of
jaroslav@1258: * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
jaroslav@1258: * 186-2).
jaroslav@1258: *
jaroslav@1258: * The following assumptions are made:
jaroslav@1258: * This BigInteger is a positive, odd number greater than 2.
jaroslav@1258: * iterations<=50.
jaroslav@1258: */
jaroslav@1258: private boolean passesMillerRabin(int iterations, Random rnd) {
jaroslav@1258: // Find a and m such that m is odd and this == 1 + 2**a * m
jaroslav@1258: BigInteger thisMinusOne = this.subtract(ONE);
jaroslav@1258: BigInteger m = thisMinusOne;
jaroslav@1258: int a = m.getLowestSetBit();
jaroslav@1258: m = m.shiftRight(a);
jaroslav@1258:
jaroslav@1258: // Do the tests
jaroslav@1258: if (rnd == null) {
jaroslav@1258: rnd = getSecureRandom();
jaroslav@1258: }
jaroslav@1258: for (int i=0; i= 0);
jaroslav@1258:
jaroslav@1258: int j = 0;
jaroslav@1258: BigInteger z = b.modPow(m, this);
jaroslav@1258: while(!((j==0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
jaroslav@1258: if (j>0 && z.equals(ONE) || ++j==a)
jaroslav@1258: return false;
jaroslav@1258: z = z.modPow(TWO, this);
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258: return true;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * This internal constructor differs from its public cousin
jaroslav@1258: * with the arguments reversed in two ways: it assumes that its
jaroslav@1258: * arguments are correct, and it doesn't copy the magnitude array.
jaroslav@1258: */
jaroslav@1258: BigInteger(int[] magnitude, int signum) {
jaroslav@1258: this.signum = (magnitude.length==0 ? 0 : signum);
jaroslav@1258: this.mag = magnitude;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * This private constructor is for internal use and assumes that its
jaroslav@1258: * arguments are correct.
jaroslav@1258: */
jaroslav@1258: private BigInteger(byte[] magnitude, int signum) {
jaroslav@1258: this.signum = (magnitude.length==0 ? 0 : signum);
jaroslav@1258: this.mag = stripLeadingZeroBytes(magnitude);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: //Static Factory Methods
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is equal to that of the
jaroslav@1258: * specified {@code long}. This "static factory method" is
jaroslav@1258: * provided in preference to a ({@code long}) constructor
jaroslav@1258: * because it allows for reuse of frequently used BigIntegers.
jaroslav@1258: *
jaroslav@1258: * @param val value of the BigInteger to return.
jaroslav@1258: * @return a BigInteger with the specified value.
jaroslav@1258: */
jaroslav@1258: public static BigInteger valueOf(long val) {
jaroslav@1258: // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
jaroslav@1258: if (val == 0)
jaroslav@1258: return ZERO;
jaroslav@1258: if (val > 0 && val <= MAX_CONSTANT)
jaroslav@1258: return posConst[(int) val];
jaroslav@1258: else if (val < 0 && val >= -MAX_CONSTANT)
jaroslav@1258: return negConst[(int) -val];
jaroslav@1258:
jaroslav@1258: return new BigInteger(val);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Constructs a BigInteger with the specified value, which may not be zero.
jaroslav@1258: */
jaroslav@1258: private BigInteger(long val) {
jaroslav@1258: if (val < 0) {
jaroslav@1258: val = -val;
jaroslav@1258: signum = -1;
jaroslav@1258: } else {
jaroslav@1258: signum = 1;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: int highWord = (int)(val >>> 32);
jaroslav@1258: if (highWord==0) {
jaroslav@1258: mag = new int[1];
jaroslav@1258: mag[0] = (int)val;
jaroslav@1258: } else {
jaroslav@1258: mag = new int[2];
jaroslav@1258: mag[0] = highWord;
jaroslav@1258: mag[1] = (int)val;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger with the given two's complement representation.
jaroslav@1258: * Assumes that the input array will not be modified (the returned
jaroslav@1258: * BigInteger will reference the input array if feasible).
jaroslav@1258: */
jaroslav@1258: private static BigInteger valueOf(int val[]) {
jaroslav@1258: return (val[0]>0 ? new BigInteger(val, 1) : new BigInteger(val));
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Constants
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Initialize static constant array when class is loaded.
jaroslav@1258: */
jaroslav@1258: private final static int MAX_CONSTANT = 16;
jaroslav@1258: private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
jaroslav@1258: private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
jaroslav@1258: static {
jaroslav@1258: for (int i = 1; i <= MAX_CONSTANT; i++) {
jaroslav@1258: int[] magnitude = new int[1];
jaroslav@1258: magnitude[0] = i;
jaroslav@1258: posConst[i] = new BigInteger(magnitude, 1);
jaroslav@1258: negConst[i] = new BigInteger(magnitude, -1);
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * The BigInteger constant zero.
jaroslav@1258: *
jaroslav@1258: * @since 1.2
jaroslav@1258: */
jaroslav@1258: public static final BigInteger ZERO = new BigInteger(new int[0], 0);
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * The BigInteger constant one.
jaroslav@1258: *
jaroslav@1258: * @since 1.2
jaroslav@1258: */
jaroslav@1258: public static final BigInteger ONE = valueOf(1);
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * The BigInteger constant two. (Not exported.)
jaroslav@1258: */
jaroslav@1258: private static final BigInteger TWO = valueOf(2);
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * The BigInteger constant ten.
jaroslav@1258: *
jaroslav@1258: * @since 1.5
jaroslav@1258: */
jaroslav@1258: public static final BigInteger TEN = valueOf(10);
jaroslav@1258:
jaroslav@1258: // Arithmetic Operations
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (this + val)}.
jaroslav@1258: *
jaroslav@1258: * @param val value to be added to this BigInteger.
jaroslav@1258: * @return {@code this + val}
jaroslav@1258: */
jaroslav@1258: public BigInteger add(BigInteger val) {
jaroslav@1258: if (val.signum == 0)
jaroslav@1258: return this;
jaroslav@1258: if (signum == 0)
jaroslav@1258: return val;
jaroslav@1258: if (val.signum == signum)
jaroslav@1258: return new BigInteger(add(mag, val.mag), signum);
jaroslav@1258:
jaroslav@1258: int cmp = compareMagnitude(val);
jaroslav@1258: if (cmp == 0)
jaroslav@1258: return ZERO;
jaroslav@1258: int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
jaroslav@1258: : subtract(val.mag, mag));
jaroslav@1258: resultMag = trustedStripLeadingZeroInts(resultMag);
jaroslav@1258:
jaroslav@1258: return new BigInteger(resultMag, cmp == signum ? 1 : -1);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Adds the contents of the int arrays x and y. This method allocates
jaroslav@1258: * a new int array to hold the answer and returns a reference to that
jaroslav@1258: * array.
jaroslav@1258: */
jaroslav@1258: private static int[] add(int[] x, int[] y) {
jaroslav@1258: // If x is shorter, swap the two arrays
jaroslav@1258: if (x.length < y.length) {
jaroslav@1258: int[] tmp = x;
jaroslav@1258: x = y;
jaroslav@1258: y = tmp;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: int xIndex = x.length;
jaroslav@1258: int yIndex = y.length;
jaroslav@1258: int result[] = new int[xIndex];
jaroslav@1258: long sum = 0;
jaroslav@1258:
jaroslav@1258: // Add common parts of both numbers
jaroslav@1258: while(yIndex > 0) {
jaroslav@1258: sum = (x[--xIndex] & LONG_MASK) +
jaroslav@1258: (y[--yIndex] & LONG_MASK) + (sum >>> 32);
jaroslav@1258: result[xIndex] = (int)sum;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Copy remainder of longer number while carry propagation is required
jaroslav@1258: boolean carry = (sum >>> 32 != 0);
jaroslav@1258: while (xIndex > 0 && carry)
jaroslav@1258: carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
jaroslav@1258:
jaroslav@1258: // Copy remainder of longer number
jaroslav@1258: while (xIndex > 0)
jaroslav@1258: result[--xIndex] = x[xIndex];
jaroslav@1258:
jaroslav@1258: // Grow result if necessary
jaroslav@1258: if (carry) {
jaroslav@1258: int bigger[] = new int[result.length + 1];
jaroslav@1258: System.arraycopy(result, 0, bigger, 1, result.length);
jaroslav@1258: bigger[0] = 0x01;
jaroslav@1258: return bigger;
jaroslav@1258: }
jaroslav@1258: return result;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (this - val)}.
jaroslav@1258: *
jaroslav@1258: * @param val value to be subtracted from this BigInteger.
jaroslav@1258: * @return {@code this - val}
jaroslav@1258: */
jaroslav@1258: public BigInteger subtract(BigInteger val) {
jaroslav@1258: if (val.signum == 0)
jaroslav@1258: return this;
jaroslav@1258: if (signum == 0)
jaroslav@1258: return val.negate();
jaroslav@1258: if (val.signum != signum)
jaroslav@1258: return new BigInteger(add(mag, val.mag), signum);
jaroslav@1258:
jaroslav@1258: int cmp = compareMagnitude(val);
jaroslav@1258: if (cmp == 0)
jaroslav@1258: return ZERO;
jaroslav@1258: int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
jaroslav@1258: : subtract(val.mag, mag));
jaroslav@1258: resultMag = trustedStripLeadingZeroInts(resultMag);
jaroslav@1258: return new BigInteger(resultMag, cmp == signum ? 1 : -1);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Subtracts the contents of the second int arrays (little) from the
jaroslav@1258: * first (big). The first int array (big) must represent a larger number
jaroslav@1258: * than the second. This method allocates the space necessary to hold the
jaroslav@1258: * answer.
jaroslav@1258: */
jaroslav@1258: private static int[] subtract(int[] big, int[] little) {
jaroslav@1258: int bigIndex = big.length;
jaroslav@1258: int result[] = new int[bigIndex];
jaroslav@1258: int littleIndex = little.length;
jaroslav@1258: long difference = 0;
jaroslav@1258:
jaroslav@1258: // Subtract common parts of both numbers
jaroslav@1258: while(littleIndex > 0) {
jaroslav@1258: difference = (big[--bigIndex] & LONG_MASK) -
jaroslav@1258: (little[--littleIndex] & LONG_MASK) +
jaroslav@1258: (difference >> 32);
jaroslav@1258: result[bigIndex] = (int)difference;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Subtract remainder of longer number while borrow propagates
jaroslav@1258: boolean borrow = (difference >> 32 != 0);
jaroslav@1258: while (bigIndex > 0 && borrow)
jaroslav@1258: borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
jaroslav@1258:
jaroslav@1258: // Copy remainder of longer number
jaroslav@1258: while (bigIndex > 0)
jaroslav@1258: result[--bigIndex] = big[bigIndex];
jaroslav@1258:
jaroslav@1258: return result;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (this * val)}.
jaroslav@1258: *
jaroslav@1258: * @param val value to be multiplied by this BigInteger.
jaroslav@1258: * @return {@code this * val}
jaroslav@1258: */
jaroslav@1258: public BigInteger multiply(BigInteger val) {
jaroslav@1258: if (val.signum == 0 || signum == 0)
jaroslav@1258: return ZERO;
jaroslav@1258:
jaroslav@1258: int[] result = multiplyToLen(mag, mag.length,
jaroslav@1258: val.mag, val.mag.length, null);
jaroslav@1258: result = trustedStripLeadingZeroInts(result);
jaroslav@1258: return new BigInteger(result, signum == val.signum ? 1 : -1);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Package private methods used by BigDecimal code to multiply a BigInteger
jaroslav@1258: * with a long. Assumes v is not equal to INFLATED.
jaroslav@1258: */
jaroslav@1258: BigInteger multiply(long v) {
jaroslav@1258: if (v == 0 || signum == 0)
jaroslav@1258: return ZERO;
jaroslav@1258: if (v == BigDecimal.INFLATED)
jaroslav@1258: return multiply(BigInteger.valueOf(v));
jaroslav@1258: int rsign = (v > 0 ? signum : -signum);
jaroslav@1258: if (v < 0)
jaroslav@1258: v = -v;
jaroslav@1258: long dh = v >>> 32; // higher order bits
jaroslav@1258: long dl = v & LONG_MASK; // lower order bits
jaroslav@1258:
jaroslav@1258: int xlen = mag.length;
jaroslav@1258: int[] value = mag;
jaroslav@1258: int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]);
jaroslav@1258: long carry = 0;
jaroslav@1258: int rstart = rmag.length - 1;
jaroslav@1258: for (int i = xlen - 1; i >= 0; i--) {
jaroslav@1258: long product = (value[i] & LONG_MASK) * dl + carry;
jaroslav@1258: rmag[rstart--] = (int)product;
jaroslav@1258: carry = product >>> 32;
jaroslav@1258: }
jaroslav@1258: rmag[rstart] = (int)carry;
jaroslav@1258: if (dh != 0L) {
jaroslav@1258: carry = 0;
jaroslav@1258: rstart = rmag.length - 2;
jaroslav@1258: for (int i = xlen - 1; i >= 0; i--) {
jaroslav@1258: long product = (value[i] & LONG_MASK) * dh +
jaroslav@1258: (rmag[rstart] & LONG_MASK) + carry;
jaroslav@1258: rmag[rstart--] = (int)product;
jaroslav@1258: carry = product >>> 32;
jaroslav@1258: }
jaroslav@1258: rmag[0] = (int)carry;
jaroslav@1258: }
jaroslav@1258: if (carry == 0L)
jaroslav@1258: rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
jaroslav@1258: return new BigInteger(rmag, rsign);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Multiplies int arrays x and y to the specified lengths and places
jaroslav@1258: * the result into z. There will be no leading zeros in the resultant array.
jaroslav@1258: */
jaroslav@1258: private int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
jaroslav@1258: int xstart = xlen - 1;
jaroslav@1258: int ystart = ylen - 1;
jaroslav@1258:
jaroslav@1258: if (z == null || z.length < (xlen+ ylen))
jaroslav@1258: z = new int[xlen+ylen];
jaroslav@1258:
jaroslav@1258: long carry = 0;
jaroslav@1258: for (int j=ystart, k=ystart+1+xstart; j>=0; j--, k--) {
jaroslav@1258: long product = (y[j] & LONG_MASK) *
jaroslav@1258: (x[xstart] & LONG_MASK) + carry;
jaroslav@1258: z[k] = (int)product;
jaroslav@1258: carry = product >>> 32;
jaroslav@1258: }
jaroslav@1258: z[xstart] = (int)carry;
jaroslav@1258:
jaroslav@1258: for (int i = xstart-1; i >= 0; i--) {
jaroslav@1258: carry = 0;
jaroslav@1258: for (int j=ystart, k=ystart+1+i; j>=0; j--, k--) {
jaroslav@1258: long product = (y[j] & LONG_MASK) *
jaroslav@1258: (x[i] & LONG_MASK) +
jaroslav@1258: (z[k] & LONG_MASK) + carry;
jaroslav@1258: z[k] = (int)product;
jaroslav@1258: carry = product >>> 32;
jaroslav@1258: }
jaroslav@1258: z[i] = (int)carry;
jaroslav@1258: }
jaroslav@1258: return z;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (this2)}.
jaroslav@1258: *
jaroslav@1258: * @return {@code this2}
jaroslav@1258: */
jaroslav@1258: private BigInteger square() {
jaroslav@1258: if (signum == 0)
jaroslav@1258: return ZERO;
jaroslav@1258: int[] z = squareToLen(mag, mag.length, null);
jaroslav@1258: return new BigInteger(trustedStripLeadingZeroInts(z), 1);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Squares the contents of the int array x. The result is placed into the
jaroslav@1258: * int array z. The contents of x are not changed.
jaroslav@1258: */
jaroslav@1258: private static final int[] squareToLen(int[] x, int len, int[] z) {
jaroslav@1258: /*
jaroslav@1258: * The algorithm used here is adapted from Colin Plumb's C library.
jaroslav@1258: * Technique: Consider the partial products in the multiplication
jaroslav@1258: * of "abcde" by itself:
jaroslav@1258: *
jaroslav@1258: * a b c d e
jaroslav@1258: * * a b c d e
jaroslav@1258: * ==================
jaroslav@1258: * ae be ce de ee
jaroslav@1258: * ad bd cd dd de
jaroslav@1258: * ac bc cc cd ce
jaroslav@1258: * ab bb bc bd be
jaroslav@1258: * aa ab ac ad ae
jaroslav@1258: *
jaroslav@1258: * Note that everything above the main diagonal:
jaroslav@1258: * ae be ce de = (abcd) * e
jaroslav@1258: * ad bd cd = (abc) * d
jaroslav@1258: * ac bc = (ab) * c
jaroslav@1258: * ab = (a) * b
jaroslav@1258: *
jaroslav@1258: * is a copy of everything below the main diagonal:
jaroslav@1258: * de
jaroslav@1258: * cd ce
jaroslav@1258: * bc bd be
jaroslav@1258: * ab ac ad ae
jaroslav@1258: *
jaroslav@1258: * Thus, the sum is 2 * (off the diagonal) + diagonal.
jaroslav@1258: *
jaroslav@1258: * This is accumulated beginning with the diagonal (which
jaroslav@1258: * consist of the squares of the digits of the input), which is then
jaroslav@1258: * divided by two, the off-diagonal added, and multiplied by two
jaroslav@1258: * again. The low bit is simply a copy of the low bit of the
jaroslav@1258: * input, so it doesn't need special care.
jaroslav@1258: */
jaroslav@1258: int zlen = len << 1;
jaroslav@1258: if (z == null || z.length < zlen)
jaroslav@1258: z = new int[zlen];
jaroslav@1258:
jaroslav@1258: // Store the squares, right shifted one bit (i.e., divided by 2)
jaroslav@1258: int lastProductLowWord = 0;
jaroslav@1258: for (int j=0, i=0; j>> 33);
jaroslav@1258: z[i++] = (int)(product >>> 1);
jaroslav@1258: lastProductLowWord = (int)product;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Add in off-diagonal sums
jaroslav@1258: for (int i=len, offset=1; i>0; i--, offset+=2) {
jaroslav@1258: int t = x[i-1];
jaroslav@1258: t = mulAdd(z, x, offset, i-1, t);
jaroslav@1258: addOne(z, offset-1, i, t);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Shift back up and set low bit
jaroslav@1258: primitiveLeftShift(z, zlen, 1);
jaroslav@1258: z[zlen-1] |= x[len-1] & 1;
jaroslav@1258:
jaroslav@1258: return z;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (this / val)}.
jaroslav@1258: *
jaroslav@1258: * @param val value by which this BigInteger is to be divided.
jaroslav@1258: * @return {@code this / val}
jaroslav@1258: * @throws ArithmeticException if {@code val} is zero.
jaroslav@1258: */
jaroslav@1258: public BigInteger divide(BigInteger val) {
jaroslav@1258: MutableBigInteger q = new MutableBigInteger(),
jaroslav@1258: a = new MutableBigInteger(this.mag),
jaroslav@1258: b = new MutableBigInteger(val.mag);
jaroslav@1258:
jaroslav@1258: a.divide(b, q);
jaroslav@1258: return q.toBigInteger(this.signum == val.signum ? 1 : -1);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns an array of two BigIntegers containing {@code (this / val)}
jaroslav@1258: * followed by {@code (this % val)}.
jaroslav@1258: *
jaroslav@1258: * @param val value by which this BigInteger is to be divided, and the
jaroslav@1258: * remainder computed.
jaroslav@1258: * @return an array of two BigIntegers: the quotient {@code (this / val)}
jaroslav@1258: * is the initial element, and the remainder {@code (this % val)}
jaroslav@1258: * is the final element.
jaroslav@1258: * @throws ArithmeticException if {@code val} is zero.
jaroslav@1258: */
jaroslav@1258: public BigInteger[] divideAndRemainder(BigInteger val) {
jaroslav@1258: BigInteger[] result = new BigInteger[2];
jaroslav@1258: MutableBigInteger q = new MutableBigInteger(),
jaroslav@1258: a = new MutableBigInteger(this.mag),
jaroslav@1258: b = new MutableBigInteger(val.mag);
jaroslav@1258: MutableBigInteger r = a.divide(b, q);
jaroslav@1258: result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);
jaroslav@1258: result[1] = r.toBigInteger(this.signum);
jaroslav@1258: return result;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (this % val)}.
jaroslav@1258: *
jaroslav@1258: * @param val value by which this BigInteger is to be divided, and the
jaroslav@1258: * remainder computed.
jaroslav@1258: * @return {@code this % val}
jaroslav@1258: * @throws ArithmeticException if {@code val} is zero.
jaroslav@1258: */
jaroslav@1258: public BigInteger remainder(BigInteger val) {
jaroslav@1258: MutableBigInteger q = new MutableBigInteger(),
jaroslav@1258: a = new MutableBigInteger(this.mag),
jaroslav@1258: b = new MutableBigInteger(val.mag);
jaroslav@1258:
jaroslav@1258: return a.divide(b, q).toBigInteger(this.signum);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is (thisexponent).
jaroslav@1258: * Note that {@code exponent} is an integer rather than a BigInteger.
jaroslav@1258: *
jaroslav@1258: * @param exponent exponent to which this BigInteger is to be raised.
jaroslav@1258: * @return thisexponent
jaroslav@1258: * @throws ArithmeticException {@code exponent} is negative. (This would
jaroslav@1258: * cause the operation to yield a non-integer value.)
jaroslav@1258: */
jaroslav@1258: public BigInteger pow(int exponent) {
jaroslav@1258: if (exponent < 0)
jaroslav@1258: throw new ArithmeticException("Negative exponent");
jaroslav@1258: if (signum==0)
jaroslav@1258: return (exponent==0 ? ONE : this);
jaroslav@1258:
jaroslav@1258: // Perform exponentiation using repeated squaring trick
jaroslav@1258: int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
jaroslav@1258: int[] baseToPow2 = this.mag;
jaroslav@1258: int[] result = {1};
jaroslav@1258:
jaroslav@1258: while (exponent != 0) {
jaroslav@1258: if ((exponent & 1)==1) {
jaroslav@1258: result = multiplyToLen(result, result.length,
jaroslav@1258: baseToPow2, baseToPow2.length, null);
jaroslav@1258: result = trustedStripLeadingZeroInts(result);
jaroslav@1258: }
jaroslav@1258: if ((exponent >>>= 1) != 0) {
jaroslav@1258: baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null);
jaroslav@1258: baseToPow2 = trustedStripLeadingZeroInts(baseToPow2);
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258: return new BigInteger(result, newSign);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is the greatest common divisor of
jaroslav@1258: * {@code abs(this)} and {@code abs(val)}. Returns 0 if
jaroslav@1258: * {@code this==0 && val==0}.
jaroslav@1258: *
jaroslav@1258: * @param val value with which the GCD is to be computed.
jaroslav@1258: * @return {@code GCD(abs(this), abs(val))}
jaroslav@1258: */
jaroslav@1258: public BigInteger gcd(BigInteger val) {
jaroslav@1258: if (val.signum == 0)
jaroslav@1258: return this.abs();
jaroslav@1258: else if (this.signum == 0)
jaroslav@1258: return val.abs();
jaroslav@1258:
jaroslav@1258: MutableBigInteger a = new MutableBigInteger(this);
jaroslav@1258: MutableBigInteger b = new MutableBigInteger(val);
jaroslav@1258:
jaroslav@1258: MutableBigInteger result = a.hybridGCD(b);
jaroslav@1258:
jaroslav@1258: return result.toBigInteger(1);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Package private method to return bit length for an integer.
jaroslav@1258: */
jaroslav@1258: static int bitLengthForInt(int n) {
jaroslav@1258: return 32 - Integer.numberOfLeadingZeros(n);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Left shift int array a up to len by n bits. Returns the array that
jaroslav@1258: * results from the shift since space may have to be reallocated.
jaroslav@1258: */
jaroslav@1258: private static int[] leftShift(int[] a, int len, int n) {
jaroslav@1258: int nInts = n >>> 5;
jaroslav@1258: int nBits = n&0x1F;
jaroslav@1258: int bitsInHighWord = bitLengthForInt(a[0]);
jaroslav@1258:
jaroslav@1258: // If shift can be done without recopy, do so
jaroslav@1258: if (n <= (32-bitsInHighWord)) {
jaroslav@1258: primitiveLeftShift(a, len, nBits);
jaroslav@1258: return a;
jaroslav@1258: } else { // Array must be resized
jaroslav@1258: if (nBits <= (32-bitsInHighWord)) {
jaroslav@1258: int result[] = new int[nInts+len];
jaroslav@1258: for (int i=0; i0; i--) {
jaroslav@1258: int b = c;
jaroslav@1258: c = a[i-1];
jaroslav@1258: a[i] = (c << n2) | (b >>> n);
jaroslav@1258: }
jaroslav@1258: a[0] >>>= n;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
jaroslav@1258: static void primitiveLeftShift(int[] a, int len, int n) {
jaroslav@1258: if (len == 0 || n == 0)
jaroslav@1258: return;
jaroslav@1258:
jaroslav@1258: int n2 = 32 - n;
jaroslav@1258: for (int i=0, c=a[i], m=i+len-1; i>> n2);
jaroslav@1258: }
jaroslav@1258: a[len-1] <<= n;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Calculate bitlength of contents of the first len elements an int array,
jaroslav@1258: * assuming there are no leading zero ints.
jaroslav@1258: */
jaroslav@1258: private static int bitLength(int[] val, int len) {
jaroslav@1258: if (len == 0)
jaroslav@1258: return 0;
jaroslav@1258: return ((len - 1) << 5) + bitLengthForInt(val[0]);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is the absolute value of this
jaroslav@1258: * BigInteger.
jaroslav@1258: *
jaroslav@1258: * @return {@code abs(this)}
jaroslav@1258: */
jaroslav@1258: public BigInteger abs() {
jaroslav@1258: return (signum >= 0 ? this : this.negate());
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (-this)}.
jaroslav@1258: *
jaroslav@1258: * @return {@code -this}
jaroslav@1258: */
jaroslav@1258: public BigInteger negate() {
jaroslav@1258: return new BigInteger(this.mag, -this.signum);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the signum function of this BigInteger.
jaroslav@1258: *
jaroslav@1258: * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or
jaroslav@1258: * positive.
jaroslav@1258: */
jaroslav@1258: public int signum() {
jaroslav@1258: return this.signum;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Modular Arithmetic Operations
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (this mod m}). This method
jaroslav@1258: * differs from {@code remainder} in that it always returns a
jaroslav@1258: * non-negative BigInteger.
jaroslav@1258: *
jaroslav@1258: * @param m the modulus.
jaroslav@1258: * @return {@code this mod m}
jaroslav@1258: * @throws ArithmeticException {@code m} ≤ 0
jaroslav@1258: * @see #remainder
jaroslav@1258: */
jaroslav@1258: public BigInteger mod(BigInteger m) {
jaroslav@1258: if (m.signum <= 0)
jaroslav@1258: throw new ArithmeticException("BigInteger: modulus not positive");
jaroslav@1258:
jaroslav@1258: BigInteger result = this.remainder(m);
jaroslav@1258: return (result.signum >= 0 ? result : result.add(m));
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is
jaroslav@1258: * (thisexponent mod m). (Unlike {@code pow}, this
jaroslav@1258: * method permits negative exponents.)
jaroslav@1258: *
jaroslav@1258: * @param exponent the exponent.
jaroslav@1258: * @param m the modulus.
jaroslav@1258: * @return thisexponent mod m
jaroslav@1258: * @throws ArithmeticException {@code m} ≤ 0 or the exponent is
jaroslav@1258: * negative and this BigInteger is not relatively
jaroslav@1258: * prime to {@code m}.
jaroslav@1258: * @see #modInverse
jaroslav@1258: */
jaroslav@1258: public BigInteger modPow(BigInteger exponent, BigInteger m) {
jaroslav@1258: if (m.signum <= 0)
jaroslav@1258: throw new ArithmeticException("BigInteger: modulus not positive");
jaroslav@1258:
jaroslav@1258: // Trivial cases
jaroslav@1258: if (exponent.signum == 0)
jaroslav@1258: return (m.equals(ONE) ? ZERO : ONE);
jaroslav@1258:
jaroslav@1258: if (this.equals(ONE))
jaroslav@1258: return (m.equals(ONE) ? ZERO : ONE);
jaroslav@1258:
jaroslav@1258: if (this.equals(ZERO) && exponent.signum >= 0)
jaroslav@1258: return ZERO;
jaroslav@1258:
jaroslav@1258: if (this.equals(negConst[1]) && (!exponent.testBit(0)))
jaroslav@1258: return (m.equals(ONE) ? ZERO : ONE);
jaroslav@1258:
jaroslav@1258: boolean invertResult;
jaroslav@1258: if ((invertResult = (exponent.signum < 0)))
jaroslav@1258: exponent = exponent.negate();
jaroslav@1258:
jaroslav@1258: BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
jaroslav@1258: ? this.mod(m) : this);
jaroslav@1258: BigInteger result;
jaroslav@1258: if (m.testBit(0)) { // odd modulus
jaroslav@1258: result = base.oddModPow(exponent, m);
jaroslav@1258: } else {
jaroslav@1258: /*
jaroslav@1258: * Even modulus. Tear it into an "odd part" (m1) and power of two
jaroslav@1258: * (m2), exponentiate mod m1, manually exponentiate mod m2, and
jaroslav@1258: * use Chinese Remainder Theorem to combine results.
jaroslav@1258: */
jaroslav@1258:
jaroslav@1258: // Tear m apart into odd part (m1) and power of 2 (m2)
jaroslav@1258: int p = m.getLowestSetBit(); // Max pow of 2 that divides m
jaroslav@1258:
jaroslav@1258: BigInteger m1 = m.shiftRight(p); // m/2**p
jaroslav@1258: BigInteger m2 = ONE.shiftLeft(p); // 2**p
jaroslav@1258:
jaroslav@1258: // Calculate new base from m1
jaroslav@1258: BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0
jaroslav@1258: ? this.mod(m1) : this);
jaroslav@1258:
jaroslav@1258: // Caculate (base ** exponent) mod m1.
jaroslav@1258: BigInteger a1 = (m1.equals(ONE) ? ZERO :
jaroslav@1258: base2.oddModPow(exponent, m1));
jaroslav@1258:
jaroslav@1258: // Calculate (this ** exponent) mod m2
jaroslav@1258: BigInteger a2 = base.modPow2(exponent, p);
jaroslav@1258:
jaroslav@1258: // Combine results using Chinese Remainder Theorem
jaroslav@1258: BigInteger y1 = m2.modInverse(m1);
jaroslav@1258: BigInteger y2 = m1.modInverse(m2);
jaroslav@1258:
jaroslav@1258: result = a1.multiply(m2).multiply(y1).add
jaroslav@1258: (a2.multiply(m1).multiply(y2)).mod(m);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: return (invertResult ? result.modInverse(m) : result);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,
jaroslav@1258: Integer.MAX_VALUE}; // Sentinel
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is x to the power of y mod z.
jaroslav@1258: * Assumes: z is odd && x < z.
jaroslav@1258: */
jaroslav@1258: private BigInteger oddModPow(BigInteger y, BigInteger z) {
jaroslav@1258: /*
jaroslav@1258: * The algorithm is adapted from Colin Plumb's C library.
jaroslav@1258: *
jaroslav@1258: * The window algorithm:
jaroslav@1258: * The idea is to keep a running product of b1 = n^(high-order bits of exp)
jaroslav@1258: * and then keep appending exponent bits to it. The following patterns
jaroslav@1258: * apply to a 3-bit window (k = 3):
jaroslav@1258: * To append 0: square
jaroslav@1258: * To append 1: square, multiply by n^1
jaroslav@1258: * To append 10: square, multiply by n^1, square
jaroslav@1258: * To append 11: square, square, multiply by n^3
jaroslav@1258: * To append 100: square, multiply by n^1, square, square
jaroslav@1258: * To append 101: square, square, square, multiply by n^5
jaroslav@1258: * To append 110: square, square, multiply by n^3, square
jaroslav@1258: * To append 111: square, square, square, multiply by n^7
jaroslav@1258: *
jaroslav@1258: * Since each pattern involves only one multiply, the longer the pattern
jaroslav@1258: * the better, except that a 0 (no multiplies) can be appended directly.
jaroslav@1258: * We precompute a table of odd powers of n, up to 2^k, and can then
jaroslav@1258: * multiply k bits of exponent at a time. Actually, assuming random
jaroslav@1258: * exponents, there is on average one zero bit between needs to
jaroslav@1258: * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
jaroslav@1258: * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so
jaroslav@1258: * you have to do one multiply per k+1 bits of exponent.
jaroslav@1258: *
jaroslav@1258: * The loop walks down the exponent, squaring the result buffer as
jaroslav@1258: * it goes. There is a wbits+1 bit lookahead buffer, buf, that is
jaroslav@1258: * filled with the upcoming exponent bits. (What is read after the
jaroslav@1258: * end of the exponent is unimportant, but it is filled with zero here.)
jaroslav@1258: * When the most-significant bit of this buffer becomes set, i.e.
jaroslav@1258: * (buf & tblmask) != 0, we have to decide what pattern to multiply
jaroslav@1258: * by, and when to do it. We decide, remember to do it in future
jaroslav@1258: * after a suitable number of squarings have passed (e.g. a pattern
jaroslav@1258: * of "100" in the buffer requires that we multiply by n^1 immediately;
jaroslav@1258: * a pattern of "110" calls for multiplying by n^3 after one more
jaroslav@1258: * squaring), clear the buffer, and continue.
jaroslav@1258: *
jaroslav@1258: * When we start, there is one more optimization: the result buffer
jaroslav@1258: * is implcitly one, so squaring it or multiplying by it can be
jaroslav@1258: * optimized away. Further, if we start with a pattern like "100"
jaroslav@1258: * in the lookahead window, rather than placing n into the buffer
jaroslav@1258: * and then starting to square it, we have already computed n^2
jaroslav@1258: * to compute the odd-powers table, so we can place that into
jaroslav@1258: * the buffer and save a squaring.
jaroslav@1258: *
jaroslav@1258: * This means that if you have a k-bit window, to compute n^z,
jaroslav@1258: * where z is the high k bits of the exponent, 1/2 of the time
jaroslav@1258: * it requires no squarings. 1/4 of the time, it requires 1
jaroslav@1258: * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.
jaroslav@1258: * And the remaining 1/2^(k-1) of the time, the top k bits are a
jaroslav@1258: * 1 followed by k-1 0 bits, so it again only requires k-2
jaroslav@1258: * squarings, not k-1. The average of these is 1. Add that
jaroslav@1258: * to the one squaring we have to do to compute the table,
jaroslav@1258: * and you'll see that a k-bit window saves k-2 squarings
jaroslav@1258: * as well as reducing the multiplies. (It actually doesn't
jaroslav@1258: * hurt in the case k = 1, either.)
jaroslav@1258: */
jaroslav@1258: // Special case for exponent of one
jaroslav@1258: if (y.equals(ONE))
jaroslav@1258: return this;
jaroslav@1258:
jaroslav@1258: // Special case for base of zero
jaroslav@1258: if (signum==0)
jaroslav@1258: return ZERO;
jaroslav@1258:
jaroslav@1258: int[] base = mag.clone();
jaroslav@1258: int[] exp = y.mag;
jaroslav@1258: int[] mod = z.mag;
jaroslav@1258: int modLen = mod.length;
jaroslav@1258:
jaroslav@1258: // Select an appropriate window size
jaroslav@1258: int wbits = 0;
jaroslav@1258: int ebits = bitLength(exp, exp.length);
jaroslav@1258: // if exponent is 65537 (0x10001), use minimum window size
jaroslav@1258: if ((ebits != 17) || (exp[0] != 65537)) {
jaroslav@1258: while (ebits > bnExpModThreshTable[wbits]) {
jaroslav@1258: wbits++;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Calculate appropriate table size
jaroslav@1258: int tblmask = 1 << wbits;
jaroslav@1258:
jaroslav@1258: // Allocate table for precomputed odd powers of base in Montgomery form
jaroslav@1258: int[][] table = new int[tblmask][];
jaroslav@1258: for (int i=0; i>>= 1;
jaroslav@1258: if (bitpos == 0) {
jaroslav@1258: eIndex++;
jaroslav@1258: bitpos = 1 << (32-1);
jaroslav@1258: elen--;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: int multpos = ebits;
jaroslav@1258:
jaroslav@1258: // The first iteration, which is hoisted out of the main loop
jaroslav@1258: ebits--;
jaroslav@1258: boolean isone = true;
jaroslav@1258:
jaroslav@1258: multpos = ebits - wbits;
jaroslav@1258: while ((buf & 1) == 0) {
jaroslav@1258: buf >>>= 1;
jaroslav@1258: multpos++;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: int[] mult = table[buf >>> 1];
jaroslav@1258:
jaroslav@1258: buf = 0;
jaroslav@1258: if (multpos == ebits)
jaroslav@1258: isone = false;
jaroslav@1258:
jaroslav@1258: // The main loop
jaroslav@1258: while(true) {
jaroslav@1258: ebits--;
jaroslav@1258: // Advance the window
jaroslav@1258: buf <<= 1;
jaroslav@1258:
jaroslav@1258: if (elen != 0) {
jaroslav@1258: buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
jaroslav@1258: bitpos >>>= 1;
jaroslav@1258: if (bitpos == 0) {
jaroslav@1258: eIndex++;
jaroslav@1258: bitpos = 1 << (32-1);
jaroslav@1258: elen--;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Examine the window for pending multiplies
jaroslav@1258: if ((buf & tblmask) != 0) {
jaroslav@1258: multpos = ebits - wbits;
jaroslav@1258: while ((buf & 1) == 0) {
jaroslav@1258: buf >>>= 1;
jaroslav@1258: multpos++;
jaroslav@1258: }
jaroslav@1258: mult = table[buf >>> 1];
jaroslav@1258: buf = 0;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Perform multiply
jaroslav@1258: if (ebits == multpos) {
jaroslav@1258: if (isone) {
jaroslav@1258: b = mult.clone();
jaroslav@1258: isone = false;
jaroslav@1258: } else {
jaroslav@1258: t = b;
jaroslav@1258: a = multiplyToLen(t, modLen, mult, modLen, a);
jaroslav@1258: a = montReduce(a, mod, modLen, inv);
jaroslav@1258: t = a; a = b; b = t;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Check if done
jaroslav@1258: if (ebits == 0)
jaroslav@1258: break;
jaroslav@1258:
jaroslav@1258: // Square the input
jaroslav@1258: if (!isone) {
jaroslav@1258: t = b;
jaroslav@1258: a = squareToLen(t, modLen, a);
jaroslav@1258: a = montReduce(a, mod, modLen, inv);
jaroslav@1258: t = a; a = b; b = t;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Convert result out of Montgomery form and return
jaroslav@1258: int[] t2 = new int[2*modLen];
jaroslav@1258: for(int i=0; i 0);
jaroslav@1258:
jaroslav@1258: while(c>0)
jaroslav@1258: c += subN(n, mod, mlen);
jaroslav@1258:
jaroslav@1258: while (intArrayCmpToLen(n, mod, mlen) >= 0)
jaroslav@1258: subN(n, mod, mlen);
jaroslav@1258:
jaroslav@1258: return n;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258:
jaroslav@1258: /*
jaroslav@1258: * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,
jaroslav@1258: * equal to, or greater than arg2 up to length len.
jaroslav@1258: */
jaroslav@1258: private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
jaroslav@1258: for (int i=0; i b2)
jaroslav@1258: return 1;
jaroslav@1258: }
jaroslav@1258: return 0;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Subtracts two numbers of same length, returning borrow.
jaroslav@1258: */
jaroslav@1258: private static int subN(int[] a, int[] b, int len) {
jaroslav@1258: long sum = 0;
jaroslav@1258:
jaroslav@1258: while(--len >= 0) {
jaroslav@1258: sum = (a[len] & LONG_MASK) -
jaroslav@1258: (b[len] & LONG_MASK) + (sum >> 32);
jaroslav@1258: a[len] = (int)sum;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: return (int)(sum >> 32);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Multiply an array by one word k and add to result, return the carry
jaroslav@1258: */
jaroslav@1258: static int mulAdd(int[] out, int[] in, int offset, int len, int k) {
jaroslav@1258: long kLong = k & LONG_MASK;
jaroslav@1258: long carry = 0;
jaroslav@1258:
jaroslav@1258: offset = out.length-offset - 1;
jaroslav@1258: for (int j=len-1; j >= 0; j--) {
jaroslav@1258: long product = (in[j] & LONG_MASK) * kLong +
jaroslav@1258: (out[offset] & LONG_MASK) + carry;
jaroslav@1258: out[offset--] = (int)product;
jaroslav@1258: carry = product >>> 32;
jaroslav@1258: }
jaroslav@1258: return (int)carry;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Add one word to the number a mlen words into a. Return the resulting
jaroslav@1258: * carry.
jaroslav@1258: */
jaroslav@1258: static int addOne(int[] a, int offset, int mlen, int carry) {
jaroslav@1258: offset = a.length-1-mlen-offset;
jaroslav@1258: long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);
jaroslav@1258:
jaroslav@1258: a[offset] = (int)t;
jaroslav@1258: if ((t >>> 32) == 0)
jaroslav@1258: return 0;
jaroslav@1258: while (--mlen >= 0) {
jaroslav@1258: if (--offset < 0) { // Carry out of number
jaroslav@1258: return 1;
jaroslav@1258: } else {
jaroslav@1258: a[offset]++;
jaroslav@1258: if (a[offset] != 0)
jaroslav@1258: return 0;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258: return 1;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is (this ** exponent) mod (2**p)
jaroslav@1258: */
jaroslav@1258: private BigInteger modPow2(BigInteger exponent, int p) {
jaroslav@1258: /*
jaroslav@1258: * Perform exponentiation using repeated squaring trick, chopping off
jaroslav@1258: * high order bits as indicated by modulus.
jaroslav@1258: */
jaroslav@1258: BigInteger result = valueOf(1);
jaroslav@1258: BigInteger baseToPow2 = this.mod2(p);
jaroslav@1258: int expOffset = 0;
jaroslav@1258:
jaroslav@1258: int limit = exponent.bitLength();
jaroslav@1258:
jaroslav@1258: if (this.testBit(0))
jaroslav@1258: limit = (p-1) < limit ? (p-1) : limit;
jaroslav@1258:
jaroslav@1258: while (expOffset < limit) {
jaroslav@1258: if (exponent.testBit(expOffset))
jaroslav@1258: result = result.multiply(baseToPow2).mod2(p);
jaroslav@1258: expOffset++;
jaroslav@1258: if (expOffset < limit)
jaroslav@1258: baseToPow2 = baseToPow2.square().mod2(p);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: return result;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is this mod(2**p).
jaroslav@1258: * Assumes that this {@code BigInteger >= 0} and {@code p > 0}.
jaroslav@1258: */
jaroslav@1258: private BigInteger mod2(int p) {
jaroslav@1258: if (bitLength() <= p)
jaroslav@1258: return this;
jaroslav@1258:
jaroslav@1258: // Copy remaining ints of mag
jaroslav@1258: int numInts = (p + 31) >>> 5;
jaroslav@1258: int[] mag = new int[numInts];
jaroslav@1258: for (int i=0; i-1 {@code mod m)}.
jaroslav@1258: *
jaroslav@1258: * @param m the modulus.
jaroslav@1258: * @return {@code this}-1 {@code mod m}.
jaroslav@1258: * @throws ArithmeticException {@code m} ≤ 0, or this BigInteger
jaroslav@1258: * has no multiplicative inverse mod m (that is, this BigInteger
jaroslav@1258: * is not relatively prime to m).
jaroslav@1258: */
jaroslav@1258: public BigInteger modInverse(BigInteger m) {
jaroslav@1258: if (m.signum != 1)
jaroslav@1258: throw new ArithmeticException("BigInteger: modulus not positive");
jaroslav@1258:
jaroslav@1258: if (m.equals(ONE))
jaroslav@1258: return ZERO;
jaroslav@1258:
jaroslav@1258: // Calculate (this mod m)
jaroslav@1258: BigInteger modVal = this;
jaroslav@1258: if (signum < 0 || (this.compareMagnitude(m) >= 0))
jaroslav@1258: modVal = this.mod(m);
jaroslav@1258:
jaroslav@1258: if (modVal.equals(ONE))
jaroslav@1258: return ONE;
jaroslav@1258:
jaroslav@1258: MutableBigInteger a = new MutableBigInteger(modVal);
jaroslav@1258: MutableBigInteger b = new MutableBigInteger(m);
jaroslav@1258:
jaroslav@1258: MutableBigInteger result = a.mutableModInverse(b);
jaroslav@1258: return result.toBigInteger(1);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Shift Operations
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (this << n)}.
jaroslav@1258: * The shift distance, {@code n}, may be negative, in which case
jaroslav@1258: * this method performs a right shift.
jaroslav@1258: * (Computes floor(this * 2n).)
jaroslav@1258: *
jaroslav@1258: * @param n shift distance, in bits.
jaroslav@1258: * @return {@code this << n}
jaroslav@1258: * @throws ArithmeticException if the shift distance is {@code
jaroslav@1258: * Integer.MIN_VALUE}.
jaroslav@1258: * @see #shiftRight
jaroslav@1258: */
jaroslav@1258: public BigInteger shiftLeft(int n) {
jaroslav@1258: if (signum == 0)
jaroslav@1258: return ZERO;
jaroslav@1258: if (n==0)
jaroslav@1258: return this;
jaroslav@1258: if (n<0) {
jaroslav@1258: if (n == Integer.MIN_VALUE) {
jaroslav@1258: throw new ArithmeticException("Shift distance of Integer.MIN_VALUE not supported.");
jaroslav@1258: } else {
jaroslav@1258: return shiftRight(-n);
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: int nInts = n >>> 5;
jaroslav@1258: int nBits = n & 0x1f;
jaroslav@1258: int magLen = mag.length;
jaroslav@1258: int newMag[] = null;
jaroslav@1258:
jaroslav@1258: if (nBits == 0) {
jaroslav@1258: newMag = new int[magLen + nInts];
jaroslav@1258: for (int i=0; i>> nBits2;
jaroslav@1258: if (highBits != 0) {
jaroslav@1258: newMag = new int[magLen + nInts + 1];
jaroslav@1258: newMag[i++] = highBits;
jaroslav@1258: } else {
jaroslav@1258: newMag = new int[magLen + nInts];
jaroslav@1258: }
jaroslav@1258: int j=0;
jaroslav@1258: while (j < magLen-1)
jaroslav@1258: newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2;
jaroslav@1258: newMag[i] = mag[j] << nBits;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: return new BigInteger(newMag, signum);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (this >> n)}. Sign
jaroslav@1258: * extension is performed. The shift distance, {@code n}, may be
jaroslav@1258: * negative, in which case this method performs a left shift.
jaroslav@1258: * (Computes floor(this / 2n).)
jaroslav@1258: *
jaroslav@1258: * @param n shift distance, in bits.
jaroslav@1258: * @return {@code this >> n}
jaroslav@1258: * @throws ArithmeticException if the shift distance is {@code
jaroslav@1258: * Integer.MIN_VALUE}.
jaroslav@1258: * @see #shiftLeft
jaroslav@1258: */
jaroslav@1258: public BigInteger shiftRight(int n) {
jaroslav@1258: if (n==0)
jaroslav@1258: return this;
jaroslav@1258: if (n<0) {
jaroslav@1258: if (n == Integer.MIN_VALUE) {
jaroslav@1258: throw new ArithmeticException("Shift distance of Integer.MIN_VALUE not supported.");
jaroslav@1258: } else {
jaroslav@1258: return shiftLeft(-n);
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: int nInts = n >>> 5;
jaroslav@1258: int nBits = n & 0x1f;
jaroslav@1258: int magLen = mag.length;
jaroslav@1258: int newMag[] = null;
jaroslav@1258:
jaroslav@1258: // Special case: entire contents shifted off the end
jaroslav@1258: if (nInts >= magLen)
jaroslav@1258: return (signum >= 0 ? ZERO : negConst[1]);
jaroslav@1258:
jaroslav@1258: if (nBits == 0) {
jaroslav@1258: int newMagLen = magLen - nInts;
jaroslav@1258: newMag = new int[newMagLen];
jaroslav@1258: for (int i=0; i>> nBits;
jaroslav@1258: if (highBits != 0) {
jaroslav@1258: newMag = new int[magLen - nInts];
jaroslav@1258: newMag[i++] = highBits;
jaroslav@1258: } else {
jaroslav@1258: newMag = new int[magLen - nInts -1];
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: int nBits2 = 32 - nBits;
jaroslav@1258: int j=0;
jaroslav@1258: while (j < magLen - nInts - 1)
jaroslav@1258: newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: if (signum < 0) {
jaroslav@1258: // Find out whether any one-bits were shifted off the end.
jaroslav@1258: boolean onesLost = false;
jaroslav@1258: for (int i=magLen-1, j=magLen-nInts; i>=j && !onesLost; i--)
jaroslav@1258: onesLost = (mag[i] != 0);
jaroslav@1258: if (!onesLost && nBits != 0)
jaroslav@1258: onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
jaroslav@1258:
jaroslav@1258: if (onesLost)
jaroslav@1258: newMag = javaIncrement(newMag);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: return new BigInteger(newMag, signum);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: int[] javaIncrement(int[] val) {
jaroslav@1258: int lastSum = 0;
jaroslav@1258: for (int i=val.length-1; i >= 0 && lastSum == 0; i--)
jaroslav@1258: lastSum = (val[i] += 1);
jaroslav@1258: if (lastSum == 0) {
jaroslav@1258: val = new int[val.length+1];
jaroslav@1258: val[0] = 1;
jaroslav@1258: }
jaroslav@1258: return val;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Bitwise Operations
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is {@code (this & val)}. (This
jaroslav@1258: * method returns a negative BigInteger if and only if this and val are
jaroslav@1258: * both negative.)
jaroslav@1258: *
jaroslav@1258: * @param val value to be AND'ed with this BigInteger.
jaroslav@1258: * @return {@code this & val}
jaroslav@1258: */
jaroslav@1258: public BigInteger and(BigInteger val) {
jaroslav@1258: int[] result = new int[Math.max(intLength(), val.intLength())];
jaroslav@1258: for (int i=0; i>> 5) & (1 << (n & 31))) != 0;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a BigInteger whose value is equivalent to this BigInteger
jaroslav@1258: * with the designated bit set. (Computes {@code (this | (1<>> 5;
jaroslav@1258: int[] result = new int[Math.max(intLength(), intNum+2)];
jaroslav@1258:
jaroslav@1258: for (int i=0; i>> 5;
jaroslav@1258: int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];
jaroslav@1258:
jaroslav@1258: for (int i=0; i>> 5;
jaroslav@1258: int[] result = new int[Math.max(intLength(), intNum+2)];
jaroslav@1258:
jaroslav@1258: for (int i=0; iexcluding a sign bit.
jaroslav@1258: * For positive BigIntegers, this is equivalent to the number of bits in
jaroslav@1258: * the ordinary binary representation. (Computes
jaroslav@1258: * {@code (ceil(log2(this < 0 ? -this : this+1)))}.)
jaroslav@1258: *
jaroslav@1258: * @return number of bits in the minimal two's-complement
jaroslav@1258: * representation of this BigInteger, excluding a sign bit.
jaroslav@1258: */
jaroslav@1258: public int bitLength() {
jaroslav@1258: @SuppressWarnings("deprecation") int n = bitLength - 1;
jaroslav@1258: if (n == -1) { // bitLength not initialized yet
jaroslav@1258: int[] m = mag;
jaroslav@1258: int len = m.length;
jaroslav@1258: if (len == 0) {
jaroslav@1258: n = 0; // offset by one to initialize
jaroslav@1258: } else {
jaroslav@1258: // Calculate the bit length of the magnitude
jaroslav@1258: int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
jaroslav@1258: if (signum < 0) {
jaroslav@1258: // Check if magnitude is a power of two
jaroslav@1258: boolean pow2 = (Integer.bitCount(mag[0]) == 1);
jaroslav@1258: for(int i=1; i< len && pow2; i++)
jaroslav@1258: pow2 = (mag[i] == 0);
jaroslav@1258:
jaroslav@1258: n = (pow2 ? magBitLength -1 : magBitLength);
jaroslav@1258: } else {
jaroslav@1258: n = magBitLength;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258: bitLength = n + 1;
jaroslav@1258: }
jaroslav@1258: return n;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the number of bits in the two's complement representation
jaroslav@1258: * of this BigInteger that differ from its sign bit. This method is
jaroslav@1258: * useful when implementing bit-vector style sets atop BigIntegers.
jaroslav@1258: *
jaroslav@1258: * @return number of bits in the two's complement representation
jaroslav@1258: * of this BigInteger that differ from its sign bit.
jaroslav@1258: */
jaroslav@1258: public int bitCount() {
jaroslav@1258: @SuppressWarnings("deprecation") int bc = bitCount - 1;
jaroslav@1258: if (bc == -1) { // bitCount not initialized yet
jaroslav@1258: bc = 0; // offset by one to initialize
jaroslav@1258: // Count the bits in the magnitude
jaroslav@1258: for (int i=0; i{@code certainty}). The execution time of
jaroslav@1258: * this method is proportional to the value of this parameter.
jaroslav@1258: * @return {@code true} if this BigInteger is probably prime,
jaroslav@1258: * {@code false} if it's definitely composite.
jaroslav@1258: */
jaroslav@1258: public boolean isProbablePrime(int certainty) {
jaroslav@1258: if (certainty <= 0)
jaroslav@1258: return true;
jaroslav@1258: BigInteger w = this.abs();
jaroslav@1258: if (w.equals(TWO))
jaroslav@1258: return true;
jaroslav@1258: if (!w.testBit(0) || w.equals(ONE))
jaroslav@1258: return false;
jaroslav@1258:
jaroslav@1258: return w.primeToCertainty(certainty, null);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Comparison Operations
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Compares this BigInteger with the specified BigInteger. This
jaroslav@1258: * method is provided in preference to individual methods for each
jaroslav@1258: * of the six boolean comparison operators ({@literal <}, ==,
jaroslav@1258: * {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested
jaroslav@1258: * idiom for performing these comparisons is: {@code
jaroslav@1258: * (x.compareTo(y)} <op> {@code 0)}, where
jaroslav@1258: * <op> is one of the six comparison operators.
jaroslav@1258: *
jaroslav@1258: * @param val BigInteger to which this BigInteger is to be compared.
jaroslav@1258: * @return -1, 0 or 1 as this BigInteger is numerically less than, equal
jaroslav@1258: * to, or greater than {@code val}.
jaroslav@1258: */
jaroslav@1258: public int compareTo(BigInteger val) {
jaroslav@1258: if (signum == val.signum) {
jaroslav@1258: switch (signum) {
jaroslav@1258: case 1:
jaroslav@1258: return compareMagnitude(val);
jaroslav@1258: case -1:
jaroslav@1258: return val.compareMagnitude(this);
jaroslav@1258: default:
jaroslav@1258: return 0;
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258: return signum > val.signum ? 1 : -1;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Compares the magnitude array of this BigInteger with the specified
jaroslav@1258: * BigInteger's. This is the version of compareTo ignoring sign.
jaroslav@1258: *
jaroslav@1258: * @param val BigInteger whose magnitude array to be compared.
jaroslav@1258: * @return -1, 0 or 1 as this magnitude array is less than, equal to or
jaroslav@1258: * greater than the magnitude aray for the specified BigInteger's.
jaroslav@1258: */
jaroslav@1258: final int compareMagnitude(BigInteger val) {
jaroslav@1258: int[] m1 = mag;
jaroslav@1258: int len1 = m1.length;
jaroslav@1258: int[] m2 = val.mag;
jaroslav@1258: int len2 = m2.length;
jaroslav@1258: if (len1 < len2)
jaroslav@1258: return -1;
jaroslav@1258: if (len1 > len2)
jaroslav@1258: return 1;
jaroslav@1258: for (int i = 0; i < len1; i++) {
jaroslav@1258: int a = m1[i];
jaroslav@1258: int b = m2[i];
jaroslav@1258: if (a != b)
jaroslav@1258: return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
jaroslav@1258: }
jaroslav@1258: return 0;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Compares this BigInteger with the specified Object for equality.
jaroslav@1258: *
jaroslav@1258: * @param x Object to which this BigInteger is to be compared.
jaroslav@1258: * @return {@code true} if and only if the specified Object is a
jaroslav@1258: * BigInteger whose value is numerically equal to this BigInteger.
jaroslav@1258: */
jaroslav@1258: public boolean equals(Object x) {
jaroslav@1258: // This test is just an optimization, which may or may not help
jaroslav@1258: if (x == this)
jaroslav@1258: return true;
jaroslav@1258:
jaroslav@1258: if (!(x instanceof BigInteger))
jaroslav@1258: return false;
jaroslav@1258:
jaroslav@1258: BigInteger xInt = (BigInteger) x;
jaroslav@1258: if (xInt.signum != signum)
jaroslav@1258: return false;
jaroslav@1258:
jaroslav@1258: int[] m = mag;
jaroslav@1258: int len = m.length;
jaroslav@1258: int[] xm = xInt.mag;
jaroslav@1258: if (len != xm.length)
jaroslav@1258: return false;
jaroslav@1258:
jaroslav@1258: for (int i = 0; i < len; i++)
jaroslav@1258: if (xm[i] != m[i])
jaroslav@1258: return false;
jaroslav@1258:
jaroslav@1258: return true;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the minimum of this BigInteger and {@code val}.
jaroslav@1258: *
jaroslav@1258: * @param val value with which the minimum is to be computed.
jaroslav@1258: * @return the BigInteger whose value is the lesser of this BigInteger and
jaroslav@1258: * {@code val}. If they are equal, either may be returned.
jaroslav@1258: */
jaroslav@1258: public BigInteger min(BigInteger val) {
jaroslav@1258: return (compareTo(val)<0 ? this : val);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the maximum of this BigInteger and {@code val}.
jaroslav@1258: *
jaroslav@1258: * @param val value with which the maximum is to be computed.
jaroslav@1258: * @return the BigInteger whose value is the greater of this and
jaroslav@1258: * {@code val}. If they are equal, either may be returned.
jaroslav@1258: */
jaroslav@1258: public BigInteger max(BigInteger val) {
jaroslav@1258: return (compareTo(val)>0 ? this : val);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258:
jaroslav@1258: // Hash Function
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the hash code for this BigInteger.
jaroslav@1258: *
jaroslav@1258: * @return hash code for this BigInteger.
jaroslav@1258: */
jaroslav@1258: public int hashCode() {
jaroslav@1258: int hashCode = 0;
jaroslav@1258:
jaroslav@1258: for (int i=0; i Character.MAX_RADIX)
jaroslav@1258: radix = 10;
jaroslav@1258:
jaroslav@1258: // Compute upper bound on number of digit groups and allocate space
jaroslav@1258: int maxNumDigitGroups = (4*mag.length + 6)/7;
jaroslav@1258: String digitGroup[] = new String[maxNumDigitGroups];
jaroslav@1258:
jaroslav@1258: // Translate number to string, a digit group at a time
jaroslav@1258: BigInteger tmp = this.abs();
jaroslav@1258: int numGroups = 0;
jaroslav@1258: while (tmp.signum != 0) {
jaroslav@1258: BigInteger d = longRadix[radix];
jaroslav@1258:
jaroslav@1258: MutableBigInteger q = new MutableBigInteger(),
jaroslav@1258: a = new MutableBigInteger(tmp.mag),
jaroslav@1258: b = new MutableBigInteger(d.mag);
jaroslav@1258: MutableBigInteger r = a.divide(b, q);
jaroslav@1258: BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);
jaroslav@1258: BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
jaroslav@1258:
jaroslav@1258: digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
jaroslav@1258: tmp = q2;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Put sign (if any) and first digit group into result buffer
jaroslav@1258: StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1);
jaroslav@1258: if (signum<0)
jaroslav@1258: buf.append('-');
jaroslav@1258: buf.append(digitGroup[numGroups-1]);
jaroslav@1258:
jaroslav@1258: // Append remaining digit groups padded with leading zeros
jaroslav@1258: for (int i=numGroups-2; i>=0; i--) {
jaroslav@1258: // Prepend (any) leading zeros for this digit group
jaroslav@1258: int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
jaroslav@1258: if (numLeadingZeros != 0)
jaroslav@1258: buf.append(zeros[numLeadingZeros]);
jaroslav@1258: buf.append(digitGroup[i]);
jaroslav@1258: }
jaroslav@1258: return buf.toString();
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /* zero[i] is a string of i consecutive zeros. */
jaroslav@1258: private static String zeros[] = new String[64];
jaroslav@1258: static {
jaroslav@1258: zeros[63] =
jaroslav@1258: "000000000000000000000000000000000000000000000000000000000000000";
jaroslav@1258: for (int i=0; i<63; i++)
jaroslav@1258: zeros[i] = zeros[63].substring(0, i);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the decimal String representation of this BigInteger.
jaroslav@1258: * The digit-to-character mapping provided by
jaroslav@1258: * {@code Character.forDigit} is used, and a minus sign is
jaroslav@1258: * prepended if appropriate. (This representation is compatible
jaroslav@1258: * with the {@link #BigInteger(String) (String)} constructor, and
jaroslav@1258: * allows for String concatenation with Java's + operator.)
jaroslav@1258: *
jaroslav@1258: * @return decimal String representation of this BigInteger.
jaroslav@1258: * @see Character#forDigit
jaroslav@1258: * @see #BigInteger(java.lang.String)
jaroslav@1258: */
jaroslav@1258: public String toString() {
jaroslav@1258: return toString(10);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a byte array containing the two's-complement
jaroslav@1258: * representation of this BigInteger. The byte array will be in
jaroslav@1258: * big-endian byte-order: the most significant byte is in
jaroslav@1258: * the zeroth element. The array will contain the minimum number
jaroslav@1258: * of bytes required to represent this BigInteger, including at
jaroslav@1258: * least one sign bit, which is {@code (ceil((this.bitLength() +
jaroslav@1258: * 1)/8))}. (This representation is compatible with the
jaroslav@1258: * {@link #BigInteger(byte[]) (byte[])} constructor.)
jaroslav@1258: *
jaroslav@1258: * @return a byte array containing the two's-complement representation of
jaroslav@1258: * this BigInteger.
jaroslav@1258: * @see #BigInteger(byte[])
jaroslav@1258: */
jaroslav@1258: public byte[] toByteArray() {
jaroslav@1258: int byteLen = bitLength()/8 + 1;
jaroslav@1258: byte[] byteArray = new byte[byteLen];
jaroslav@1258:
jaroslav@1258: for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i>=0; i--) {
jaroslav@1258: if (bytesCopied == 4) {
jaroslav@1258: nextInt = getInt(intIndex++);
jaroslav@1258: bytesCopied = 1;
jaroslav@1258: } else {
jaroslav@1258: nextInt >>>= 8;
jaroslav@1258: bytesCopied++;
jaroslav@1258: }
jaroslav@1258: byteArray[i] = (byte)nextInt;
jaroslav@1258: }
jaroslav@1258: return byteArray;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Converts this BigInteger to an {@code int}. This
jaroslav@1258: * conversion is analogous to a
jaroslav@1258: * narrowing primitive conversion from {@code long} to
jaroslav@1258: * {@code int} as defined in section 5.1.3 of
jaroslav@1258: * The Java™ Language Specification:
jaroslav@1258: * if this BigInteger is too big to fit in an
jaroslav@1258: * {@code int}, only the low-order 32 bits are returned.
jaroslav@1258: * Note that this conversion can lose information about the
jaroslav@1258: * overall magnitude of the BigInteger value as well as return a
jaroslav@1258: * result with the opposite sign.
jaroslav@1258: *
jaroslav@1258: * @return this BigInteger converted to an {@code int}.
jaroslav@1258: */
jaroslav@1258: public int intValue() {
jaroslav@1258: int result = 0;
jaroslav@1258: result = getInt(0);
jaroslav@1258: return result;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Converts this BigInteger to a {@code long}. This
jaroslav@1258: * conversion is analogous to a
jaroslav@1258: * narrowing primitive conversion from {@code long} to
jaroslav@1258: * {@code int} as defined in section 5.1.3 of
jaroslav@1258: * The Java™ Language Specification:
jaroslav@1258: * if this BigInteger is too big to fit in a
jaroslav@1258: * {@code long}, only the low-order 64 bits are returned.
jaroslav@1258: * Note that this conversion can lose information about the
jaroslav@1258: * overall magnitude of the BigInteger value as well as return a
jaroslav@1258: * result with the opposite sign.
jaroslav@1258: *
jaroslav@1258: * @return this BigInteger converted to a {@code long}.
jaroslav@1258: */
jaroslav@1258: public long longValue() {
jaroslav@1258: long result = 0;
jaroslav@1258:
jaroslav@1258: for (int i=1; i>=0; i--)
jaroslav@1258: result = (result << 32) + (getInt(i) & LONG_MASK);
jaroslav@1258: return result;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Converts this BigInteger to a {@code float}. This
jaroslav@1258: * conversion is similar to the
jaroslav@1258: * narrowing primitive conversion from {@code double} to
jaroslav@1258: * {@code float} as defined in section 5.1.3 of
jaroslav@1258: * The Java™ Language Specification:
jaroslav@1258: * if this BigInteger has too great a magnitude
jaroslav@1258: * to represent as a {@code float}, it will be converted to
jaroslav@1258: * {@link Float#NEGATIVE_INFINITY} or {@link
jaroslav@1258: * Float#POSITIVE_INFINITY} as appropriate. Note that even when
jaroslav@1258: * the return value is finite, this conversion can lose
jaroslav@1258: * information about the precision of the BigInteger value.
jaroslav@1258: *
jaroslav@1258: * @return this BigInteger converted to a {@code float}.
jaroslav@1258: */
jaroslav@1258: public float floatValue() {
jaroslav@1258: // Somewhat inefficient, but guaranteed to work.
jaroslav@1258: return Float.parseFloat(this.toString());
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Converts this BigInteger to a {@code double}. This
jaroslav@1258: * conversion is similar to the
jaroslav@1258: * narrowing primitive conversion from {@code double} to
jaroslav@1258: * {@code float} as defined in section 5.1.3 of
jaroslav@1258: * The Java™ Language Specification:
jaroslav@1258: * if this BigInteger has too great a magnitude
jaroslav@1258: * to represent as a {@code double}, it will be converted to
jaroslav@1258: * {@link Double#NEGATIVE_INFINITY} or {@link
jaroslav@1258: * Double#POSITIVE_INFINITY} as appropriate. Note that even when
jaroslav@1258: * the return value is finite, this conversion can lose
jaroslav@1258: * information about the precision of the BigInteger value.
jaroslav@1258: *
jaroslav@1258: * @return this BigInteger converted to a {@code double}.
jaroslav@1258: */
jaroslav@1258: public double doubleValue() {
jaroslav@1258: // Somewhat inefficient, but guaranteed to work.
jaroslav@1258: return Double.parseDouble(this.toString());
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a copy of the input array stripped of any leading zero bytes.
jaroslav@1258: */
jaroslav@1258: private static int[] stripLeadingZeroInts(int val[]) {
jaroslav@1258: int vlen = val.length;
jaroslav@1258: int keep;
jaroslav@1258:
jaroslav@1258: // Find first nonzero byte
jaroslav@1258: for (keep = 0; keep < vlen && val[keep] == 0; keep++)
jaroslav@1258: ;
jaroslav@1258: return java.util.Arrays.copyOfRange(val, keep, vlen);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the input array stripped of any leading zero bytes.
jaroslav@1258: * Since the source is trusted the copying may be skipped.
jaroslav@1258: */
jaroslav@1258: private static int[] trustedStripLeadingZeroInts(int val[]) {
jaroslav@1258: int vlen = val.length;
jaroslav@1258: int keep;
jaroslav@1258:
jaroslav@1258: // Find first nonzero byte
jaroslav@1258: for (keep = 0; keep < vlen && val[keep] == 0; keep++)
jaroslav@1258: ;
jaroslav@1258: return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns a copy of the input array stripped of any leading zero bytes.
jaroslav@1258: */
jaroslav@1258: private static int[] stripLeadingZeroBytes(byte a[]) {
jaroslav@1258: int byteLength = a.length;
jaroslav@1258: int keep;
jaroslav@1258:
jaroslav@1258: // Find first nonzero byte
jaroslav@1258: for (keep = 0; keep < byteLength && a[keep]==0; keep++)
jaroslav@1258: ;
jaroslav@1258:
jaroslav@1258: // Allocate new array and copy relevant part of input array
jaroslav@1258: int intLength = ((byteLength - keep) + 3) >>> 2;
jaroslav@1258: int[] result = new int[intLength];
jaroslav@1258: int b = byteLength - 1;
jaroslav@1258: for (int i = intLength-1; i >= 0; i--) {
jaroslav@1258: result[i] = a[b--] & 0xff;
jaroslav@1258: int bytesRemaining = b - keep + 1;
jaroslav@1258: int bytesToTransfer = Math.min(3, bytesRemaining);
jaroslav@1258: for (int j=8; j <= (bytesToTransfer << 3); j += 8)
jaroslav@1258: result[i] |= ((a[b--] & 0xff) << j);
jaroslav@1258: }
jaroslav@1258: return result;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Takes an array a representing a negative 2's-complement number and
jaroslav@1258: * returns the minimal (no leading zero bytes) unsigned whose value is -a.
jaroslav@1258: */
jaroslav@1258: private static int[] makePositive(byte a[]) {
jaroslav@1258: int keep, k;
jaroslav@1258: int byteLength = a.length;
jaroslav@1258:
jaroslav@1258: // Find first non-sign (0xff) byte of input
jaroslav@1258: for (keep=0; keep= 0; i--) {
jaroslav@1258: result[i] = a[b--] & 0xff;
jaroslav@1258: int numBytesToTransfer = Math.min(3, b-keep+1);
jaroslav@1258: if (numBytesToTransfer < 0)
jaroslav@1258: numBytesToTransfer = 0;
jaroslav@1258: for (int j=8; j <= 8*numBytesToTransfer; j += 8)
jaroslav@1258: result[i] |= ((a[b--] & 0xff) << j);
jaroslav@1258:
jaroslav@1258: // Mask indicates which bits must be complemented
jaroslav@1258: int mask = -1 >>> (8*(3-numBytesToTransfer));
jaroslav@1258: result[i] = ~result[i] & mask;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Add one to one's complement to generate two's complement
jaroslav@1258: for (int i=result.length-1; i>=0; i--) {
jaroslav@1258: result[i] = (int)((result[i] & LONG_MASK) + 1);
jaroslav@1258: if (result[i] != 0)
jaroslav@1258: break;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: return result;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Takes an array a representing a negative 2's-complement number and
jaroslav@1258: * returns the minimal (no leading zero ints) unsigned whose value is -a.
jaroslav@1258: */
jaroslav@1258: private static int[] makePositive(int a[]) {
jaroslav@1258: int keep, j;
jaroslav@1258:
jaroslav@1258: // Find first non-sign (0xffffffff) int of input
jaroslav@1258: for (keep=0; keep>> 5) + 1;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /* Returns sign bit */
jaroslav@1258: private int signBit() {
jaroslav@1258: return signum < 0 ? 1 : 0;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /* Returns an int of sign bits */
jaroslav@1258: private int signInt() {
jaroslav@1258: return signum < 0 ? -1 : 0;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the specified int of the little-endian two's complement
jaroslav@1258: * representation (int 0 is the least significant). The int number can
jaroslav@1258: * be arbitrarily high (values are logically preceded by infinitely many
jaroslav@1258: * sign ints).
jaroslav@1258: */
jaroslav@1258: private int getInt(int n) {
jaroslav@1258: if (n < 0)
jaroslav@1258: return 0;
jaroslav@1258: if (n >= mag.length)
jaroslav@1258: return signInt();
jaroslav@1258:
jaroslav@1258: int magInt = mag[mag.length-n-1];
jaroslav@1258:
jaroslav@1258: return (signum >= 0 ? magInt :
jaroslav@1258: (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the index of the int that contains the first nonzero int in the
jaroslav@1258: * little-endian binary representation of the magnitude (int 0 is the
jaroslav@1258: * least significant). If the magnitude is zero, return value is undefined.
jaroslav@1258: */
jaroslav@1258: private int firstNonzeroIntNum() {
jaroslav@1258: int fn = firstNonzeroIntNum - 2;
jaroslav@1258: if (fn == -2) { // firstNonzeroIntNum not initialized yet
jaroslav@1258: fn = 0;
jaroslav@1258:
jaroslav@1258: // Search for the first nonzero int
jaroslav@1258: int i;
jaroslav@1258: int mlen = mag.length;
jaroslav@1258: for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
jaroslav@1258: ;
jaroslav@1258: fn = mlen - i - 1;
jaroslav@1258: firstNonzeroIntNum = fn + 2; // offset by two to initialize
jaroslav@1258: }
jaroslav@1258: return fn;
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /** use serialVersionUID from JDK 1.1. for interoperability */
jaroslav@1258: private static final long serialVersionUID = -8287574255936472291L;
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Serializable fields for BigInteger.
jaroslav@1258: *
jaroslav@1258: * @serialField signum int
jaroslav@1258: * signum of this BigInteger.
jaroslav@1258: * @serialField magnitude int[]
jaroslav@1258: * magnitude array of this BigInteger.
jaroslav@1258: * @serialField bitCount int
jaroslav@1258: * number of bits in this BigInteger
jaroslav@1258: * @serialField bitLength int
jaroslav@1258: * the number of bits in the minimal two's-complement
jaroslav@1258: * representation of this BigInteger
jaroslav@1258: * @serialField lowestSetBit int
jaroslav@1258: * lowest set bit in the twos complement representation
jaroslav@1258: */
jaroslav@1258: private static final ObjectStreamField[] serialPersistentFields = {
jaroslav@1258: new ObjectStreamField("signum", Integer.TYPE),
jaroslav@1258: new ObjectStreamField("magnitude", byte[].class),
jaroslav@1258: new ObjectStreamField("bitCount", Integer.TYPE),
jaroslav@1258: new ObjectStreamField("bitLength", Integer.TYPE),
jaroslav@1258: new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
jaroslav@1258: new ObjectStreamField("lowestSetBit", Integer.TYPE)
jaroslav@1258: };
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Reconstitute the {@code BigInteger} instance from a stream (that is,
jaroslav@1258: * deserialize it). The magnitude is read in as an array of bytes
jaroslav@1258: * for historical reasons, but it is converted to an array of ints
jaroslav@1258: * and the byte array is discarded.
jaroslav@1258: * Note:
jaroslav@1258: * The current convention is to initialize the cache fields, bitCount,
jaroslav@1258: * bitLength and lowestSetBit, to 0 rather than some other marker value.
jaroslav@1258: * Therefore, no explicit action to set these fields needs to be taken in
jaroslav@1258: * readObject because those fields already have a 0 value be default since
jaroslav@1258: * defaultReadObject is not being used.
jaroslav@1258: */
jaroslav@1258: private void readObject(java.io.ObjectInputStream s)
jaroslav@1258: throws java.io.IOException, ClassNotFoundException {
jaroslav@1258: /*
jaroslav@1258: * In order to maintain compatibility with previous serialized forms,
jaroslav@1258: * the magnitude of a BigInteger is serialized as an array of bytes.
jaroslav@1258: * The magnitude field is used as a temporary store for the byte array
jaroslav@1258: * that is deserialized. The cached computation fields should be
jaroslav@1258: * transient but are serialized for compatibility reasons.
jaroslav@1258: */
jaroslav@1258:
jaroslav@1258: // prepare to read the alternate persistent fields
jaroslav@1258: ObjectInputStream.GetField fields = s.readFields();
jaroslav@1258:
jaroslav@1258: // Read the alternate persistent fields that we care about
jaroslav@1258: int sign = fields.get("signum", -2);
jaroslav@1258: byte[] magnitude = (byte[])fields.get("magnitude", null);
jaroslav@1258:
jaroslav@1258: // Validate signum
jaroslav@1258: if (sign < -1 || sign > 1) {
jaroslav@1258: String message = "BigInteger: Invalid signum value";
jaroslav@1258: if (fields.defaulted("signum"))
jaroslav@1258: message = "BigInteger: Signum not present in stream";
jaroslav@1258: throw new java.io.StreamCorruptedException(message);
jaroslav@1258: }
jaroslav@1258: if ((magnitude.length == 0) != (sign == 0)) {
jaroslav@1258: String message = "BigInteger: signum-magnitude mismatch";
jaroslav@1258: if (fields.defaulted("magnitude"))
jaroslav@1258: message = "BigInteger: Magnitude not present in stream";
jaroslav@1258: throw new java.io.StreamCorruptedException(message);
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Commit final fields via Unsafe
jaroslav@1258: unsafe.putIntVolatile(this, signumOffset, sign);
jaroslav@1258:
jaroslav@1258: // Calculate mag field from magnitude and discard magnitude
jaroslav@1258: unsafe.putObjectVolatile(this, magOffset,
jaroslav@1258: stripLeadingZeroBytes(magnitude));
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: // Support for resetting final fields while deserializing
jaroslav@1258: private static final sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
jaroslav@1258: private static final long signumOffset;
jaroslav@1258: private static final long magOffset;
jaroslav@1258: static {
jaroslav@1258: try {
jaroslav@1258: signumOffset = unsafe.objectFieldOffset
jaroslav@1258: (BigInteger.class.getDeclaredField("signum"));
jaroslav@1258: magOffset = unsafe.objectFieldOffset
jaroslav@1258: (BigInteger.class.getDeclaredField("mag"));
jaroslav@1258: } catch (Exception ex) {
jaroslav@1258: throw new Error(ex);
jaroslav@1258: }
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Save the {@code BigInteger} instance to a stream.
jaroslav@1258: * The magnitude of a BigInteger is serialized as a byte array for
jaroslav@1258: * historical reasons.
jaroslav@1258: *
jaroslav@1258: * @serialData two necessary fields are written as well as obsolete
jaroslav@1258: * fields for compatibility with older versions.
jaroslav@1258: */
jaroslav@1258: private void writeObject(ObjectOutputStream s) throws IOException {
jaroslav@1258: // set the values of the Serializable fields
jaroslav@1258: ObjectOutputStream.PutField fields = s.putFields();
jaroslav@1258: fields.put("signum", signum);
jaroslav@1258: fields.put("magnitude", magSerializedForm());
jaroslav@1258: // The values written for cached fields are compatible with older
jaroslav@1258: // versions, but are ignored in readObject so don't otherwise matter.
jaroslav@1258: fields.put("bitCount", -1);
jaroslav@1258: fields.put("bitLength", -1);
jaroslav@1258: fields.put("lowestSetBit", -2);
jaroslav@1258: fields.put("firstNonzeroByteNum", -2);
jaroslav@1258:
jaroslav@1258: // save them
jaroslav@1258: s.writeFields();
jaroslav@1258: }
jaroslav@1258:
jaroslav@1258: /**
jaroslav@1258: * Returns the mag array as an array of bytes.
jaroslav@1258: */
jaroslav@1258: private byte[] magSerializedForm() {
jaroslav@1258: int len = mag.length;
jaroslav@1258:
jaroslav@1258: int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0]));
jaroslav@1258: int byteLen = (bitLen + 7) >>> 3;
jaroslav@1258: byte[] result = new byte[byteLen];
jaroslav@1258:
jaroslav@1258: for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;
jaroslav@1258: i>=0; i--) {
jaroslav@1258: if (bytesCopied == 4) {
jaroslav@1258: nextInt = mag[intIndex--];
jaroslav@1258: bytesCopied = 1;
jaroslav@1258: } else {
jaroslav@1258: nextInt >>>= 8;
jaroslav@1258: bytesCopied++;
jaroslav@1258: }
jaroslav@1258: result[i] = (byte)nextInt;
jaroslav@1258: }
jaroslav@1258: return result;
jaroslav@1258: }
jaroslav@1258: }