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