Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/math/BigInteger.java
38829 views
/*1* Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* Portions Copyright (c) 1995 Colin Plumb. All rights reserved.27*/2829package java.math;3031import java.io.IOException;32import java.io.ObjectInputStream;33import java.io.ObjectOutputStream;34import java.io.ObjectStreamField;35import java.util.Arrays;36import java.util.Random;37import java.util.concurrent.ThreadLocalRandom;38import sun.misc.DoubleConsts;39import sun.misc.FloatConsts;4041/**42* Immutable arbitrary-precision integers. All operations behave as if43* BigIntegers were represented in two's-complement notation (like Java's44* primitive integer types). BigInteger provides analogues to all of Java's45* primitive integer operators, and all relevant methods from java.lang.Math.46* Additionally, BigInteger provides operations for modular arithmetic, GCD47* calculation, primality testing, prime generation, bit manipulation,48* and a few other miscellaneous operations.49*50* <p>Semantics of arithmetic operations exactly mimic those of Java's integer51* arithmetic operators, as defined in <i>The Java Language Specification</i>.52* For example, division by zero throws an {@code ArithmeticException}, and53* division of a negative by a positive yields a negative (or zero) remainder.54* All of the details in the Spec concerning overflow are ignored, as55* BigIntegers are made as large as necessary to accommodate the results of an56* operation.57*58* <p>Semantics of shift operations extend those of Java's shift operators59* to allow for negative shift distances. A right-shift with a negative60* shift distance results in a left shift, and vice-versa. The unsigned61* right shift operator ({@code >>>}) is omitted, as this operation makes62* little sense in combination with the "infinite word size" abstraction63* provided by this class.64*65* <p>Semantics of bitwise logical operations exactly mimic those of Java's66* bitwise integer operators. The binary operators ({@code and},67* {@code or}, {@code xor}) implicitly perform sign extension on the shorter68* of the two operands prior to performing the operation.69*70* <p>Comparison operations perform signed integer comparisons, analogous to71* those performed by Java's relational and equality operators.72*73* <p>Modular arithmetic operations are provided to compute residues, perform74* exponentiation, and compute multiplicative inverses. These methods always75* return a non-negative result, between {@code 0} and {@code (modulus - 1)},76* inclusive.77*78* <p>Bit operations operate on a single bit of the two's-complement79* representation of their operand. If necessary, the operand is sign-80* extended so that it contains the designated bit. None of the single-bit81* operations can produce a BigInteger with a different sign from the82* BigInteger being operated on, as they affect only a single bit, and the83* "infinite word size" abstraction provided by this class ensures that there84* are infinitely many "virtual sign bits" preceding each BigInteger.85*86* <p>For the sake of brevity and clarity, pseudo-code is used throughout the87* descriptions of BigInteger methods. The pseudo-code expression88* {@code (i + j)} is shorthand for "a BigInteger whose value is89* that of the BigInteger {@code i} plus that of the BigInteger {@code j}."90* The pseudo-code expression {@code (i == j)} is shorthand for91* "{@code true} if and only if the BigInteger {@code i} represents the same92* value as the BigInteger {@code j}." Other pseudo-code expressions are93* interpreted similarly.94*95* <p>All methods and constructors in this class throw96* {@code NullPointerException} when passed97* a null object reference for any input parameter.98*99* BigInteger must support values in the range100* -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to101* +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive)102* and may support values outside of that range.103*104* The range of probable prime values is limited and may be less than105* the full supported positive range of {@code BigInteger}.106* The range must be at least 1 to 2<sup>500000000</sup>.107*108* @implNote109* BigInteger constructors and operations throw {@code ArithmeticException} when110* the result is out of the supported range of111* -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to112* +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive).113*114* @see BigDecimal115* @author Josh Bloch116* @author Michael McCloskey117* @author Alan Eliasen118* @author Timothy Buktu119* @since JDK1.1120*/121122public class BigInteger extends Number implements Comparable<BigInteger> {123/**124* The signum of this BigInteger: -1 for negative, 0 for zero, or125* 1 for positive. Note that the BigInteger zero <i>must</i> have126* a signum of 0. This is necessary to ensures that there is exactly one127* representation for each BigInteger value.128*129* @serial130*/131final int signum;132133/**134* The magnitude of this BigInteger, in <i>big-endian</i> order: the135* zeroth element of this array is the most-significant int of the136* magnitude. The magnitude must be "minimal" in that the most-significant137* int ({@code mag[0]}) must be non-zero. This is necessary to138* ensure that there is exactly one representation for each BigInteger139* value. Note that this implies that the BigInteger zero has a140* zero-length mag array.141*/142final int[] mag;143144// These "redundant fields" are initialized with recognizable nonsense145// values, and cached the first time they are needed (or never, if they146// aren't needed).147148/**149* One plus the bitCount of this BigInteger. Zeros means unitialized.150*151* @serial152* @see #bitCount153* @deprecated Deprecated since logical value is offset from stored154* value and correction factor is applied in accessor method.155*/156@Deprecated157private int bitCount;158159/**160* One plus the bitLength of this BigInteger. Zeros means unitialized.161* (either value is acceptable).162*163* @serial164* @see #bitLength()165* @deprecated Deprecated since logical value is offset from stored166* value and correction factor is applied in accessor method.167*/168@Deprecated169private int bitLength;170171/**172* Two plus the lowest set bit of this BigInteger, as returned by173* getLowestSetBit().174*175* @serial176* @see #getLowestSetBit177* @deprecated Deprecated since logical value is offset from stored178* value and correction factor is applied in accessor method.179*/180@Deprecated181private int lowestSetBit;182183/**184* Two plus the index of the lowest-order int in the magnitude of this185* BigInteger that contains a nonzero int, or -2 (either value is acceptable).186* The least significant int has int-number 0, the next int in order of187* increasing significance has int-number 1, and so forth.188* @deprecated Deprecated since logical value is offset from stored189* value and correction factor is applied in accessor method.190*/191@Deprecated192private int firstNonzeroIntNum;193194/**195* This mask is used to obtain the value of an int as if it were unsigned.196*/197final static long LONG_MASK = 0xffffffffL;198199/**200* This constant limits {@code mag.length} of BigIntegers to the supported201* range.202*/203private static final int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26)204205/**206* Bit lengths larger than this constant can cause overflow in searchLen207* calculation and in BitSieve.singleSearch method.208*/209private static final int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;210211/**212* The threshold value for using Karatsuba multiplication. If the number213* of ints in both mag arrays are greater than this number, then214* Karatsuba multiplication will be used. This value is found215* experimentally to work well.216*/217private static final int KARATSUBA_THRESHOLD = 80;218219/**220* The threshold value for using 3-way Toom-Cook multiplication.221* If the number of ints in each mag array is greater than the222* Karatsuba threshold, and the number of ints in at least one of223* the mag arrays is greater than this threshold, then Toom-Cook224* multiplication will be used.225*/226private static final int TOOM_COOK_THRESHOLD = 240;227228/**229* The threshold value for using Karatsuba squaring. If the number230* of ints in the number are larger than this value,231* Karatsuba squaring will be used. This value is found232* experimentally to work well.233*/234private static final int KARATSUBA_SQUARE_THRESHOLD = 128;235236/**237* The threshold value for using Toom-Cook squaring. If the number238* of ints in the number are larger than this value,239* Toom-Cook squaring will be used. This value is found240* experimentally to work well.241*/242private static final int TOOM_COOK_SQUARE_THRESHOLD = 216;243244/**245* The threshold value for using Burnikel-Ziegler division. If the number246* of ints in the divisor are larger than this value, Burnikel-Ziegler247* division may be used. This value is found experimentally to work well.248*/249static final int BURNIKEL_ZIEGLER_THRESHOLD = 80;250251/**252* The offset value for using Burnikel-Ziegler division. If the number253* of ints in the divisor exceeds the Burnikel-Ziegler threshold, and the254* number of ints in the dividend is greater than the number of ints in the255* divisor plus this value, Burnikel-Ziegler division will be used. This256* value is found experimentally to work well.257*/258static final int BURNIKEL_ZIEGLER_OFFSET = 40;259260/**261* The threshold value for using Schoenhage recursive base conversion. If262* the number of ints in the number are larger than this value,263* the Schoenhage algorithm will be used. In practice, it appears that the264* Schoenhage routine is faster for any threshold down to 2, and is265* relatively flat for thresholds between 2-25, so this choice may be266* varied within this range for very small effect.267*/268private static final int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20;269270/**271* The threshold value for using squaring code to perform multiplication272* of a {@code BigInteger} instance by itself. If the number of ints in273* the number are larger than this value, {@code multiply(this)} will274* return {@code square()}.275*/276private static final int MULTIPLY_SQUARE_THRESHOLD = 20;277278/**279* The threshold for using an intrinsic version of280* implMontgomeryXXX to perform Montgomery multiplication. If the281* number of ints in the number is more than this value we do not282* use the intrinsic.283*/284private static final int MONTGOMERY_INTRINSIC_THRESHOLD = 512;285286287// Constructors288289/**290* Translates a byte array containing the two's-complement binary291* representation of a BigInteger into a BigInteger. The input array is292* assumed to be in <i>big-endian</i> byte-order: the most significant293* byte is in the zeroth element.294*295* @param val big-endian two's-complement binary representation of296* BigInteger.297* @throws NumberFormatException {@code val} is zero bytes long.298*/299public BigInteger(byte[] val) {300if (val.length == 0)301throw new NumberFormatException("Zero length BigInteger");302303if (val[0] < 0) {304mag = makePositive(val);305signum = -1;306} else {307mag = stripLeadingZeroBytes(val);308signum = (mag.length == 0 ? 0 : 1);309}310if (mag.length >= MAX_MAG_LENGTH) {311checkRange();312}313}314315/**316* This private constructor translates an int array containing the317* two's-complement binary representation of a BigInteger into a318* BigInteger. The input array is assumed to be in <i>big-endian</i>319* int-order: the most significant int is in the zeroth element.320*/321private BigInteger(int[] val) {322if (val.length == 0)323throw new NumberFormatException("Zero length BigInteger");324325if (val[0] < 0) {326mag = makePositive(val);327signum = -1;328} else {329mag = trustedStripLeadingZeroInts(val);330signum = (mag.length == 0 ? 0 : 1);331}332if (mag.length >= MAX_MAG_LENGTH) {333checkRange();334}335}336337/**338* Translates the sign-magnitude representation of a BigInteger into a339* BigInteger. The sign is represented as an integer signum value: -1 for340* negative, 0 for zero, or 1 for positive. The magnitude is a byte array341* in <i>big-endian</i> byte-order: the most significant byte is in the342* zeroth element. A zero-length magnitude array is permissible, and will343* result in a BigInteger value of 0, whether signum is -1, 0 or 1.344*345* @param signum signum of the number (-1 for negative, 0 for zero, 1346* for positive).347* @param magnitude big-endian binary representation of the magnitude of348* the number.349* @throws NumberFormatException {@code signum} is not one of the three350* legal values (-1, 0, and 1), or {@code signum} is 0 and351* {@code magnitude} contains one or more non-zero bytes.352*/353public BigInteger(int signum, byte[] magnitude) {354this.mag = stripLeadingZeroBytes(magnitude);355356if (signum < -1 || signum > 1)357throw(new NumberFormatException("Invalid signum value"));358359if (this.mag.length == 0) {360this.signum = 0;361} else {362if (signum == 0)363throw(new NumberFormatException("signum-magnitude mismatch"));364this.signum = signum;365}366if (mag.length >= MAX_MAG_LENGTH) {367checkRange();368}369}370371/**372* A constructor for internal use that translates the sign-magnitude373* representation of a BigInteger into a BigInteger. It checks the374* arguments and copies the magnitude so this constructor would be375* safe for external use.376*/377private BigInteger(int signum, int[] magnitude) {378this.mag = stripLeadingZeroInts(magnitude);379380if (signum < -1 || signum > 1)381throw(new NumberFormatException("Invalid signum value"));382383if (this.mag.length == 0) {384this.signum = 0;385} else {386if (signum == 0)387throw(new NumberFormatException("signum-magnitude mismatch"));388this.signum = signum;389}390if (mag.length >= MAX_MAG_LENGTH) {391checkRange();392}393}394395/**396* Translates the String representation of a BigInteger in the397* specified radix into a BigInteger. The String representation398* consists of an optional minus or plus sign followed by a399* sequence of one or more digits in the specified radix. The400* character-to-digit mapping is provided by {@code401* Character.digit}. The String may not contain any extraneous402* characters (whitespace, for example).403*404* @param val String representation of BigInteger.405* @param radix radix to be used in interpreting {@code val}.406* @throws NumberFormatException {@code val} is not a valid representation407* of a BigInteger in the specified radix, or {@code radix} is408* outside the range from {@link Character#MIN_RADIX} to409* {@link Character#MAX_RADIX}, inclusive.410* @see Character#digit411*/412public BigInteger(String val, int radix) {413int cursor = 0, numDigits;414final int len = val.length();415416if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)417throw new NumberFormatException("Radix out of range");418if (len == 0)419throw new NumberFormatException("Zero length BigInteger");420421// Check for at most one leading sign422int sign = 1;423int index1 = val.lastIndexOf('-');424int index2 = val.lastIndexOf('+');425if (index1 >= 0) {426if (index1 != 0 || index2 >= 0) {427throw new NumberFormatException("Illegal embedded sign character");428}429sign = -1;430cursor = 1;431} else if (index2 >= 0) {432if (index2 != 0) {433throw new NumberFormatException("Illegal embedded sign character");434}435cursor = 1;436}437if (cursor == len)438throw new NumberFormatException("Zero length BigInteger");439440// Skip leading zeros and compute number of digits in magnitude441while (cursor < len &&442Character.digit(val.charAt(cursor), radix) == 0) {443cursor++;444}445446if (cursor == len) {447signum = 0;448mag = ZERO.mag;449return;450}451452numDigits = len - cursor;453signum = sign;454455// Pre-allocate array of expected size. May be too large but can456// never be too small. Typically exact.457long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1;458if (numBits + 31 >= (1L << 32)) {459reportOverflow();460}461int numWords = (int) (numBits + 31) >>> 5;462int[] magnitude = new int[numWords];463464// Process first (potentially short) digit group465int firstGroupLen = numDigits % digitsPerInt[radix];466if (firstGroupLen == 0)467firstGroupLen = digitsPerInt[radix];468String group = val.substring(cursor, cursor += firstGroupLen);469magnitude[numWords - 1] = Integer.parseInt(group, radix);470if (magnitude[numWords - 1] < 0)471throw new NumberFormatException("Illegal digit");472473// Process remaining digit groups474int superRadix = intRadix[radix];475int groupVal = 0;476while (cursor < len) {477group = val.substring(cursor, cursor += digitsPerInt[radix]);478groupVal = Integer.parseInt(group, radix);479if (groupVal < 0)480throw new NumberFormatException("Illegal digit");481destructiveMulAdd(magnitude, superRadix, groupVal);482}483// Required for cases where the array was overallocated.484mag = trustedStripLeadingZeroInts(magnitude);485if (mag.length >= MAX_MAG_LENGTH) {486checkRange();487}488}489490/*491* Constructs a new BigInteger using a char array with radix=10.492* Sign is precalculated outside and not allowed in the val.493*/494BigInteger(char[] val, int sign, int len) {495int cursor = 0, numDigits;496497// Skip leading zeros and compute number of digits in magnitude498while (cursor < len && Character.digit(val[cursor], 10) == 0) {499cursor++;500}501if (cursor == len) {502signum = 0;503mag = ZERO.mag;504return;505}506507numDigits = len - cursor;508signum = sign;509// Pre-allocate array of expected size510int numWords;511if (len < 10) {512numWords = 1;513} else {514long numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1;515if (numBits + 31 >= (1L << 32)) {516reportOverflow();517}518numWords = (int) (numBits + 31) >>> 5;519}520int[] magnitude = new int[numWords];521522// Process first (potentially short) digit group523int firstGroupLen = numDigits % digitsPerInt[10];524if (firstGroupLen == 0)525firstGroupLen = digitsPerInt[10];526magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen);527528// Process remaining digit groups529while (cursor < len) {530int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);531destructiveMulAdd(magnitude, intRadix[10], groupVal);532}533mag = trustedStripLeadingZeroInts(magnitude);534if (mag.length >= MAX_MAG_LENGTH) {535checkRange();536}537}538539// Create an integer with the digits between the two indexes540// Assumes start < end. The result may be negative, but it541// is to be treated as an unsigned value.542private int parseInt(char[] source, int start, int end) {543int result = Character.digit(source[start++], 10);544if (result == -1)545throw new NumberFormatException(new String(source));546547for (int index = start; index < end; index++) {548int nextVal = Character.digit(source[index], 10);549if (nextVal == -1)550throw new NumberFormatException(new String(source));551result = 10*result + nextVal;552}553554return result;555}556557// bitsPerDigit in the given radix times 1024558// Rounded up to avoid underallocation.559private static long bitsPerDigit[] = { 0, 0,5601024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,5613790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,5624696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,5635253, 5295};564565// Multiply x array times word y in place, and add word z566private static void destructiveMulAdd(int[] x, int y, int z) {567// Perform the multiplication word by word568long ylong = y & LONG_MASK;569long zlong = z & LONG_MASK;570int len = x.length;571572long product = 0;573long carry = 0;574for (int i = len-1; i >= 0; i--) {575product = ylong * (x[i] & LONG_MASK) + carry;576x[i] = (int)product;577carry = product >>> 32;578}579580// Perform the addition581long sum = (x[len-1] & LONG_MASK) + zlong;582x[len-1] = (int)sum;583carry = sum >>> 32;584for (int i = len-2; i >= 0; i--) {585sum = (x[i] & LONG_MASK) + carry;586x[i] = (int)sum;587carry = sum >>> 32;588}589}590591/**592* Translates the decimal String representation of a BigInteger into a593* BigInteger. The String representation consists of an optional minus594* sign followed by a sequence of one or more decimal digits. The595* character-to-digit mapping is provided by {@code Character.digit}.596* The String may not contain any extraneous characters (whitespace, for597* example).598*599* @param val decimal String representation of BigInteger.600* @throws NumberFormatException {@code val} is not a valid representation601* of a BigInteger.602* @see Character#digit603*/604public BigInteger(String val) {605this(val, 10);606}607608/**609* Constructs a randomly generated BigInteger, uniformly distributed over610* the range 0 to (2<sup>{@code numBits}</sup> - 1), inclusive.611* The uniformity of the distribution assumes that a fair source of random612* bits is provided in {@code rnd}. Note that this constructor always613* constructs a non-negative BigInteger.614*615* @param numBits maximum bitLength of the new BigInteger.616* @param rnd source of randomness to be used in computing the new617* BigInteger.618* @throws IllegalArgumentException {@code numBits} is negative.619* @see #bitLength()620*/621public BigInteger(int numBits, Random rnd) {622this(1, randomBits(numBits, rnd));623}624625private static byte[] randomBits(int numBits, Random rnd) {626if (numBits < 0)627throw new IllegalArgumentException("numBits must be non-negative");628int numBytes = (int)(((long)numBits+7)/8); // avoid overflow629byte[] randomBits = new byte[numBytes];630631// Generate random bytes and mask out any excess bits632if (numBytes > 0) {633rnd.nextBytes(randomBits);634int excessBits = 8*numBytes - numBits;635randomBits[0] &= (1 << (8-excessBits)) - 1;636}637return randomBits;638}639640/**641* Constructs a randomly generated positive BigInteger that is probably642* prime, with the specified bitLength.643*644* <p>It is recommended that the {@link #probablePrime probablePrime}645* method be used in preference to this constructor unless there646* is a compelling need to specify a certainty.647*648* @param bitLength bitLength of the returned BigInteger.649* @param certainty a measure of the uncertainty that the caller is650* willing to tolerate. The probability that the new BigInteger651* represents a prime number will exceed652* (1 - 1/2<sup>{@code certainty}</sup>). The execution time of653* this constructor is proportional to the value of this parameter.654* @param rnd source of random bits used to select candidates to be655* tested for primality.656* @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.657* @see #bitLength()658*/659public BigInteger(int bitLength, int certainty, Random rnd) {660BigInteger prime;661662if (bitLength < 2)663throw new ArithmeticException("bitLength < 2");664prime = (bitLength < SMALL_PRIME_THRESHOLD665? smallPrime(bitLength, certainty, rnd)666: largePrime(bitLength, certainty, rnd));667signum = 1;668mag = prime.mag;669}670671// Minimum size in bits that the requested prime number has672// before we use the large prime number generating algorithms.673// The cutoff of 95 was chosen empirically for best performance.674private static final int SMALL_PRIME_THRESHOLD = 95;675676// Certainty required to meet the spec of probablePrime677private static final int DEFAULT_PRIME_CERTAINTY = 100;678679/**680* Returns a positive BigInteger that is probably prime, with the681* specified bitLength. The probability that a BigInteger returned682* by this method is composite does not exceed 2<sup>-100</sup>.683*684* @param bitLength bitLength of the returned BigInteger.685* @param rnd source of random bits used to select candidates to be686* tested for primality.687* @return a BigInteger of {@code bitLength} bits that is probably prime688* @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.689* @see #bitLength()690* @since 1.4691*/692public static BigInteger probablePrime(int bitLength, Random rnd) {693if (bitLength < 2)694throw new ArithmeticException("bitLength < 2");695696return (bitLength < SMALL_PRIME_THRESHOLD ?697smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :698largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));699}700701/**702* Find a random number of the specified bitLength that is probably prime.703* This method is used for smaller primes, its performance degrades on704* larger bitlengths.705*706* This method assumes bitLength > 1.707*/708private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {709int magLen = (bitLength + 31) >>> 5;710int temp[] = new int[magLen];711int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int712int highMask = (highBit << 1) - 1; // Bits to keep in high int713714while (true) {715// Construct a candidate716for (int i=0; i < magLen; i++)717temp[i] = rnd.nextInt();718temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length719if (bitLength > 2)720temp[magLen-1] |= 1; // Make odd if bitlen > 2721722BigInteger p = new BigInteger(temp, 1);723724// Do cheap "pre-test" if applicable725if (bitLength > 6) {726long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();727if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||728(r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||729(r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))730continue; // Candidate is composite; try another731}732733// All candidates of bitLength 2 and 3 are prime by this point734if (bitLength < 4)735return p;736737// Do expensive test if we survive pre-test (or it's inapplicable)738if (p.primeToCertainty(certainty, rnd))739return p;740}741}742743private static final BigInteger SMALL_PRIME_PRODUCT744= valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);745746/**747* Find a random number of the specified bitLength that is probably prime.748* This method is more appropriate for larger bitlengths since it uses749* a sieve to eliminate most composites before using a more expensive750* test.751*/752private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {753BigInteger p;754p = new BigInteger(bitLength, rnd).setBit(bitLength-1);755p.mag[p.mag.length-1] &= 0xfffffffe;756757// Use a sieve length likely to contain the next prime number758int searchLen = getPrimeSearchLen(bitLength);759BitSieve searchSieve = new BitSieve(p, searchLen);760BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);761762while ((candidate == null) || (candidate.bitLength() != bitLength)) {763p = p.add(BigInteger.valueOf(2*searchLen));764if (p.bitLength() != bitLength)765p = new BigInteger(bitLength, rnd).setBit(bitLength-1);766p.mag[p.mag.length-1] &= 0xfffffffe;767searchSieve = new BitSieve(p, searchLen);768candidate = searchSieve.retrieve(p, certainty, rnd);769}770return candidate;771}772773/**774* Returns the first integer greater than this {@code BigInteger} that775* is probably prime. The probability that the number returned by this776* method is composite does not exceed 2<sup>-100</sup>. This method will777* never skip over a prime when searching: if it returns {@code p}, there778* is no prime {@code q} such that {@code this < q < p}.779*780* @return the first integer greater than this {@code BigInteger} that781* is probably prime.782* @throws ArithmeticException {@code this < 0} or {@code this} is too large.783* @since 1.5784*/785public BigInteger nextProbablePrime() {786if (this.signum < 0)787throw new ArithmeticException("start < 0: " + this);788789// Handle trivial cases790if ((this.signum == 0) || this.equals(ONE))791return TWO;792793BigInteger result = this.add(ONE);794795// Fastpath for small numbers796if (result.bitLength() < SMALL_PRIME_THRESHOLD) {797798// Ensure an odd number799if (!result.testBit(0))800result = result.add(ONE);801802while (true) {803// Do cheap "pre-test" if applicable804if (result.bitLength() > 6) {805long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();806if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||807(r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||808(r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {809result = result.add(TWO);810continue; // Candidate is composite; try another811}812}813814// All candidates of bitLength 2 and 3 are prime by this point815if (result.bitLength() < 4)816return result;817818// The expensive test819if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))820return result;821822result = result.add(TWO);823}824}825826// Start at previous even number827if (result.testBit(0))828result = result.subtract(ONE);829830// Looking for the next large prime831int searchLen = getPrimeSearchLen(result.bitLength());832833while (true) {834BitSieve searchSieve = new BitSieve(result, searchLen);835BigInteger candidate = searchSieve.retrieve(result,836DEFAULT_PRIME_CERTAINTY, null);837if (candidate != null)838return candidate;839result = result.add(BigInteger.valueOf(2 * searchLen));840}841}842843private static int getPrimeSearchLen(int bitLength) {844if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) {845throw new ArithmeticException("Prime search implementation restriction on bitLength");846}847return bitLength / 20 * 64;848}849850/**851* Returns {@code true} if this BigInteger is probably prime,852* {@code false} if it's definitely composite.853*854* This method assumes bitLength > 2.855*856* @param certainty a measure of the uncertainty that the caller is857* willing to tolerate: if the call returns {@code true}858* the probability that this BigInteger is prime exceeds859* {@code (1 - 1/2<sup>certainty</sup>)}. The execution time of860* this method is proportional to the value of this parameter.861* @return {@code true} if this BigInteger is probably prime,862* {@code false} if it's definitely composite.863*/864boolean primeToCertainty(int certainty, Random random) {865int rounds = 0;866int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;867868// The relationship between the certainty and the number of rounds869// we perform is given in the draft standard ANSI X9.80, "PRIME870// NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".871int sizeInBits = this.bitLength();872if (sizeInBits < 100) {873rounds = 50;874rounds = n < rounds ? n : rounds;875return passesMillerRabin(rounds, random);876}877878if (sizeInBits < 256) {879rounds = 27;880} else if (sizeInBits < 512) {881rounds = 15;882} else if (sizeInBits < 768) {883rounds = 8;884} else if (sizeInBits < 1024) {885rounds = 4;886} else {887rounds = 2;888}889rounds = n < rounds ? n : rounds;890891return passesMillerRabin(rounds, random) && passesLucasLehmer();892}893894/**895* Returns true iff this BigInteger is a Lucas-Lehmer probable prime.896*897* The following assumptions are made:898* This BigInteger is a positive, odd number.899*/900private boolean passesLucasLehmer() {901BigInteger thisPlusOne = this.add(ONE);902903// Step 1904int d = 5;905while (jacobiSymbol(d, this) != -1) {906// 5, -7, 9, -11, ...907d = (d < 0) ? Math.abs(d)+2 : -(d+2);908}909910// Step 2911BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);912913// Step 3914return u.mod(this).equals(ZERO);915}916917/**918* Computes Jacobi(p,n).919* Assumes n positive, odd, n>=3.920*/921private static int jacobiSymbol(int p, BigInteger n) {922if (p == 0)923return 0;924925// Algorithm and comments adapted from Colin Plumb's C library.926int j = 1;927int u = n.mag[n.mag.length-1];928929// Make p positive930if (p < 0) {931p = -p;932int n8 = u & 7;933if ((n8 == 3) || (n8 == 7))934j = -j; // 3 (011) or 7 (111) mod 8935}936937// Get rid of factors of 2 in p938while ((p & 3) == 0)939p >>= 2;940if ((p & 1) == 0) {941p >>= 1;942if (((u ^ (u>>1)) & 2) != 0)943j = -j; // 3 (011) or 5 (101) mod 8944}945if (p == 1)946return j;947// Then, apply quadratic reciprocity948if ((p & u & 2) != 0) // p = u = 3 (mod 4)?949j = -j;950// And reduce u mod p951u = n.mod(BigInteger.valueOf(p)).intValue();952953// Now compute Jacobi(u,p), u < p954while (u != 0) {955while ((u & 3) == 0)956u >>= 2;957if ((u & 1) == 0) {958u >>= 1;959if (((p ^ (p>>1)) & 2) != 0)960j = -j; // 3 (011) or 5 (101) mod 8961}962if (u == 1)963return j;964// Now both u and p are odd, so use quadratic reciprocity965assert (u < p);966int t = u; u = p; p = t;967if ((u & p & 2) != 0) // u = p = 3 (mod 4)?968j = -j;969// Now u >= p, so it can be reduced970u %= p;971}972return 0;973}974975private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {976BigInteger d = BigInteger.valueOf(z);977BigInteger u = ONE; BigInteger u2;978BigInteger v = ONE; BigInteger v2;979980for (int i=k.bitLength()-2; i >= 0; i--) {981u2 = u.multiply(v).mod(n);982983v2 = v.square().add(d.multiply(u.square())).mod(n);984if (v2.testBit(0))985v2 = v2.subtract(n);986987v2 = v2.shiftRight(1);988989u = u2; v = v2;990if (k.testBit(i)) {991u2 = u.add(v).mod(n);992if (u2.testBit(0))993u2 = u2.subtract(n);994995u2 = u2.shiftRight(1);996v2 = v.add(d.multiply(u)).mod(n);997if (v2.testBit(0))998v2 = v2.subtract(n);999v2 = v2.shiftRight(1);10001001u = u2; v = v2;1002}1003}1004return u;1005}10061007/**1008* Returns true iff this BigInteger passes the specified number of1009* Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS1010* 186-2).1011*1012* The following assumptions are made:1013* This BigInteger is a positive, odd number greater than 2.1014* iterations<=50.1015*/1016private boolean passesMillerRabin(int iterations, Random rnd) {1017// Find a and m such that m is odd and this == 1 + 2**a * m1018BigInteger thisMinusOne = this.subtract(ONE);1019BigInteger m = thisMinusOne;1020int a = m.getLowestSetBit();1021m = m.shiftRight(a);10221023// Do the tests1024if (rnd == null) {1025rnd = ThreadLocalRandom.current();1026}1027for (int i=0; i < iterations; i++) {1028// Generate a uniform random on (1, this)1029BigInteger b;1030do {1031b = new BigInteger(this.bitLength(), rnd);1032} while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);10331034int j = 0;1035BigInteger z = b.modPow(m, this);1036while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {1037if (j > 0 && z.equals(ONE) || ++j == a)1038return false;1039z = z.modPow(TWO, this);1040}1041}1042return true;1043}10441045/**1046* This internal constructor differs from its public cousin1047* with the arguments reversed in two ways: it assumes that its1048* arguments are correct, and it doesn't copy the magnitude array.1049*/1050BigInteger(int[] magnitude, int signum) {1051this.signum = (magnitude.length == 0 ? 0 : signum);1052this.mag = magnitude;1053if (mag.length >= MAX_MAG_LENGTH) {1054checkRange();1055}1056}10571058/**1059* This private constructor is for internal use and assumes that its1060* arguments are correct.1061*/1062private BigInteger(byte[] magnitude, int signum) {1063this.signum = (magnitude.length == 0 ? 0 : signum);1064this.mag = stripLeadingZeroBytes(magnitude);1065if (mag.length >= MAX_MAG_LENGTH) {1066checkRange();1067}1068}10691070/**1071* Throws an {@code ArithmeticException} if the {@code BigInteger} would be1072* out of the supported range.1073*1074* @throws ArithmeticException if {@code this} exceeds the supported range.1075*/1076private void checkRange() {1077if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) {1078reportOverflow();1079}1080}10811082private static void reportOverflow() {1083throw new ArithmeticException("BigInteger would overflow supported range");1084}10851086//Static Factory Methods10871088/**1089* Returns a BigInteger whose value is equal to that of the1090* specified {@code long}. This "static factory method" is1091* provided in preference to a ({@code long}) constructor1092* because it allows for reuse of frequently used BigIntegers.1093*1094* @param val value of the BigInteger to return.1095* @return a BigInteger with the specified value.1096*/1097public static BigInteger valueOf(long val) {1098// If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant1099if (val == 0)1100return ZERO;1101if (val > 0 && val <= MAX_CONSTANT)1102return posConst[(int) val];1103else if (val < 0 && val >= -MAX_CONSTANT)1104return negConst[(int) -val];11051106return new BigInteger(val);1107}11081109/**1110* Constructs a BigInteger with the specified value, which may not be zero.1111*/1112private BigInteger(long val) {1113if (val < 0) {1114val = -val;1115signum = -1;1116} else {1117signum = 1;1118}11191120int highWord = (int)(val >>> 32);1121if (highWord == 0) {1122mag = new int[1];1123mag[0] = (int)val;1124} else {1125mag = new int[2];1126mag[0] = highWord;1127mag[1] = (int)val;1128}1129}11301131/**1132* Returns a BigInteger with the given two's complement representation.1133* Assumes that the input array will not be modified (the returned1134* BigInteger will reference the input array if feasible).1135*/1136private static BigInteger valueOf(int val[]) {1137return (val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val));1138}11391140// Constants11411142/**1143* Initialize static constant array when class is loaded.1144*/1145private final static int MAX_CONSTANT = 16;1146private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];1147private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];11481149/**1150* The cache of powers of each radix. This allows us to not have to1151* recalculate powers of radix^(2^n) more than once. This speeds1152* Schoenhage recursive base conversion significantly.1153*/1154private static volatile BigInteger[][] powerCache;11551156/** The cache of logarithms of radices for base conversion. */1157private static final double[] logCache;11581159/** The natural log of 2. This is used in computing cache indices. */1160private static final double LOG_TWO = Math.log(2.0);11611162static {1163assert 0 < KARATSUBA_THRESHOLD1164&& KARATSUBA_THRESHOLD < TOOM_COOK_THRESHOLD1165&& TOOM_COOK_THRESHOLD < Integer.MAX_VALUE1166&& 0 < KARATSUBA_SQUARE_THRESHOLD1167&& KARATSUBA_SQUARE_THRESHOLD < TOOM_COOK_SQUARE_THRESHOLD1168&& TOOM_COOK_SQUARE_THRESHOLD < Integer.MAX_VALUE :1169"Algorithm thresholds are inconsistent";11701171for (int i = 1; i <= MAX_CONSTANT; i++) {1172int[] magnitude = new int[1];1173magnitude[0] = i;1174posConst[i] = new BigInteger(magnitude, 1);1175negConst[i] = new BigInteger(magnitude, -1);1176}11771178/*1179* Initialize the cache of radix^(2^x) values used for base conversion1180* with just the very first value. Additional values will be created1181* on demand.1182*/1183powerCache = new BigInteger[Character.MAX_RADIX+1][];1184logCache = new double[Character.MAX_RADIX+1];11851186for (int i=Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {1187powerCache[i] = new BigInteger[] { BigInteger.valueOf(i) };1188logCache[i] = Math.log(i);1189}1190}11911192/**1193* The BigInteger constant zero.1194*1195* @since 1.21196*/1197public static final BigInteger ZERO = new BigInteger(new int[0], 0);11981199/**1200* The BigInteger constant one.1201*1202* @since 1.21203*/1204public static final BigInteger ONE = valueOf(1);12051206/**1207* The BigInteger constant two. (Not exported.)1208*/1209private static final BigInteger TWO = valueOf(2);12101211/**1212* The BigInteger constant -1. (Not exported.)1213*/1214private static final BigInteger NEGATIVE_ONE = valueOf(-1);12151216/**1217* The BigInteger constant ten.1218*1219* @since 1.51220*/1221public static final BigInteger TEN = valueOf(10);12221223// Arithmetic Operations12241225/**1226* Returns a BigInteger whose value is {@code (this + val)}.1227*1228* @param val value to be added to this BigInteger.1229* @return {@code this + val}1230*/1231public BigInteger add(BigInteger val) {1232if (val.signum == 0)1233return this;1234if (signum == 0)1235return val;1236if (val.signum == signum)1237return new BigInteger(add(mag, val.mag), signum);12381239int cmp = compareMagnitude(val);1240if (cmp == 0)1241return ZERO;1242int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)1243: subtract(val.mag, mag));1244resultMag = trustedStripLeadingZeroInts(resultMag);12451246return new BigInteger(resultMag, cmp == signum ? 1 : -1);1247}12481249/**1250* Package private methods used by BigDecimal code to add a BigInteger1251* with a long. Assumes val is not equal to INFLATED.1252*/1253BigInteger add(long val) {1254if (val == 0)1255return this;1256if (signum == 0)1257return valueOf(val);1258if (Long.signum(val) == signum)1259return new BigInteger(add(mag, Math.abs(val)), signum);1260int cmp = compareMagnitude(val);1261if (cmp == 0)1262return ZERO;1263int[] resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag));1264resultMag = trustedStripLeadingZeroInts(resultMag);1265return new BigInteger(resultMag, cmp == signum ? 1 : -1);1266}12671268/**1269* Adds the contents of the int array x and long value val. This1270* method allocates a new int array to hold the answer and returns1271* a reference to that array. Assumes x.length > 0 and val is1272* non-negative1273*/1274private static int[] add(int[] x, long val) {1275int[] y;1276long sum = 0;1277int xIndex = x.length;1278int[] result;1279int highWord = (int)(val >>> 32);1280if (highWord == 0) {1281result = new int[xIndex];1282sum = (x[--xIndex] & LONG_MASK) + val;1283result[xIndex] = (int)sum;1284} else {1285if (xIndex == 1) {1286result = new int[2];1287sum = val + (x[0] & LONG_MASK);1288result[1] = (int)sum;1289result[0] = (int)(sum >>> 32);1290return result;1291} else {1292result = new int[xIndex];1293sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK);1294result[xIndex] = (int)sum;1295sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32);1296result[xIndex] = (int)sum;1297}1298}1299// Copy remainder of longer number while carry propagation is required1300boolean carry = (sum >>> 32 != 0);1301while (xIndex > 0 && carry)1302carry = ((result[--xIndex] = x[xIndex] + 1) == 0);1303// Copy remainder of longer number1304while (xIndex > 0)1305result[--xIndex] = x[xIndex];1306// Grow result if necessary1307if (carry) {1308int bigger[] = new int[result.length + 1];1309System.arraycopy(result, 0, bigger, 1, result.length);1310bigger[0] = 0x01;1311return bigger;1312}1313return result;1314}13151316/**1317* Adds the contents of the int arrays x and y. This method allocates1318* a new int array to hold the answer and returns a reference to that1319* array.1320*/1321private static int[] add(int[] x, int[] y) {1322// If x is shorter, swap the two arrays1323if (x.length < y.length) {1324int[] tmp = x;1325x = y;1326y = tmp;1327}13281329int xIndex = x.length;1330int yIndex = y.length;1331int result[] = new int[xIndex];1332long sum = 0;1333if (yIndex == 1) {1334sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ;1335result[xIndex] = (int)sum;1336} else {1337// Add common parts of both numbers1338while (yIndex > 0) {1339sum = (x[--xIndex] & LONG_MASK) +1340(y[--yIndex] & LONG_MASK) + (sum >>> 32);1341result[xIndex] = (int)sum;1342}1343}1344// Copy remainder of longer number while carry propagation is required1345boolean carry = (sum >>> 32 != 0);1346while (xIndex > 0 && carry)1347carry = ((result[--xIndex] = x[xIndex] + 1) == 0);13481349// Copy remainder of longer number1350while (xIndex > 0)1351result[--xIndex] = x[xIndex];13521353// Grow result if necessary1354if (carry) {1355int bigger[] = new int[result.length + 1];1356System.arraycopy(result, 0, bigger, 1, result.length);1357bigger[0] = 0x01;1358return bigger;1359}1360return result;1361}13621363private static int[] subtract(long val, int[] little) {1364int highWord = (int)(val >>> 32);1365if (highWord == 0) {1366int result[] = new int[1];1367result[0] = (int)(val - (little[0] & LONG_MASK));1368return result;1369} else {1370int result[] = new int[2];1371if (little.length == 1) {1372long difference = ((int)val & LONG_MASK) - (little[0] & LONG_MASK);1373result[1] = (int)difference;1374// Subtract remainder of longer number while borrow propagates1375boolean borrow = (difference >> 32 != 0);1376if (borrow) {1377result[0] = highWord - 1;1378} else { // Copy remainder of longer number1379result[0] = highWord;1380}1381return result;1382} else { // little.length == 21383long difference = ((int)val & LONG_MASK) - (little[1] & LONG_MASK);1384result[1] = (int)difference;1385difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32);1386result[0] = (int)difference;1387return result;1388}1389}1390}13911392/**1393* Subtracts the contents of the second argument (val) from the1394* first (big). The first int array (big) must represent a larger number1395* than the second. This method allocates the space necessary to hold the1396* answer.1397* assumes val >= 01398*/1399private static int[] subtract(int[] big, long val) {1400int highWord = (int)(val >>> 32);1401int bigIndex = big.length;1402int result[] = new int[bigIndex];1403long difference = 0;14041405if (highWord == 0) {1406difference = (big[--bigIndex] & LONG_MASK) - val;1407result[bigIndex] = (int)difference;1408} else {1409difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK);1410result[bigIndex] = (int)difference;1411difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32);1412result[bigIndex] = (int)difference;1413}14141415// Subtract remainder of longer number while borrow propagates1416boolean borrow = (difference >> 32 != 0);1417while (bigIndex > 0 && borrow)1418borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);14191420// Copy remainder of longer number1421while (bigIndex > 0)1422result[--bigIndex] = big[bigIndex];14231424return result;1425}14261427/**1428* Returns a BigInteger whose value is {@code (this - val)}.1429*1430* @param val value to be subtracted from this BigInteger.1431* @return {@code this - val}1432*/1433public BigInteger subtract(BigInteger val) {1434if (val.signum == 0)1435return this;1436if (signum == 0)1437return val.negate();1438if (val.signum != signum)1439return new BigInteger(add(mag, val.mag), signum);14401441int cmp = compareMagnitude(val);1442if (cmp == 0)1443return ZERO;1444int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)1445: subtract(val.mag, mag));1446resultMag = trustedStripLeadingZeroInts(resultMag);1447return new BigInteger(resultMag, cmp == signum ? 1 : -1);1448}14491450/**1451* Subtracts the contents of the second int arrays (little) from the1452* first (big). The first int array (big) must represent a larger number1453* than the second. This method allocates the space necessary to hold the1454* answer.1455*/1456private static int[] subtract(int[] big, int[] little) {1457int bigIndex = big.length;1458int result[] = new int[bigIndex];1459int littleIndex = little.length;1460long difference = 0;14611462// Subtract common parts of both numbers1463while (littleIndex > 0) {1464difference = (big[--bigIndex] & LONG_MASK) -1465(little[--littleIndex] & LONG_MASK) +1466(difference >> 32);1467result[bigIndex] = (int)difference;1468}14691470// Subtract remainder of longer number while borrow propagates1471boolean borrow = (difference >> 32 != 0);1472while (bigIndex > 0 && borrow)1473borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);14741475// Copy remainder of longer number1476while (bigIndex > 0)1477result[--bigIndex] = big[bigIndex];14781479return result;1480}14811482/**1483* Returns a BigInteger whose value is {@code (this * val)}.1484*1485* @implNote An implementation may offer better algorithmic1486* performance when {@code val == this}.1487*1488* @param val value to be multiplied by this BigInteger.1489* @return {@code this * val}1490*/1491public BigInteger multiply(BigInteger val) {1492return multiply(val, false);1493}14941495/**1496* Returns a BigInteger whose value is {@code (this * val)}. If1497* the invocation is recursive certain overflow checks are skipped.1498*1499* @param val value to be multiplied by this BigInteger.1500* @param isRecursion whether this is a recursive invocation1501* @return {@code this * val}1502*/1503private BigInteger multiply(BigInteger val, boolean isRecursion) {1504if (val.signum == 0 || signum == 0)1505return ZERO;15061507int xlen = mag.length;15081509if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD) {1510return square();1511}15121513int ylen = val.mag.length;15141515if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD)) {1516int resultSign = signum == val.signum ? 1 : -1;1517if (val.mag.length == 1) {1518return multiplyByInt(mag,val.mag[0], resultSign);1519}1520if (mag.length == 1) {1521return multiplyByInt(val.mag,mag[0], resultSign);1522}1523int[] result = multiplyToLen(mag, xlen,1524val.mag, ylen, null);1525result = trustedStripLeadingZeroInts(result);1526return new BigInteger(result, resultSign);1527} else {1528if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {1529return multiplyKaratsuba(this, val);1530} else {1531//1532// In "Hacker's Delight" section 2-13, p.33, it is explained1533// that if x and y are unsigned 32-bit quantities and m and n1534// are their respective numbers of leading zeros within 32 bits,1535// then the number of leading zeros within their product as a1536// 64-bit unsigned quantity is either m + n or m + n + 1. If1537// their product is not to overflow, it cannot exceed 32 bits,1538// and so the number of leading zeros of the product within 641539// bits must be at least 32, i.e., the leftmost set bit is at1540// zero-relative position 31 or less.1541//1542// From the above there are three cases:1543//1544// m + n leftmost set bit condition1545// ----- ---------------- ---------1546// >= 32 x <= 64 - 32 = 32 no overflow1547// == 31 x >= 64 - 32 = 32 possible overflow1548// <= 30 x >= 64 - 31 = 33 definite overflow1549//1550// The "possible overflow" condition cannot be detected by1551// examning data lengths alone and requires further calculation.1552//1553// By analogy, if 'this' and 'val' have m and n as their1554// respective numbers of leading zeros within 32*MAX_MAG_LENGTH1555// bits, then:1556//1557// m + n >= 32*MAX_MAG_LENGTH no overflow1558// m + n == 32*MAX_MAG_LENGTH - 1 possible overflow1559// m + n <= 32*MAX_MAG_LENGTH - 2 definite overflow1560//1561// Note however that if the number of ints in the result1562// were to be MAX_MAG_LENGTH and mag[0] < 0, then there would1563// be overflow. As a result the leftmost bit (of mag[0]) cannot1564// be used and the constraints must be adjusted by one bit to:1565//1566// m + n > 32*MAX_MAG_LENGTH no overflow1567// m + n == 32*MAX_MAG_LENGTH possible overflow1568// m + n < 32*MAX_MAG_LENGTH definite overflow1569//1570// The foregoing leading zero-based discussion is for clarity1571// only. The actual calculations use the estimated bit length1572// of the product as this is more natural to the internal1573// array representation of the magnitude which has no leading1574// zero elements.1575//1576if (!isRecursion) {1577// The bitLength() instance method is not used here as we1578// are only considering the magnitudes as non-negative. The1579// Toom-Cook multiplication algorithm determines the sign1580// at its end from the two signum values.1581if (bitLength(mag, mag.length) +1582bitLength(val.mag, val.mag.length) >158332L*MAX_MAG_LENGTH) {1584reportOverflow();1585}1586}15871588return multiplyToomCook3(this, val);1589}1590}1591}15921593private static BigInteger multiplyByInt(int[] x, int y, int sign) {1594if (Integer.bitCount(y) == 1) {1595return new BigInteger(shiftLeft(x,Integer.numberOfTrailingZeros(y)), sign);1596}1597int xlen = x.length;1598int[] rmag = new int[xlen + 1];1599long carry = 0;1600long yl = y & LONG_MASK;1601int rstart = rmag.length - 1;1602for (int i = xlen - 1; i >= 0; i--) {1603long product = (x[i] & LONG_MASK) * yl + carry;1604rmag[rstart--] = (int)product;1605carry = product >>> 32;1606}1607if (carry == 0L) {1608rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);1609} else {1610rmag[rstart] = (int)carry;1611}1612return new BigInteger(rmag, sign);1613}16141615/**1616* Package private methods used by BigDecimal code to multiply a BigInteger1617* with a long. Assumes v is not equal to INFLATED.1618*/1619BigInteger multiply(long v) {1620if (v == 0 || signum == 0)1621return ZERO;1622if (v == BigDecimal.INFLATED)1623return multiply(BigInteger.valueOf(v));1624int rsign = (v > 0 ? signum : -signum);1625if (v < 0)1626v = -v;1627long dh = v >>> 32; // higher order bits1628long dl = v & LONG_MASK; // lower order bits16291630int xlen = mag.length;1631int[] value = mag;1632int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]);1633long carry = 0;1634int rstart = rmag.length - 1;1635for (int i = xlen - 1; i >= 0; i--) {1636long product = (value[i] & LONG_MASK) * dl + carry;1637rmag[rstart--] = (int)product;1638carry = product >>> 32;1639}1640rmag[rstart] = (int)carry;1641if (dh != 0L) {1642carry = 0;1643rstart = rmag.length - 2;1644for (int i = xlen - 1; i >= 0; i--) {1645long product = (value[i] & LONG_MASK) * dh +1646(rmag[rstart] & LONG_MASK) + carry;1647rmag[rstart--] = (int)product;1648carry = product >>> 32;1649}1650rmag[0] = (int)carry;1651}1652if (carry == 0L)1653rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);1654return new BigInteger(rmag, rsign);1655}16561657/**1658* Multiplies int arrays x and y to the specified lengths and places1659* the result into z. There will be no leading zeros in the resultant array.1660*/1661private static int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {1662int xstart = xlen - 1;1663int ystart = ylen - 1;16641665if (z == null || z.length < (xlen+ ylen))1666z = new int[xlen+ylen];16671668long carry = 0;1669for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {1670long product = (y[j] & LONG_MASK) *1671(x[xstart] & LONG_MASK) + carry;1672z[k] = (int)product;1673carry = product >>> 32;1674}1675z[xstart] = (int)carry;16761677for (int i = xstart-1; i >= 0; i--) {1678carry = 0;1679for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) {1680long product = (y[j] & LONG_MASK) *1681(x[i] & LONG_MASK) +1682(z[k] & LONG_MASK) + carry;1683z[k] = (int)product;1684carry = product >>> 32;1685}1686z[i] = (int)carry;1687}1688return z;1689}16901691/**1692* Multiplies two BigIntegers using the Karatsuba multiplication1693* algorithm. This is a recursive divide-and-conquer algorithm which is1694* more efficient for large numbers than what is commonly called the1695* "grade-school" algorithm used in multiplyToLen. If the numbers to be1696* multiplied have length n, the "grade-school" algorithm has an1697* asymptotic complexity of O(n^2). In contrast, the Karatsuba algorithm1698* has complexity of O(n^(log2(3))), or O(n^1.585). It achieves this1699* increased performance by doing 3 multiplies instead of 4 when1700* evaluating the product. As it has some overhead, should be used when1701* both numbers are larger than a certain threshold (found1702* experimentally).1703*1704* See: http://en.wikipedia.org/wiki/Karatsuba_algorithm1705*/1706private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) {1707int xlen = x.mag.length;1708int ylen = y.mag.length;17091710// The number of ints in each half of the number.1711int half = (Math.max(xlen, ylen)+1) / 2;17121713// xl and yl are the lower halves of x and y respectively,1714// xh and yh are the upper halves.1715BigInteger xl = x.getLower(half);1716BigInteger xh = x.getUpper(half);1717BigInteger yl = y.getLower(half);1718BigInteger yh = y.getUpper(half);17191720BigInteger p1 = xh.multiply(yh); // p1 = xh*yh1721BigInteger p2 = xl.multiply(yl); // p2 = xl*yl17221723// p3=(xh+xl)*(yh+yl)1724BigInteger p3 = xh.add(xl).multiply(yh.add(yl));17251726// result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p21727BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2);17281729if (x.signum != y.signum) {1730return result.negate();1731} else {1732return result;1733}1734}17351736/**1737* Multiplies two BigIntegers using a 3-way Toom-Cook multiplication1738* algorithm. This is a recursive divide-and-conquer algorithm which is1739* more efficient for large numbers than what is commonly called the1740* "grade-school" algorithm used in multiplyToLen. If the numbers to be1741* multiplied have length n, the "grade-school" algorithm has an1742* asymptotic complexity of O(n^2). In contrast, 3-way Toom-Cook has a1743* complexity of about O(n^1.465). It achieves this increased asymptotic1744* performance by breaking each number into three parts and by doing 51745* multiplies instead of 9 when evaluating the product. Due to overhead1746* (additions, shifts, and one division) in the Toom-Cook algorithm, it1747* should only be used when both numbers are larger than a certain1748* threshold (found experimentally). This threshold is generally larger1749* than that for Karatsuba multiplication, so this algorithm is generally1750* only used when numbers become significantly larger.1751*1752* The algorithm used is the "optimal" 3-way Toom-Cook algorithm outlined1753* by Marco Bodrato.1754*1755* See: http://bodrato.it/toom-cook/1756* http://bodrato.it/papers/#WAIFI20071757*1758* "Towards Optimal Toom-Cook Multiplication for Univariate and1759* Multivariate Polynomials in Characteristic 2 and 0." by Marco BODRATO;1760* In C.Carlet and B.Sunar, Eds., "WAIFI'07 proceedings", p. 116-133,1761* LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007.1762*1763*/1764private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) {1765int alen = a.mag.length;1766int blen = b.mag.length;17671768int largest = Math.max(alen, blen);17691770// k is the size (in ints) of the lower-order slices.1771int k = (largest+2)/3; // Equal to ceil(largest/3)17721773// r is the size (in ints) of the highest-order slice.1774int r = largest - 2*k;17751776// Obtain slices of the numbers. a2 and b2 are the most significant1777// bits of the numbers a and b, and a0 and b0 the least significant.1778BigInteger a0, a1, a2, b0, b1, b2;1779a2 = a.getToomSlice(k, r, 0, largest);1780a1 = a.getToomSlice(k, r, 1, largest);1781a0 = a.getToomSlice(k, r, 2, largest);1782b2 = b.getToomSlice(k, r, 0, largest);1783b1 = b.getToomSlice(k, r, 1, largest);1784b0 = b.getToomSlice(k, r, 2, largest);17851786BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;17871788v0 = a0.multiply(b0, true);1789da1 = a2.add(a0);1790db1 = b2.add(b0);1791vm1 = da1.subtract(a1).multiply(db1.subtract(b1), true);1792da1 = da1.add(a1);1793db1 = db1.add(b1);1794v1 = da1.multiply(db1, true);1795v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(1796db1.add(b2).shiftLeft(1).subtract(b0), true);1797vinf = a2.multiply(b2, true);17981799// The algorithm requires two divisions by 2 and one by 3.1800// All divisions are known to be exact, that is, they do not produce1801// remainders, and all results are positive. The divisions by 2 are1802// implemented as right shifts which are relatively efficient, leaving1803// only an exact division by 3, which is done by a specialized1804// linear-time algorithm.1805t2 = v2.subtract(vm1).exactDivideBy3();1806tm1 = v1.subtract(vm1).shiftRight(1);1807t1 = v1.subtract(v0);1808t2 = t2.subtract(t1).shiftRight(1);1809t1 = t1.subtract(tm1).subtract(vinf);1810t2 = t2.subtract(vinf.shiftLeft(1));1811tm1 = tm1.subtract(t2);18121813// Number of bits to shift left.1814int ss = k*32;18151816BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);18171818if (a.signum != b.signum) {1819return result.negate();1820} else {1821return result;1822}1823}182418251826/**1827* Returns a slice of a BigInteger for use in Toom-Cook multiplication.1828*1829* @param lowerSize The size of the lower-order bit slices.1830* @param upperSize The size of the higher-order bit slices.1831* @param slice The index of which slice is requested, which must be a1832* number from 0 to size-1. Slice 0 is the highest-order bits, and slice1833* size-1 are the lowest-order bits. Slice 0 may be of different size than1834* the other slices.1835* @param fullsize The size of the larger integer array, used to align1836* slices to the appropriate position when multiplying different-sized1837* numbers.1838*/1839private BigInteger getToomSlice(int lowerSize, int upperSize, int slice,1840int fullsize) {1841int start, end, sliceSize, len, offset;18421843len = mag.length;1844offset = fullsize - len;18451846if (slice == 0) {1847start = 0 - offset;1848end = upperSize - 1 - offset;1849} else {1850start = upperSize + (slice-1)*lowerSize - offset;1851end = start + lowerSize - 1;1852}18531854if (start < 0) {1855start = 0;1856}1857if (end < 0) {1858return ZERO;1859}18601861sliceSize = (end-start) + 1;18621863if (sliceSize <= 0) {1864return ZERO;1865}18661867// While performing Toom-Cook, all slices are positive and1868// the sign is adjusted when the final number is composed.1869if (start == 0 && sliceSize >= len) {1870return this.abs();1871}18721873int intSlice[] = new int[sliceSize];1874System.arraycopy(mag, start, intSlice, 0, sliceSize);18751876return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1);1877}18781879/**1880* Does an exact division (that is, the remainder is known to be zero)1881* of the specified number by 3. This is used in Toom-Cook1882* multiplication. This is an efficient algorithm that runs in linear1883* time. If the argument is not exactly divisible by 3, results are1884* undefined. Note that this is expected to be called with positive1885* arguments only.1886*/1887private BigInteger exactDivideBy3() {1888int len = mag.length;1889int[] result = new int[len];1890long x, w, q, borrow;1891borrow = 0L;1892for (int i=len-1; i >= 0; i--) {1893x = (mag[i] & LONG_MASK);1894w = x - borrow;1895if (borrow > x) { // Did we make the number go negative?1896borrow = 1L;1897} else {1898borrow = 0L;1899}19001901// 0xAAAAAAAB is the modular inverse of 3 (mod 2^32). Thus,1902// the effect of this is to divide by 3 (mod 2^32).1903// This is much faster than division on most architectures.1904q = (w * 0xAAAAAAABL) & LONG_MASK;1905result[i] = (int) q;19061907// Now check the borrow. The second check can of course be1908// eliminated if the first fails.1909if (q >= 0x55555556L) {1910borrow++;1911if (q >= 0xAAAAAAABL)1912borrow++;1913}1914}1915result = trustedStripLeadingZeroInts(result);1916return new BigInteger(result, signum);1917}19181919/**1920* Returns a new BigInteger representing n lower ints of the number.1921* This is used by Karatsuba multiplication and Karatsuba squaring.1922*/1923private BigInteger getLower(int n) {1924int len = mag.length;19251926if (len <= n) {1927return abs();1928}19291930int lowerInts[] = new int[n];1931System.arraycopy(mag, len-n, lowerInts, 0, n);19321933return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);1934}19351936/**1937* Returns a new BigInteger representing mag.length-n upper1938* ints of the number. This is used by Karatsuba multiplication and1939* Karatsuba squaring.1940*/1941private BigInteger getUpper(int n) {1942int len = mag.length;19431944if (len <= n) {1945return ZERO;1946}19471948int upperLen = len - n;1949int upperInts[] = new int[upperLen];1950System.arraycopy(mag, 0, upperInts, 0, upperLen);19511952return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1);1953}19541955// Squaring19561957/**1958* Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.1959*1960* @return {@code this<sup>2</sup>}1961*/1962private BigInteger square() {1963return square(false);1964}19651966/**1967* Returns a BigInteger whose value is {@code (this<sup>2</sup>)}. If1968* the invocation is recursive certain overflow checks are skipped.1969*1970* @param isRecursion whether this is a recursive invocation1971* @return {@code this<sup>2</sup>}1972*/1973private BigInteger square(boolean isRecursion) {1974if (signum == 0) {1975return ZERO;1976}1977int len = mag.length;19781979if (len < KARATSUBA_SQUARE_THRESHOLD) {1980int[] z = squareToLen(mag, len, null);1981return new BigInteger(trustedStripLeadingZeroInts(z), 1);1982} else {1983if (len < TOOM_COOK_SQUARE_THRESHOLD) {1984return squareKaratsuba();1985} else {1986//1987// For a discussion of overflow detection see multiply()1988//1989if (!isRecursion) {1990if (bitLength(mag, mag.length) > 16L*MAX_MAG_LENGTH) {1991reportOverflow();1992}1993}19941995return squareToomCook3();1996}1997}1998}19992000/**2001* Squares the contents of the int array x. The result is placed into the2002* int array z. The contents of x are not changed.2003*/2004private static final int[] squareToLen(int[] x, int len, int[] z) {2005int zlen = len << 1;2006if (z == null || z.length < zlen)2007z = new int[zlen];20082009// Execute checks before calling intrinsified method.2010implSquareToLenChecks(x, len, z, zlen);2011return implSquareToLen(x, len, z, zlen);2012}20132014/**2015* Parameters validation.2016*/2017private static void implSquareToLenChecks(int[] x, int len, int[] z, int zlen) throws RuntimeException {2018if (len < 1) {2019throw new IllegalArgumentException("invalid input length: " + len);2020}2021if (len > x.length) {2022throw new IllegalArgumentException("input length out of bound: " +2023len + " > " + x.length);2024}2025if (len * 2 > z.length) {2026throw new IllegalArgumentException("input length out of bound: " +2027(len * 2) + " > " + z.length);2028}2029if (zlen < 1) {2030throw new IllegalArgumentException("invalid input length: " + zlen);2031}2032if (zlen > z.length) {2033throw new IllegalArgumentException("input length out of bound: " +2034len + " > " + z.length);2035}2036}20372038/**2039* Java Runtime may use intrinsic for this method.2040*/2041private static final int[] implSquareToLen(int[] x, int len, int[] z, int zlen) {2042/*2043* The algorithm used here is adapted from Colin Plumb's C library.2044* Technique: Consider the partial products in the multiplication2045* of "abcde" by itself:2046*2047* a b c d e2048* * a b c d e2049* ==================2050* ae be ce de ee2051* ad bd cd dd de2052* ac bc cc cd ce2053* ab bb bc bd be2054* aa ab ac ad ae2055*2056* Note that everything above the main diagonal:2057* ae be ce de = (abcd) * e2058* ad bd cd = (abc) * d2059* ac bc = (ab) * c2060* ab = (a) * b2061*2062* is a copy of everything below the main diagonal:2063* de2064* cd ce2065* bc bd be2066* ab ac ad ae2067*2068* Thus, the sum is 2 * (off the diagonal) + diagonal.2069*2070* This is accumulated beginning with the diagonal (which2071* consist of the squares of the digits of the input), which is then2072* divided by two, the off-diagonal added, and multiplied by two2073* again. The low bit is simply a copy of the low bit of the2074* input, so it doesn't need special care.2075*/20762077// Store the squares, right shifted one bit (i.e., divided by 2)2078int lastProductLowWord = 0;2079for (int j=0, i=0; j < len; j++) {2080long piece = (x[j] & LONG_MASK);2081long product = piece * piece;2082z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);2083z[i++] = (int)(product >>> 1);2084lastProductLowWord = (int)product;2085}20862087// Add in off-diagonal sums2088for (int i=len, offset=1; i > 0; i--, offset+=2) {2089int t = x[i-1];2090t = mulAdd(z, x, offset, i-1, t);2091addOne(z, offset-1, i, t);2092}20932094// Shift back up and set low bit2095primitiveLeftShift(z, zlen, 1);2096z[zlen-1] |= x[len-1] & 1;20972098return z;2099}21002101/**2102* Squares a BigInteger using the Karatsuba squaring algorithm. It should2103* be used when both numbers are larger than a certain threshold (found2104* experimentally). It is a recursive divide-and-conquer algorithm that2105* has better asymptotic performance than the algorithm used in2106* squareToLen.2107*/2108private BigInteger squareKaratsuba() {2109int half = (mag.length+1) / 2;21102111BigInteger xl = getLower(half);2112BigInteger xh = getUpper(half);21132114BigInteger xhs = xh.square(); // xhs = xh^22115BigInteger xls = xl.square(); // xls = xl^221162117// xh^2 << 64 + (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^22118return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls);2119}21202121/**2122* Squares a BigInteger using the 3-way Toom-Cook squaring algorithm. It2123* should be used when both numbers are larger than a certain threshold2124* (found experimentally). It is a recursive divide-and-conquer algorithm2125* that has better asymptotic performance than the algorithm used in2126* squareToLen or squareKaratsuba.2127*/2128private BigInteger squareToomCook3() {2129int len = mag.length;21302131// k is the size (in ints) of the lower-order slices.2132int k = (len+2)/3; // Equal to ceil(largest/3)21332134// r is the size (in ints) of the highest-order slice.2135int r = len - 2*k;21362137// Obtain slices of the numbers. a2 is the most significant2138// bits of the number, and a0 the least significant.2139BigInteger a0, a1, a2;2140a2 = getToomSlice(k, r, 0, len);2141a1 = getToomSlice(k, r, 1, len);2142a0 = getToomSlice(k, r, 2, len);2143BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;21442145v0 = a0.square(true);2146da1 = a2.add(a0);2147vm1 = da1.subtract(a1).square(true);2148da1 = da1.add(a1);2149v1 = da1.square(true);2150vinf = a2.square(true);2151v2 = da1.add(a2).shiftLeft(1).subtract(a0).square(true);21522153// The algorithm requires two divisions by 2 and one by 3.2154// All divisions are known to be exact, that is, they do not produce2155// remainders, and all results are positive. The divisions by 2 are2156// implemented as right shifts which are relatively efficient, leaving2157// only a division by 3.2158// The division by 3 is done by an optimized algorithm for this case.2159t2 = v2.subtract(vm1).exactDivideBy3();2160tm1 = v1.subtract(vm1).shiftRight(1);2161t1 = v1.subtract(v0);2162t2 = t2.subtract(t1).shiftRight(1);2163t1 = t1.subtract(tm1).subtract(vinf);2164t2 = t2.subtract(vinf.shiftLeft(1));2165tm1 = tm1.subtract(t2);21662167// Number of bits to shift left.2168int ss = k*32;21692170return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);2171}21722173// Division21742175/**2176* Returns a BigInteger whose value is {@code (this / val)}.2177*2178* @param val value by which this BigInteger is to be divided.2179* @return {@code this / val}2180* @throws ArithmeticException if {@code val} is zero.2181*/2182public BigInteger divide(BigInteger val) {2183if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||2184mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {2185return divideKnuth(val);2186} else {2187return divideBurnikelZiegler(val);2188}2189}21902191/**2192* Returns a BigInteger whose value is {@code (this / val)} using an O(n^2) algorithm from Knuth.2193*2194* @param val value by which this BigInteger is to be divided.2195* @return {@code this / val}2196* @throws ArithmeticException if {@code val} is zero.2197* @see MutableBigInteger#divideKnuth(MutableBigInteger, MutableBigInteger, boolean)2198*/2199private BigInteger divideKnuth(BigInteger val) {2200MutableBigInteger q = new MutableBigInteger(),2201a = new MutableBigInteger(this.mag),2202b = new MutableBigInteger(val.mag);22032204a.divideKnuth(b, q, false);2205return q.toBigInteger(this.signum * val.signum);2206}22072208/**2209* Returns an array of two BigIntegers containing {@code (this / val)}2210* followed by {@code (this % val)}.2211*2212* @param val value by which this BigInteger is to be divided, and the2213* remainder computed.2214* @return an array of two BigIntegers: the quotient {@code (this / val)}2215* is the initial element, and the remainder {@code (this % val)}2216* is the final element.2217* @throws ArithmeticException if {@code val} is zero.2218*/2219public BigInteger[] divideAndRemainder(BigInteger val) {2220if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||2221mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {2222return divideAndRemainderKnuth(val);2223} else {2224return divideAndRemainderBurnikelZiegler(val);2225}2226}22272228/** Long division */2229private BigInteger[] divideAndRemainderKnuth(BigInteger val) {2230BigInteger[] result = new BigInteger[2];2231MutableBigInteger q = new MutableBigInteger(),2232a = new MutableBigInteger(this.mag),2233b = new MutableBigInteger(val.mag);2234MutableBigInteger r = a.divideKnuth(b, q);2235result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);2236result[1] = r.toBigInteger(this.signum);2237return result;2238}22392240/**2241* Returns a BigInteger whose value is {@code (this % val)}.2242*2243* @param val value by which this BigInteger is to be divided, and the2244* remainder computed.2245* @return {@code this % val}2246* @throws ArithmeticException if {@code val} is zero.2247*/2248public BigInteger remainder(BigInteger val) {2249if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||2250mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {2251return remainderKnuth(val);2252} else {2253return remainderBurnikelZiegler(val);2254}2255}22562257/** Long division */2258private BigInteger remainderKnuth(BigInteger val) {2259MutableBigInteger q = new MutableBigInteger(),2260a = new MutableBigInteger(this.mag),2261b = new MutableBigInteger(val.mag);22622263return a.divideKnuth(b, q).toBigInteger(this.signum);2264}22652266/**2267* Calculates {@code this / val} using the Burnikel-Ziegler algorithm.2268* @param val the divisor2269* @return {@code this / val}2270*/2271private BigInteger divideBurnikelZiegler(BigInteger val) {2272return divideAndRemainderBurnikelZiegler(val)[0];2273}22742275/**2276* Calculates {@code this % val} using the Burnikel-Ziegler algorithm.2277* @param val the divisor2278* @return {@code this % val}2279*/2280private BigInteger remainderBurnikelZiegler(BigInteger val) {2281return divideAndRemainderBurnikelZiegler(val)[1];2282}22832284/**2285* Computes {@code this / val} and {@code this % val} using the2286* Burnikel-Ziegler algorithm.2287* @param val the divisor2288* @return an array containing the quotient and remainder2289*/2290private BigInteger[] divideAndRemainderBurnikelZiegler(BigInteger val) {2291MutableBigInteger q = new MutableBigInteger();2292MutableBigInteger r = new MutableBigInteger(this).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q);2293BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum);2294BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum);2295return new BigInteger[] {qBigInt, rBigInt};2296}22972298/**2299* Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>.2300* Note that {@code exponent} is an integer rather than a BigInteger.2301*2302* @param exponent exponent to which this BigInteger is to be raised.2303* @return <tt>this<sup>exponent</sup></tt>2304* @throws ArithmeticException {@code exponent} is negative. (This would2305* cause the operation to yield a non-integer value.)2306*/2307public BigInteger pow(int exponent) {2308if (exponent < 0) {2309throw new ArithmeticException("Negative exponent");2310}2311if (signum == 0) {2312return (exponent == 0 ? ONE : this);2313}23142315BigInteger partToSquare = this.abs();23162317// Factor out powers of two from the base, as the exponentiation of2318// these can be done by left shifts only.2319// The remaining part can then be exponentiated faster. The2320// powers of two will be multiplied back at the end.2321int powersOfTwo = partToSquare.getLowestSetBit();2322long bitsToShiftLong = (long)powersOfTwo * exponent;2323if (bitsToShiftLong > Integer.MAX_VALUE) {2324reportOverflow();2325}2326int bitsToShift = (int)bitsToShiftLong;23272328int remainingBits;23292330// Factor the powers of two out quickly by shifting right, if needed.2331if (powersOfTwo > 0) {2332partToSquare = partToSquare.shiftRight(powersOfTwo);2333remainingBits = partToSquare.bitLength();2334if (remainingBits == 1) { // Nothing left but +/- 1?2335if (signum < 0 && (exponent&1) == 1) {2336return NEGATIVE_ONE.shiftLeft(bitsToShift);2337} else {2338return ONE.shiftLeft(bitsToShift);2339}2340}2341} else {2342remainingBits = partToSquare.bitLength();2343if (remainingBits == 1) { // Nothing left but +/- 1?2344if (signum < 0 && (exponent&1) == 1) {2345return NEGATIVE_ONE;2346} else {2347return ONE;2348}2349}2350}23512352// This is a quick way to approximate the size of the result,2353// similar to doing log2[n] * exponent. This will give an upper bound2354// of how big the result can be, and which algorithm to use.2355long scaleFactor = (long)remainingBits * exponent;23562357// Use slightly different algorithms for small and large operands.2358// See if the result will safely fit into a long. (Largest 2^63-1)2359if (partToSquare.mag.length == 1 && scaleFactor <= 62) {2360// Small number algorithm. Everything fits into a long.2361int newSign = (signum <0 && (exponent&1) == 1 ? -1 : 1);2362long result = 1;2363long baseToPow2 = partToSquare.mag[0] & LONG_MASK;23642365int workingExponent = exponent;23662367// Perform exponentiation using repeated squaring trick2368while (workingExponent != 0) {2369if ((workingExponent & 1) == 1) {2370result = result * baseToPow2;2371}23722373if ((workingExponent >>>= 1) != 0) {2374baseToPow2 = baseToPow2 * baseToPow2;2375}2376}23772378// Multiply back the powers of two (quickly, by shifting left)2379if (powersOfTwo > 0) {2380if (bitsToShift + scaleFactor <= 62) { // Fits in long?2381return valueOf((result << bitsToShift) * newSign);2382} else {2383return valueOf(result*newSign).shiftLeft(bitsToShift);2384}2385} else {2386return valueOf(result*newSign);2387}2388} else {2389if ((long)bitLength() * exponent / Integer.SIZE > MAX_MAG_LENGTH) {2390reportOverflow();2391}23922393// Large number algorithm. This is basically identical to2394// the algorithm above, but calls multiply() and square()2395// which may use more efficient algorithms for large numbers.2396BigInteger answer = ONE;23972398int workingExponent = exponent;2399// Perform exponentiation using repeated squaring trick2400while (workingExponent != 0) {2401if ((workingExponent & 1) == 1) {2402answer = answer.multiply(partToSquare);2403}24042405if ((workingExponent >>>= 1) != 0) {2406partToSquare = partToSquare.square();2407}2408}2409// Multiply back the (exponentiated) powers of two (quickly,2410// by shifting left)2411if (powersOfTwo > 0) {2412answer = answer.shiftLeft(bitsToShift);2413}24142415if (signum < 0 && (exponent&1) == 1) {2416return answer.negate();2417} else {2418return answer;2419}2420}2421}24222423/**2424* Returns a BigInteger whose value is the greatest common divisor of2425* {@code abs(this)} and {@code abs(val)}. Returns 0 if2426* {@code this == 0 && val == 0}.2427*2428* @param val value with which the GCD is to be computed.2429* @return {@code GCD(abs(this), abs(val))}2430*/2431public BigInteger gcd(BigInteger val) {2432if (val.signum == 0)2433return this.abs();2434else if (this.signum == 0)2435return val.abs();24362437MutableBigInteger a = new MutableBigInteger(this);2438MutableBigInteger b = new MutableBigInteger(val);24392440MutableBigInteger result = a.hybridGCD(b);24412442return result.toBigInteger(1);2443}24442445/**2446* Package private method to return bit length for an integer.2447*/2448static int bitLengthForInt(int n) {2449return 32 - Integer.numberOfLeadingZeros(n);2450}24512452/**2453* Left shift int array a up to len by n bits. Returns the array that2454* results from the shift since space may have to be reallocated.2455*/2456private static int[] leftShift(int[] a, int len, int n) {2457int nInts = n >>> 5;2458int nBits = n&0x1F;2459int bitsInHighWord = bitLengthForInt(a[0]);24602461// If shift can be done without recopy, do so2462if (n <= (32-bitsInHighWord)) {2463primitiveLeftShift(a, len, nBits);2464return a;2465} else { // Array must be resized2466if (nBits <= (32-bitsInHighWord)) {2467int result[] = new int[nInts+len];2468System.arraycopy(a, 0, result, 0, len);2469primitiveLeftShift(result, result.length, nBits);2470return result;2471} else {2472int result[] = new int[nInts+len+1];2473System.arraycopy(a, 0, result, 0, len);2474primitiveRightShift(result, result.length, 32 - nBits);2475return result;2476}2477}2478}24792480// shifts a up to len right n bits assumes no leading zeros, 0<n<322481static void primitiveRightShift(int[] a, int len, int n) {2482int n2 = 32 - n;2483for (int i=len-1, c=a[i]; i > 0; i--) {2484int b = c;2485c = a[i-1];2486a[i] = (c << n2) | (b >>> n);2487}2488a[0] >>>= n;2489}24902491// shifts a up to len left n bits assumes no leading zeros, 0<=n<322492static void primitiveLeftShift(int[] a, int len, int n) {2493if (len == 0 || n == 0)2494return;24952496int n2 = 32 - n;2497for (int i=0, c=a[i], m=i+len-1; i < m; i++) {2498int b = c;2499c = a[i+1];2500a[i] = (b << n) | (c >>> n2);2501}2502a[len-1] <<= n;2503}25042505/**2506* Calculate bitlength of contents of the first len elements an int array,2507* assuming there are no leading zero ints.2508*/2509private static int bitLength(int[] val, int len) {2510if (len == 0)2511return 0;2512return ((len - 1) << 5) + bitLengthForInt(val[0]);2513}25142515/**2516* Returns a BigInteger whose value is the absolute value of this2517* BigInteger.2518*2519* @return {@code abs(this)}2520*/2521public BigInteger abs() {2522return (signum >= 0 ? this : this.negate());2523}25242525/**2526* Returns a BigInteger whose value is {@code (-this)}.2527*2528* @return {@code -this}2529*/2530public BigInteger negate() {2531return new BigInteger(this.mag, -this.signum);2532}25332534/**2535* Returns the signum function of this BigInteger.2536*2537* @return -1, 0 or 1 as the value of this BigInteger is negative, zero or2538* positive.2539*/2540public int signum() {2541return this.signum;2542}25432544// Modular Arithmetic Operations25452546/**2547* Returns a BigInteger whose value is {@code (this mod m}). This method2548* differs from {@code remainder} in that it always returns a2549* <i>non-negative</i> BigInteger.2550*2551* @param m the modulus.2552* @return {@code this mod m}2553* @throws ArithmeticException {@code m} ≤ 02554* @see #remainder2555*/2556public BigInteger mod(BigInteger m) {2557if (m.signum <= 0)2558throw new ArithmeticException("BigInteger: modulus not positive");25592560BigInteger result = this.remainder(m);2561return (result.signum >= 0 ? result : result.add(m));2562}25632564/**2565* Returns a BigInteger whose value is2566* <tt>(this<sup>exponent</sup> mod m)</tt>. (Unlike {@code pow}, this2567* method permits negative exponents.)2568*2569* @param exponent the exponent.2570* @param m the modulus.2571* @return <tt>this<sup>exponent</sup> mod m</tt>2572* @throws ArithmeticException {@code m} ≤ 0 or the exponent is2573* negative and this BigInteger is not <i>relatively2574* prime</i> to {@code m}.2575* @see #modInverse2576*/2577public BigInteger modPow(BigInteger exponent, BigInteger m) {2578if (m.signum <= 0)2579throw new ArithmeticException("BigInteger: modulus not positive");25802581// Trivial cases2582if (exponent.signum == 0)2583return (m.equals(ONE) ? ZERO : ONE);25842585if (this.equals(ONE))2586return (m.equals(ONE) ? ZERO : ONE);25872588if (this.equals(ZERO) && exponent.signum >= 0)2589return ZERO;25902591if (this.equals(negConst[1]) && (!exponent.testBit(0)))2592return (m.equals(ONE) ? ZERO : ONE);25932594boolean invertResult;2595if ((invertResult = (exponent.signum < 0)))2596exponent = exponent.negate();25972598BigInteger base = (this.signum < 0 || this.compareTo(m) >= 02599? this.mod(m) : this);2600BigInteger result;2601if (m.testBit(0)) { // odd modulus2602result = base.oddModPow(exponent, m);2603} else {2604/*2605* Even modulus. Tear it into an "odd part" (m1) and power of two2606* (m2), exponentiate mod m1, manually exponentiate mod m2, and2607* use Chinese Remainder Theorem to combine results.2608*/26092610// Tear m apart into odd part (m1) and power of 2 (m2)2611int p = m.getLowestSetBit(); // Max pow of 2 that divides m26122613BigInteger m1 = m.shiftRight(p); // m/2**p2614BigInteger m2 = ONE.shiftLeft(p); // 2**p26152616// Calculate new base from m12617BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 02618? this.mod(m1) : this);26192620// Caculate (base ** exponent) mod m1.2621BigInteger a1 = (m1.equals(ONE) ? ZERO :2622base2.oddModPow(exponent, m1));26232624// Calculate (this ** exponent) mod m22625BigInteger a2 = base.modPow2(exponent, p);26262627// Combine results using Chinese Remainder Theorem2628BigInteger y1 = m2.modInverse(m1);2629BigInteger y2 = m1.modInverse(m2);26302631if (m.mag.length < MAX_MAG_LENGTH / 2) {2632result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);2633} else {2634MutableBigInteger t1 = new MutableBigInteger();2635new MutableBigInteger(a1.multiply(m2)).multiply(new MutableBigInteger(y1), t1);2636MutableBigInteger t2 = new MutableBigInteger();2637new MutableBigInteger(a2.multiply(m1)).multiply(new MutableBigInteger(y2), t2);2638t1.add(t2);2639MutableBigInteger q = new MutableBigInteger();2640result = t1.divide(new MutableBigInteger(m), q).toBigInteger();2641}2642}26432644return (invertResult ? result.modInverse(m) : result);2645}26462647// Montgomery multiplication. These are wrappers for2648// implMontgomeryXX routines which are expected to be replaced by2649// virtual machine intrinsics. We don't use the intrinsics for2650// very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be2651// larger than any reasonable crypto key.2652private static int[] montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv,2653int[] product) {2654implMontgomeryMultiplyChecks(a, b, n, len, product);2655if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {2656// Very long argument: do not use an intrinsic2657product = multiplyToLen(a, len, b, len, product);2658return montReduce(product, n, len, (int)inv);2659} else {2660return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len));2661}2662}2663private static int[] montgomerySquare(int[] a, int[] n, int len, long inv,2664int[] product) {2665implMontgomeryMultiplyChecks(a, a, n, len, product);2666if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {2667// Very long argument: do not use an intrinsic2668product = squareToLen(a, len, product);2669return montReduce(product, n, len, (int)inv);2670} else {2671return implMontgomerySquare(a, n, len, inv, materialize(product, len));2672}2673}26742675// Range-check everything.2676private static void implMontgomeryMultiplyChecks2677(int[] a, int[] b, int[] n, int len, int[] product) throws RuntimeException {2678if (len % 2 != 0) {2679throw new IllegalArgumentException("input array length must be even: " + len);2680}26812682if (len < 1) {2683throw new IllegalArgumentException("invalid input length: " + len);2684}26852686if (len > a.length ||2687len > b.length ||2688len > n.length ||2689(product != null && len > product.length)) {2690throw new IllegalArgumentException("input array length out of bound: " + len);2691}2692}26932694// Make sure that the int array z (which is expected to contain2695// the result of a Montgomery multiplication) is present and2696// sufficiently large.2697private static int[] materialize(int[] z, int len) {2698if (z == null || z.length < len)2699z = new int[len];2700return z;2701}27022703// These methods are intended to be be replaced by virtual machine2704// intrinsics.2705private static int[] implMontgomeryMultiply(int[] a, int[] b, int[] n, int len,2706long inv, int[] product) {2707product = multiplyToLen(a, len, b, len, product);2708return montReduce(product, n, len, (int)inv);2709}2710private static int[] implMontgomerySquare(int[] a, int[] n, int len,2711long inv, int[] product) {2712product = squareToLen(a, len, product);2713return montReduce(product, n, len, (int)inv);2714}27152716static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,2717Integer.MAX_VALUE}; // Sentinel27182719/**2720* Returns a BigInteger whose value is x to the power of y mod z.2721* Assumes: z is odd && x < z.2722*/2723private BigInteger oddModPow(BigInteger y, BigInteger z) {2724/*2725* The algorithm is adapted from Colin Plumb's C library.2726*2727* The window algorithm:2728* The idea is to keep a running product of b1 = n^(high-order bits of exp)2729* and then keep appending exponent bits to it. The following patterns2730* apply to a 3-bit window (k = 3):2731* To append 0: square2732* To append 1: square, multiply by n^12733* To append 10: square, multiply by n^1, square2734* To append 11: square, square, multiply by n^32735* To append 100: square, multiply by n^1, square, square2736* To append 101: square, square, square, multiply by n^52737* To append 110: square, square, multiply by n^3, square2738* To append 111: square, square, square, multiply by n^72739*2740* Since each pattern involves only one multiply, the longer the pattern2741* the better, except that a 0 (no multiplies) can be appended directly.2742* We precompute a table of odd powers of n, up to 2^k, and can then2743* multiply k bits of exponent at a time. Actually, assuming random2744* exponents, there is on average one zero bit between needs to2745* multiply (1/2 of the time there's none, 1/4 of the time there's 1,2746* 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so2747* you have to do one multiply per k+1 bits of exponent.2748*2749* The loop walks down the exponent, squaring the result buffer as2750* it goes. There is a wbits+1 bit lookahead buffer, buf, that is2751* filled with the upcoming exponent bits. (What is read after the2752* end of the exponent is unimportant, but it is filled with zero here.)2753* When the most-significant bit of this buffer becomes set, i.e.2754* (buf & tblmask) != 0, we have to decide what pattern to multiply2755* by, and when to do it. We decide, remember to do it in future2756* after a suitable number of squarings have passed (e.g. a pattern2757* of "100" in the buffer requires that we multiply by n^1 immediately;2758* a pattern of "110" calls for multiplying by n^3 after one more2759* squaring), clear the buffer, and continue.2760*2761* When we start, there is one more optimization: the result buffer2762* is implcitly one, so squaring it or multiplying by it can be2763* optimized away. Further, if we start with a pattern like "100"2764* in the lookahead window, rather than placing n into the buffer2765* and then starting to square it, we have already computed n^22766* to compute the odd-powers table, so we can place that into2767* the buffer and save a squaring.2768*2769* This means that if you have a k-bit window, to compute n^z,2770* where z is the high k bits of the exponent, 1/2 of the time2771* it requires no squarings. 1/4 of the time, it requires 12772* squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.2773* And the remaining 1/2^(k-1) of the time, the top k bits are a2774* 1 followed by k-1 0 bits, so it again only requires k-22775* squarings, not k-1. The average of these is 1. Add that2776* to the one squaring we have to do to compute the table,2777* and you'll see that a k-bit window saves k-2 squarings2778* as well as reducing the multiplies. (It actually doesn't2779* hurt in the case k = 1, either.)2780*/2781// Special case for exponent of one2782if (y.equals(ONE))2783return this;27842785// Special case for base of zero2786if (signum == 0)2787return ZERO;27882789int[] base = mag.clone();2790int[] exp = y.mag;2791int[] mod = z.mag;2792int modLen = mod.length;27932794// Make modLen even. It is conventional to use a cryptographic2795// modulus that is 512, 768, 1024, or 2048 bits, so this code2796// will not normally be executed. However, it is necessary for2797// the correct functioning of the HotSpot intrinsics.2798if ((modLen & 1) != 0) {2799int[] x = new int[modLen + 1];2800System.arraycopy(mod, 0, x, 1, modLen);2801mod = x;2802modLen++;2803}28042805// Select an appropriate window size2806int wbits = 0;2807int ebits = bitLength(exp, exp.length);2808// if exponent is 65537 (0x10001), use minimum window size2809if ((ebits != 17) || (exp[0] != 65537)) {2810while (ebits > bnExpModThreshTable[wbits]) {2811wbits++;2812}2813}28142815// Calculate appropriate table size2816int tblmask = 1 << wbits;28172818// Allocate table for precomputed odd powers of base in Montgomery form2819int[][] table = new int[tblmask][];2820for (int i=0; i < tblmask; i++)2821table[i] = new int[modLen];28222823// Compute the modular inverse of the least significant 64-bit2824// digit of the modulus2825long n0 = (mod[modLen-1] & LONG_MASK) + ((mod[modLen-2] & LONG_MASK) << 32);2826long inv = -MutableBigInteger.inverseMod64(n0);28272828// Convert base to Montgomery form2829int[] a = leftShift(base, base.length, modLen << 5);28302831MutableBigInteger q = new MutableBigInteger(),2832a2 = new MutableBigInteger(a),2833b2 = new MutableBigInteger(mod);2834b2.normalize(); // MutableBigInteger.divide() assumes that its2835// divisor is in normal form.28362837MutableBigInteger r= a2.divide(b2, q);2838table[0] = r.toIntArray();28392840// Pad table[0] with leading zeros so its length is at least modLen2841if (table[0].length < modLen) {2842int offset = modLen - table[0].length;2843int[] t2 = new int[modLen];2844System.arraycopy(table[0], 0, t2, offset, table[0].length);2845table[0] = t2;2846}28472848// Set b to the square of the base2849int[] b = montgomerySquare(table[0], mod, modLen, inv, null);28502851// Set t to high half of b2852int[] t = Arrays.copyOf(b, modLen);28532854// Fill in the table with odd powers of the base2855for (int i=1; i < tblmask; i++) {2856table[i] = montgomeryMultiply(t, table[i-1], mod, modLen, inv, null);2857}28582859// Pre load the window that slides over the exponent2860int bitpos = 1 << ((ebits-1) & (32-1));28612862int buf = 0;2863int elen = exp.length;2864int eIndex = 0;2865for (int i = 0; i <= wbits; i++) {2866buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);2867bitpos >>>= 1;2868if (bitpos == 0) {2869eIndex++;2870bitpos = 1 << (32-1);2871elen--;2872}2873}28742875int multpos = ebits;28762877// The first iteration, which is hoisted out of the main loop2878ebits--;2879boolean isone = true;28802881multpos = ebits - wbits;2882while ((buf & 1) == 0) {2883buf >>>= 1;2884multpos++;2885}28862887int[] mult = table[buf >>> 1];28882889buf = 0;2890if (multpos == ebits)2891isone = false;28922893// The main loop2894while (true) {2895ebits--;2896// Advance the window2897buf <<= 1;28982899if (elen != 0) {2900buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;2901bitpos >>>= 1;2902if (bitpos == 0) {2903eIndex++;2904bitpos = 1 << (32-1);2905elen--;2906}2907}29082909// Examine the window for pending multiplies2910if ((buf & tblmask) != 0) {2911multpos = ebits - wbits;2912while ((buf & 1) == 0) {2913buf >>>= 1;2914multpos++;2915}2916mult = table[buf >>> 1];2917buf = 0;2918}29192920// Perform multiply2921if (ebits == multpos) {2922if (isone) {2923b = mult.clone();2924isone = false;2925} else {2926t = b;2927a = montgomeryMultiply(t, mult, mod, modLen, inv, a);2928t = a; a = b; b = t;2929}2930}29312932// Check if done2933if (ebits == 0)2934break;29352936// Square the input2937if (!isone) {2938t = b;2939a = montgomerySquare(t, mod, modLen, inv, a);2940t = a; a = b; b = t;2941}2942}29432944// Convert result out of Montgomery form and return2945int[] t2 = new int[2*modLen];2946System.arraycopy(b, 0, t2, modLen, modLen);29472948b = montReduce(t2, mod, modLen, (int)inv);29492950t2 = Arrays.copyOf(b, modLen);29512952return new BigInteger(1, t2);2953}29542955/**2956* Montgomery reduce n, modulo mod. This reduces modulo mod and divides2957* by 2^(32*mlen). Adapted from Colin Plumb's C library.2958*/2959private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {2960int c=0;2961int len = mlen;2962int offset=0;29632964do {2965int nEnd = n[n.length-1-offset];2966int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);2967c += addOne(n, offset, mlen, carry);2968offset++;2969} while (--len > 0);29702971while (c > 0)2972c += subN(n, mod, mlen);29732974while (intArrayCmpToLen(n, mod, mlen) >= 0)2975subN(n, mod, mlen);29762977return n;2978}297929802981/*2982* Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,2983* equal to, or greater than arg2 up to length len.2984*/2985private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {2986for (int i=0; i < len; i++) {2987long b1 = arg1[i] & LONG_MASK;2988long b2 = arg2[i] & LONG_MASK;2989if (b1 < b2)2990return -1;2991if (b1 > b2)2992return 1;2993}2994return 0;2995}29962997/**2998* Subtracts two numbers of same length, returning borrow.2999*/3000private static int subN(int[] a, int[] b, int len) {3001long sum = 0;30023003while (--len >= 0) {3004sum = (a[len] & LONG_MASK) -3005(b[len] & LONG_MASK) + (sum >> 32);3006a[len] = (int)sum;3007}30083009return (int)(sum >> 32);3010}30113012/**3013* Multiply an array by one word k and add to result, return the carry3014*/3015static int mulAdd(int[] out, int[] in, int offset, int len, int k) {3016implMulAddCheck(out, in, offset, len, k);3017return implMulAdd(out, in, offset, len, k);3018}30193020/**3021* Parameters validation.3022*/3023private static void implMulAddCheck(int[] out, int[] in, int offset, int len, int k) {3024if (len > in.length) {3025throw new IllegalArgumentException("input length is out of bound: " + len + " > " + in.length);3026}3027if (offset < 0) {3028throw new IllegalArgumentException("input offset is invalid: " + offset);3029}3030if (offset > (out.length - 1)) {3031throw new IllegalArgumentException("input offset is out of bound: " + offset + " > " + (out.length - 1));3032}3033if (len > (out.length - offset)) {3034throw new IllegalArgumentException("input len is out of bound: " + len + " > " + (out.length - offset));3035}3036}30373038/**3039* Java Runtime may use intrinsic for this method.3040*/3041private static int implMulAdd(int[] out, int[] in, int offset, int len, int k) {3042long kLong = k & LONG_MASK;3043long carry = 0;30443045offset = out.length-offset - 1;3046for (int j=len-1; j >= 0; j--) {3047long product = (in[j] & LONG_MASK) * kLong +3048(out[offset] & LONG_MASK) + carry;3049out[offset--] = (int)product;3050carry = product >>> 32;3051}3052return (int)carry;3053}30543055/**3056* Add one word to the number a mlen words into a. Return the resulting3057* carry.3058*/3059static int addOne(int[] a, int offset, int mlen, int carry) {3060offset = a.length-1-mlen-offset;3061long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);30623063a[offset] = (int)t;3064if ((t >>> 32) == 0)3065return 0;3066while (--mlen >= 0) {3067if (--offset < 0) { // Carry out of number3068return 1;3069} else {3070a[offset]++;3071if (a[offset] != 0)3072return 0;3073}3074}3075return 1;3076}30773078/**3079* Returns a BigInteger whose value is (this ** exponent) mod (2**p)3080*/3081private BigInteger modPow2(BigInteger exponent, int p) {3082/*3083* Perform exponentiation using repeated squaring trick, chopping off3084* high order bits as indicated by modulus.3085*/3086BigInteger result = ONE;3087BigInteger baseToPow2 = this.mod2(p);3088int expOffset = 0;30893090int limit = exponent.bitLength();30913092if (this.testBit(0))3093limit = (p-1) < limit ? (p-1) : limit;30943095while (expOffset < limit) {3096if (exponent.testBit(expOffset))3097result = result.multiply(baseToPow2).mod2(p);3098expOffset++;3099if (expOffset < limit)3100baseToPow2 = baseToPow2.square().mod2(p);3101}31023103return result;3104}31053106/**3107* Returns a BigInteger whose value is this mod(2**p).3108* Assumes that this {@code BigInteger >= 0} and {@code p > 0}.3109*/3110private BigInteger mod2(int p) {3111if (bitLength() <= p)3112return this;31133114// Copy remaining ints of mag3115int numInts = (p + 31) >>> 5;3116int[] mag = new int[numInts];3117System.arraycopy(this.mag, (this.mag.length - numInts), mag, 0, numInts);31183119// Mask out any excess bits3120int excessBits = (numInts << 5) - p;3121mag[0] &= (1L << (32-excessBits)) - 1;31223123return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));3124}31253126/**3127* Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}.3128*3129* @param m the modulus.3130* @return {@code this}<sup>-1</sup> {@code mod m}.3131* @throws ArithmeticException {@code m} ≤ 0, or this BigInteger3132* has no multiplicative inverse mod m (that is, this BigInteger3133* is not <i>relatively prime</i> to m).3134*/3135public BigInteger modInverse(BigInteger m) {3136if (m.signum != 1)3137throw new ArithmeticException("BigInteger: modulus not positive");31383139if (m.equals(ONE))3140return ZERO;31413142// Calculate (this mod m)3143BigInteger modVal = this;3144if (signum < 0 || (this.compareMagnitude(m) >= 0))3145modVal = this.mod(m);31463147if (modVal.equals(ONE))3148return ONE;31493150MutableBigInteger a = new MutableBigInteger(modVal);3151MutableBigInteger b = new MutableBigInteger(m);31523153MutableBigInteger result = a.mutableModInverse(b);3154return result.toBigInteger(1);3155}31563157// Shift Operations31583159/**3160* Returns a BigInteger whose value is {@code (this << n)}.3161* The shift distance, {@code n}, may be negative, in which case3162* this method performs a right shift.3163* (Computes <tt>floor(this * 2<sup>n</sup>)</tt>.)3164*3165* @param n shift distance, in bits.3166* @return {@code this << n}3167* @see #shiftRight3168*/3169public BigInteger shiftLeft(int n) {3170if (signum == 0)3171return ZERO;3172if (n > 0) {3173return new BigInteger(shiftLeft(mag, n), signum);3174} else if (n == 0) {3175return this;3176} else {3177// Possible int overflow in (-n) is not a trouble,3178// because shiftRightImpl considers its argument unsigned3179return shiftRightImpl(-n);3180}3181}31823183/**3184* Returns a magnitude array whose value is {@code (mag << n)}.3185* The shift distance, {@code n}, is considered unnsigned.3186* (Computes <tt>this * 2<sup>n</sup></tt>.)3187*3188* @param mag magnitude, the most-significant int ({@code mag[0]}) must be non-zero.3189* @param n unsigned shift distance, in bits.3190* @return {@code mag << n}3191*/3192private static int[] shiftLeft(int[] mag, int n) {3193int nInts = n >>> 5;3194int nBits = n & 0x1f;3195int magLen = mag.length;3196int newMag[] = null;31973198if (nBits == 0) {3199newMag = new int[magLen + nInts];3200System.arraycopy(mag, 0, newMag, 0, magLen);3201} else {3202int i = 0;3203int nBits2 = 32 - nBits;3204int highBits = mag[0] >>> nBits2;3205if (highBits != 0) {3206newMag = new int[magLen + nInts + 1];3207newMag[i++] = highBits;3208} else {3209newMag = new int[magLen + nInts];3210}3211int j=0;3212while (j < magLen-1)3213newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2;3214newMag[i] = mag[j] << nBits;3215}3216return newMag;3217}32183219/**3220* Returns a BigInteger whose value is {@code (this >> n)}. Sign3221* extension is performed. The shift distance, {@code n}, may be3222* negative, in which case this method performs a left shift.3223* (Computes <tt>floor(this / 2<sup>n</sup>)</tt>.)3224*3225* @param n shift distance, in bits.3226* @return {@code this >> n}3227* @see #shiftLeft3228*/3229public BigInteger shiftRight(int n) {3230if (signum == 0)3231return ZERO;3232if (n > 0) {3233return shiftRightImpl(n);3234} else if (n == 0) {3235return this;3236} else {3237// Possible int overflow in {@code -n} is not a trouble,3238// because shiftLeft considers its argument unsigned3239return new BigInteger(shiftLeft(mag, -n), signum);3240}3241}32423243/**3244* Returns a BigInteger whose value is {@code (this >> n)}. The shift3245* distance, {@code n}, is considered unsigned.3246* (Computes <tt>floor(this * 2<sup>-n</sup>)</tt>.)3247*3248* @param n unsigned shift distance, in bits.3249* @return {@code this >> n}3250*/3251private BigInteger shiftRightImpl(int n) {3252int nInts = n >>> 5;3253int nBits = n & 0x1f;3254int magLen = mag.length;3255int newMag[] = null;32563257// Special case: entire contents shifted off the end3258if (nInts >= magLen)3259return (signum >= 0 ? ZERO : negConst[1]);32603261if (nBits == 0) {3262int newMagLen = magLen - nInts;3263newMag = Arrays.copyOf(mag, newMagLen);3264} else {3265int i = 0;3266int highBits = mag[0] >>> nBits;3267if (highBits != 0) {3268newMag = new int[magLen - nInts];3269newMag[i++] = highBits;3270} else {3271newMag = new int[magLen - nInts -1];3272}32733274int nBits2 = 32 - nBits;3275int j=0;3276while (j < magLen - nInts - 1)3277newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits);3278}32793280if (signum < 0) {3281// Find out whether any one-bits were shifted off the end.3282boolean onesLost = false;3283for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--)3284onesLost = (mag[i] != 0);3285if (!onesLost && nBits != 0)3286onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);32873288if (onesLost)3289newMag = javaIncrement(newMag);3290}32913292return new BigInteger(newMag, signum);3293}32943295int[] javaIncrement(int[] val) {3296int lastSum = 0;3297for (int i=val.length-1; i >= 0 && lastSum == 0; i--)3298lastSum = (val[i] += 1);3299if (lastSum == 0) {3300val = new int[val.length+1];3301val[0] = 1;3302}3303return val;3304}33053306// Bitwise Operations33073308/**3309* Returns a BigInteger whose value is {@code (this & val)}. (This3310* method returns a negative BigInteger if and only if this and val are3311* both negative.)3312*3313* @param val value to be AND'ed with this BigInteger.3314* @return {@code this & val}3315*/3316public BigInteger and(BigInteger val) {3317int[] result = new int[Math.max(intLength(), val.intLength())];3318for (int i=0; i < result.length; i++)3319result[i] = (getInt(result.length-i-1)3320& val.getInt(result.length-i-1));33213322return valueOf(result);3323}33243325/**3326* Returns a BigInteger whose value is {@code (this | val)}. (This method3327* returns a negative BigInteger if and only if either this or val is3328* negative.)3329*3330* @param val value to be OR'ed with this BigInteger.3331* @return {@code this | val}3332*/3333public BigInteger or(BigInteger val) {3334int[] result = new int[Math.max(intLength(), val.intLength())];3335for (int i=0; i < result.length; i++)3336result[i] = (getInt(result.length-i-1)3337| val.getInt(result.length-i-1));33383339return valueOf(result);3340}33413342/**3343* Returns a BigInteger whose value is {@code (this ^ val)}. (This method3344* returns a negative BigInteger if and only if exactly one of this and3345* val are negative.)3346*3347* @param val value to be XOR'ed with this BigInteger.3348* @return {@code this ^ val}3349*/3350public BigInteger xor(BigInteger val) {3351int[] result = new int[Math.max(intLength(), val.intLength())];3352for (int i=0; i < result.length; i++)3353result[i] = (getInt(result.length-i-1)3354^ val.getInt(result.length-i-1));33553356return valueOf(result);3357}33583359/**3360* Returns a BigInteger whose value is {@code (~this)}. (This method3361* returns a negative value if and only if this BigInteger is3362* non-negative.)3363*3364* @return {@code ~this}3365*/3366public BigInteger not() {3367int[] result = new int[intLength()];3368for (int i=0; i < result.length; i++)3369result[i] = ~getInt(result.length-i-1);33703371return valueOf(result);3372}33733374/**3375* Returns a BigInteger whose value is {@code (this & ~val)}. This3376* method, which is equivalent to {@code and(val.not())}, is provided as3377* a convenience for masking operations. (This method returns a negative3378* BigInteger if and only if {@code this} is negative and {@code val} is3379* positive.)3380*3381* @param val value to be complemented and AND'ed with this BigInteger.3382* @return {@code this & ~val}3383*/3384public BigInteger andNot(BigInteger val) {3385int[] result = new int[Math.max(intLength(), val.intLength())];3386for (int i=0; i < result.length; i++)3387result[i] = (getInt(result.length-i-1)3388& ~val.getInt(result.length-i-1));33893390return valueOf(result);3391}339233933394// Single Bit Operations33953396/**3397* Returns {@code true} if and only if the designated bit is set.3398* (Computes {@code ((this & (1<<n)) != 0)}.)3399*3400* @param n index of bit to test.3401* @return {@code true} if and only if the designated bit is set.3402* @throws ArithmeticException {@code n} is negative.3403*/3404public boolean testBit(int n) {3405if (n < 0)3406throw new ArithmeticException("Negative bit address");34073408return (getInt(n >>> 5) & (1 << (n & 31))) != 0;3409}34103411/**3412* Returns a BigInteger whose value is equivalent to this BigInteger3413* with the designated bit set. (Computes {@code (this | (1<<n))}.)3414*3415* @param n index of bit to set.3416* @return {@code this | (1<<n)}3417* @throws ArithmeticException {@code n} is negative.3418*/3419public BigInteger setBit(int n) {3420if (n < 0)3421throw new ArithmeticException("Negative bit address");34223423int intNum = n >>> 5;3424int[] result = new int[Math.max(intLength(), intNum+2)];34253426for (int i=0; i < result.length; i++)3427result[result.length-i-1] = getInt(i);34283429result[result.length-intNum-1] |= (1 << (n & 31));34303431return valueOf(result);3432}34333434/**3435* Returns a BigInteger whose value is equivalent to this BigInteger3436* with the designated bit cleared.3437* (Computes {@code (this & ~(1<<n))}.)3438*3439* @param n index of bit to clear.3440* @return {@code this & ~(1<<n)}3441* @throws ArithmeticException {@code n} is negative.3442*/3443public BigInteger clearBit(int n) {3444if (n < 0)3445throw new ArithmeticException("Negative bit address");34463447int intNum = n >>> 5;3448int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];34493450for (int i=0; i < result.length; i++)3451result[result.length-i-1] = getInt(i);34523453result[result.length-intNum-1] &= ~(1 << (n & 31));34543455return valueOf(result);3456}34573458/**3459* Returns a BigInteger whose value is equivalent to this BigInteger3460* with the designated bit flipped.3461* (Computes {@code (this ^ (1<<n))}.)3462*3463* @param n index of bit to flip.3464* @return {@code this ^ (1<<n)}3465* @throws ArithmeticException {@code n} is negative.3466*/3467public BigInteger flipBit(int n) {3468if (n < 0)3469throw new ArithmeticException("Negative bit address");34703471int intNum = n >>> 5;3472int[] result = new int[Math.max(intLength(), intNum+2)];34733474for (int i=0; i < result.length; i++)3475result[result.length-i-1] = getInt(i);34763477result[result.length-intNum-1] ^= (1 << (n & 31));34783479return valueOf(result);3480}34813482/**3483* Returns the index of the rightmost (lowest-order) one bit in this3484* BigInteger (the number of zero bits to the right of the rightmost3485* one bit). Returns -1 if this BigInteger contains no one bits.3486* (Computes {@code (this == 0? -1 : log2(this & -this))}.)3487*3488* @return index of the rightmost one bit in this BigInteger.3489*/3490public int getLowestSetBit() {3491@SuppressWarnings("deprecation") int lsb = lowestSetBit - 2;3492if (lsb == -2) { // lowestSetBit not initialized yet3493lsb = 0;3494if (signum == 0) {3495lsb -= 1;3496} else {3497// Search for lowest order nonzero int3498int i,b;3499for (i=0; (b = getInt(i)) == 0; i++)3500;3501lsb += (i << 5) + Integer.numberOfTrailingZeros(b);3502}3503lowestSetBit = lsb + 2;3504}3505return lsb;3506}350735083509// Miscellaneous Bit Operations35103511/**3512* Returns the number of bits in the minimal two's-complement3513* representation of this BigInteger, <i>excluding</i> a sign bit.3514* For positive BigIntegers, this is equivalent to the number of bits in3515* the ordinary binary representation. (Computes3516* {@code (ceil(log2(this < 0 ? -this : this+1)))}.)3517*3518* @return number of bits in the minimal two's-complement3519* representation of this BigInteger, <i>excluding</i> a sign bit.3520*/3521public int bitLength() {3522@SuppressWarnings("deprecation") int n = bitLength - 1;3523if (n == -1) { // bitLength not initialized yet3524int[] m = mag;3525int len = m.length;3526if (len == 0) {3527n = 0; // offset by one to initialize3528} else {3529// Calculate the bit length of the magnitude3530int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);3531if (signum < 0) {3532// Check if magnitude is a power of two3533boolean pow2 = (Integer.bitCount(mag[0]) == 1);3534for (int i=1; i< len && pow2; i++)3535pow2 = (mag[i] == 0);35363537n = (pow2 ? magBitLength - 1 : magBitLength);3538} else {3539n = magBitLength;3540}3541}3542bitLength = n + 1;3543}3544return n;3545}35463547/**3548* Returns the number of bits in the two's complement representation3549* of this BigInteger that differ from its sign bit. This method is3550* useful when implementing bit-vector style sets atop BigIntegers.3551*3552* @return number of bits in the two's complement representation3553* of this BigInteger that differ from its sign bit.3554*/3555public int bitCount() {3556@SuppressWarnings("deprecation") int bc = bitCount - 1;3557if (bc == -1) { // bitCount not initialized yet3558bc = 0; // offset by one to initialize3559// Count the bits in the magnitude3560for (int i=0; i < mag.length; i++)3561bc += Integer.bitCount(mag[i]);3562if (signum < 0) {3563// Count the trailing zeros in the magnitude3564int magTrailingZeroCount = 0, j;3565for (j=mag.length-1; mag[j] == 0; j--)3566magTrailingZeroCount += 32;3567magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);3568bc += magTrailingZeroCount - 1;3569}3570bitCount = bc + 1;3571}3572return bc;3573}35743575// Primality Testing35763577/**3578* Returns {@code true} if this BigInteger is probably prime,3579* {@code false} if it's definitely composite. If3580* {@code certainty} is ≤ 0, {@code true} is3581* returned.3582*3583* @param certainty a measure of the uncertainty that the caller is3584* willing to tolerate: if the call returns {@code true}3585* the probability that this BigInteger is prime exceeds3586* (1 - 1/2<sup>{@code certainty}</sup>). The execution time of3587* this method is proportional to the value of this parameter.3588* @return {@code true} if this BigInteger is probably prime,3589* {@code false} if it's definitely composite.3590*/3591public boolean isProbablePrime(int certainty) {3592if (certainty <= 0)3593return true;3594BigInteger w = this.abs();3595if (w.equals(TWO))3596return true;3597if (!w.testBit(0) || w.equals(ONE))3598return false;35993600return w.primeToCertainty(certainty, null);3601}36023603// Comparison Operations36043605/**3606* Compares this BigInteger with the specified BigInteger. This3607* method is provided in preference to individual methods for each3608* of the six boolean comparison operators ({@literal <}, ==,3609* {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested3610* idiom for performing these comparisons is: {@code3611* (x.compareTo(y)} <<i>op</i>> {@code 0)}, where3612* <<i>op</i>> is one of the six comparison operators.3613*3614* @param val BigInteger to which this BigInteger is to be compared.3615* @return -1, 0 or 1 as this BigInteger is numerically less than, equal3616* to, or greater than {@code val}.3617*/3618public int compareTo(BigInteger val) {3619if (signum == val.signum) {3620switch (signum) {3621case 1:3622return compareMagnitude(val);3623case -1:3624return val.compareMagnitude(this);3625default:3626return 0;3627}3628}3629return signum > val.signum ? 1 : -1;3630}36313632/**3633* Compares the magnitude array of this BigInteger with the specified3634* BigInteger's. This is the version of compareTo ignoring sign.3635*3636* @param val BigInteger whose magnitude array to be compared.3637* @return -1, 0 or 1 as this magnitude array is less than, equal to or3638* greater than the magnitude aray for the specified BigInteger's.3639*/3640final int compareMagnitude(BigInteger val) {3641int[] m1 = mag;3642int len1 = m1.length;3643int[] m2 = val.mag;3644int len2 = m2.length;3645if (len1 < len2)3646return -1;3647if (len1 > len2)3648return 1;3649for (int i = 0; i < len1; i++) {3650int a = m1[i];3651int b = m2[i];3652if (a != b)3653return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;3654}3655return 0;3656}36573658/**3659* Version of compareMagnitude that compares magnitude with long value.3660* val can't be Long.MIN_VALUE.3661*/3662final int compareMagnitude(long val) {3663assert val != Long.MIN_VALUE;3664int[] m1 = mag;3665int len = m1.length;3666if (len > 2) {3667return 1;3668}3669if (val < 0) {3670val = -val;3671}3672int highWord = (int)(val >>> 32);3673if (highWord == 0) {3674if (len < 1)3675return -1;3676if (len > 1)3677return 1;3678int a = m1[0];3679int b = (int)val;3680if (a != b) {3681return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;3682}3683return 0;3684} else {3685if (len < 2)3686return -1;3687int a = m1[0];3688int b = highWord;3689if (a != b) {3690return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;3691}3692a = m1[1];3693b = (int)val;3694if (a != b) {3695return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;3696}3697return 0;3698}3699}37003701/**3702* Compares this BigInteger with the specified Object for equality.3703*3704* @param x Object to which this BigInteger is to be compared.3705* @return {@code true} if and only if the specified Object is a3706* BigInteger whose value is numerically equal to this BigInteger.3707*/3708public boolean equals(Object x) {3709// This test is just an optimization, which may or may not help3710if (x == this)3711return true;37123713if (!(x instanceof BigInteger))3714return false;37153716BigInteger xInt = (BigInteger) x;3717if (xInt.signum != signum)3718return false;37193720int[] m = mag;3721int len = m.length;3722int[] xm = xInt.mag;3723if (len != xm.length)3724return false;37253726for (int i = 0; i < len; i++)3727if (xm[i] != m[i])3728return false;37293730return true;3731}37323733/**3734* Returns the minimum of this BigInteger and {@code val}.3735*3736* @param val value with which the minimum is to be computed.3737* @return the BigInteger whose value is the lesser of this BigInteger and3738* {@code val}. If they are equal, either may be returned.3739*/3740public BigInteger min(BigInteger val) {3741return (compareTo(val) < 0 ? this : val);3742}37433744/**3745* Returns the maximum of this BigInteger and {@code val}.3746*3747* @param val value with which the maximum is to be computed.3748* @return the BigInteger whose value is the greater of this and3749* {@code val}. If they are equal, either may be returned.3750*/3751public BigInteger max(BigInteger val) {3752return (compareTo(val) > 0 ? this : val);3753}375437553756// Hash Function37573758/**3759* Returns the hash code for this BigInteger.3760*3761* @return hash code for this BigInteger.3762*/3763public int hashCode() {3764int hashCode = 0;37653766for (int i=0; i < mag.length; i++)3767hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));37683769return hashCode * signum;3770}37713772/**3773* Returns the String representation of this BigInteger in the3774* given radix. If the radix is outside the range from {@link3775* Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive,3776* it will default to 10 (as is the case for3777* {@code Integer.toString}). The digit-to-character mapping3778* provided by {@code Character.forDigit} is used, and a minus3779* sign is prepended if appropriate. (This representation is3780* compatible with the {@link #BigInteger(String, int) (String,3781* int)} constructor.)3782*3783* @param radix radix of the String representation.3784* @return String representation of this BigInteger in the given radix.3785* @see Integer#toString3786* @see Character#forDigit3787* @see #BigInteger(java.lang.String, int)3788*/3789public String toString(int radix) {3790if (signum == 0)3791return "0";3792if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)3793radix = 10;37943795// If it's small enough, use smallToString.3796if (mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD)3797return smallToString(radix);37983799// Otherwise use recursive toString, which requires positive arguments.3800// The results will be concatenated into this StringBuilder3801StringBuilder sb = new StringBuilder();3802if (signum < 0) {3803toString(this.negate(), sb, radix, 0);3804sb.insert(0, '-');3805}3806else3807toString(this, sb, radix, 0);38083809return sb.toString();3810}38113812/** This method is used to perform toString when arguments are small. */3813private String smallToString(int radix) {3814if (signum == 0) {3815return "0";3816}38173818// Compute upper bound on number of digit groups and allocate space3819int maxNumDigitGroups = (4*mag.length + 6)/7;3820String digitGroup[] = new String[maxNumDigitGroups];38213822// Translate number to string, a digit group at a time3823BigInteger tmp = this.abs();3824int numGroups = 0;3825while (tmp.signum != 0) {3826BigInteger d = longRadix[radix];38273828MutableBigInteger q = new MutableBigInteger(),3829a = new MutableBigInteger(tmp.mag),3830b = new MutableBigInteger(d.mag);3831MutableBigInteger r = a.divide(b, q);3832BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);3833BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);38343835digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);3836tmp = q2;3837}38383839// Put sign (if any) and first digit group into result buffer3840StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1);3841if (signum < 0) {3842buf.append('-');3843}3844buf.append(digitGroup[numGroups-1]);38453846// Append remaining digit groups padded with leading zeros3847for (int i=numGroups-2; i >= 0; i--) {3848// Prepend (any) leading zeros for this digit group3849int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();3850if (numLeadingZeros != 0) {3851buf.append(zeros[numLeadingZeros]);3852}3853buf.append(digitGroup[i]);3854}3855return buf.toString();3856}38573858/**3859* Converts the specified BigInteger to a string and appends to3860* {@code sb}. This implements the recursive Schoenhage algorithm3861* for base conversions.3862* <p/>3863* See Knuth, Donald, _The Art of Computer Programming_, Vol. 2,3864* Answers to Exercises (4.4) Question 14.3865*3866* @param u The number to convert to a string.3867* @param sb The StringBuilder that will be appended to in place.3868* @param radix The base to convert to.3869* @param digits The minimum number of digits to pad to.3870*/3871private static void toString(BigInteger u, StringBuilder sb, int radix,3872int digits) {3873/* If we're smaller than a certain threshold, use the smallToString3874method, padding with leading zeroes when necessary. */3875if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {3876String s = u.smallToString(radix);38773878// Pad with internal zeros if necessary.3879// Don't pad if we're at the beginning of the string.3880if ((s.length() < digits) && (sb.length() > 0)) {3881for (int i=s.length(); i < digits; i++) { // May be a faster way to3882sb.append('0'); // do this?3883}3884}38853886sb.append(s);3887return;3888}38893890int b, n;3891b = u.bitLength();38923893// Calculate a value for n in the equation radix^(2^n) = u3894// and subtract 1 from that value. This is used to find the3895// cache index that contains the best value to divide u.3896n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0);3897BigInteger v = getRadixConversionCache(radix, n);3898BigInteger[] results;3899results = u.divideAndRemainder(v);39003901int expectedDigits = 1 << n;39023903// Now recursively build the two halves of each number.3904toString(results[0], sb, radix, digits-expectedDigits);3905toString(results[1], sb, radix, expectedDigits);3906}39073908/**3909* Returns the value radix^(2^exponent) from the cache.3910* If this value doesn't already exist in the cache, it is added.3911* <p/>3912* This could be changed to a more complicated caching method using3913* {@code Future}.3914*/3915private static BigInteger getRadixConversionCache(int radix, int exponent) {3916BigInteger[] cacheLine = powerCache[radix]; // volatile read3917if (exponent < cacheLine.length) {3918return cacheLine[exponent];3919}39203921int oldLength = cacheLine.length;3922cacheLine = Arrays.copyOf(cacheLine, exponent + 1);3923for (int i = oldLength; i <= exponent; i++) {3924cacheLine[i] = cacheLine[i - 1].pow(2);3925}39263927BigInteger[][] pc = powerCache; // volatile read again3928if (exponent >= pc[radix].length) {3929pc = pc.clone();3930pc[radix] = cacheLine;3931powerCache = pc; // volatile write, publish3932}3933return cacheLine[exponent];3934}39353936/* zero[i] is a string of i consecutive zeros. */3937private static String zeros[] = new String[64];3938static {3939zeros[63] =3940"000000000000000000000000000000000000000000000000000000000000000";3941for (int i=0; i < 63; i++)3942zeros[i] = zeros[63].substring(0, i);3943}39443945/**3946* Returns the decimal String representation of this BigInteger.3947* The digit-to-character mapping provided by3948* {@code Character.forDigit} is used, and a minus sign is3949* prepended if appropriate. (This representation is compatible3950* with the {@link #BigInteger(String) (String)} constructor, and3951* allows for String concatenation with Java's + operator.)3952*3953* @return decimal String representation of this BigInteger.3954* @see Character#forDigit3955* @see #BigInteger(java.lang.String)3956*/3957public String toString() {3958return toString(10);3959}39603961/**3962* Returns a byte array containing the two's-complement3963* representation of this BigInteger. The byte array will be in3964* <i>big-endian</i> byte-order: the most significant byte is in3965* the zeroth element. The array will contain the minimum number3966* of bytes required to represent this BigInteger, including at3967* least one sign bit, which is {@code (ceil((this.bitLength() +3968* 1)/8))}. (This representation is compatible with the3969* {@link #BigInteger(byte[]) (byte[])} constructor.)3970*3971* @return a byte array containing the two's-complement representation of3972* this BigInteger.3973* @see #BigInteger(byte[])3974*/3975public byte[] toByteArray() {3976int byteLen = bitLength()/8 + 1;3977byte[] byteArray = new byte[byteLen];39783979for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {3980if (bytesCopied == 4) {3981nextInt = getInt(intIndex++);3982bytesCopied = 1;3983} else {3984nextInt >>>= 8;3985bytesCopied++;3986}3987byteArray[i] = (byte)nextInt;3988}3989return byteArray;3990}39913992/**3993* Converts this BigInteger to an {@code int}. This3994* conversion is analogous to a3995* <i>narrowing primitive conversion</i> from {@code long} to3996* {@code int} as defined in section 5.1.3 of3997* <cite>The Java™ Language Specification</cite>:3998* if this BigInteger is too big to fit in an3999* {@code int}, only the low-order 32 bits are returned.4000* Note that this conversion can lose information about the4001* overall magnitude of the BigInteger value as well as return a4002* result with the opposite sign.4003*4004* @return this BigInteger converted to an {@code int}.4005* @see #intValueExact()4006*/4007public int intValue() {4008int result = 0;4009result = getInt(0);4010return result;4011}40124013/**4014* Converts this BigInteger to a {@code long}. This4015* conversion is analogous to a4016* <i>narrowing primitive conversion</i> from {@code long} to4017* {@code int} as defined in section 5.1.3 of4018* <cite>The Java™ Language Specification</cite>:4019* if this BigInteger is too big to fit in a4020* {@code long}, only the low-order 64 bits are returned.4021* Note that this conversion can lose information about the4022* overall magnitude of the BigInteger value as well as return a4023* result with the opposite sign.4024*4025* @return this BigInteger converted to a {@code long}.4026* @see #longValueExact()4027*/4028public long longValue() {4029long result = 0;40304031for (int i=1; i >= 0; i--)4032result = (result << 32) + (getInt(i) & LONG_MASK);4033return result;4034}40354036/**4037* Converts this BigInteger to a {@code float}. This4038* conversion is similar to the4039* <i>narrowing primitive conversion</i> from {@code double} to4040* {@code float} as defined in section 5.1.3 of4041* <cite>The Java™ Language Specification</cite>:4042* if this BigInteger has too great a magnitude4043* to represent as a {@code float}, it will be converted to4044* {@link Float#NEGATIVE_INFINITY} or {@link4045* Float#POSITIVE_INFINITY} as appropriate. Note that even when4046* the return value is finite, this conversion can lose4047* information about the precision of the BigInteger value.4048*4049* @return this BigInteger converted to a {@code float}.4050*/4051public float floatValue() {4052if (signum == 0) {4053return 0.0f;4054}40554056int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;40574058// exponent == floor(log2(abs(this)))4059if (exponent < Long.SIZE - 1) {4060return longValue();4061} else if (exponent > Float.MAX_EXPONENT) {4062return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;4063}40644065/*4066* We need the top SIGNIFICAND_WIDTH bits, including the "implicit"4067* one bit. To make rounding easier, we pick out the top4068* SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or4069* down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 14070* bits, and signifFloor the top SIGNIFICAND_WIDTH.4071*4072* It helps to consider the real number signif = abs(this) *4073* 2^(SIGNIFICAND_WIDTH - 1 - exponent).4074*/4075int shift = exponent - FloatConsts.SIGNIFICAND_WIDTH;40764077int twiceSignifFloor;4078// twiceSignifFloor will be == abs().shiftRight(shift).intValue()4079// We do the shift into an int directly to improve performance.40804081int nBits = shift & 0x1f;4082int nBits2 = 32 - nBits;40834084if (nBits == 0) {4085twiceSignifFloor = mag[0];4086} else {4087twiceSignifFloor = mag[0] >>> nBits;4088if (twiceSignifFloor == 0) {4089twiceSignifFloor = (mag[0] << nBits2) | (mag[1] >>> nBits);4090}4091}40924093int signifFloor = twiceSignifFloor >> 1;4094signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit40954096/*4097* We round up if either the fractional part of signif is strictly4098* greater than 0.5 (which is true if the 0.5 bit is set and any lower4099* bit is set), or if the fractional part of signif is >= 0.5 and4100* signifFloor is odd (which is true if both the 0.5 bit and the 1 bit4101* are set). This is equivalent to the desired HALF_EVEN rounding.4102*/4103boolean increment = (twiceSignifFloor & 1) != 04104&& ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);4105int signifRounded = increment ? signifFloor + 1 : signifFloor;4106int bits = ((exponent + FloatConsts.EXP_BIAS))4107<< (FloatConsts.SIGNIFICAND_WIDTH - 1);4108bits += signifRounded;4109/*4110* If signifRounded == 2^24, we'd need to set all of the significand4111* bits to zero and add 1 to the exponent. This is exactly the behavior4112* we get from just adding signifRounded to bits directly. If the4113* exponent is Float.MAX_EXPONENT, we round up (correctly) to4114* Float.POSITIVE_INFINITY.4115*/4116bits |= signum & FloatConsts.SIGN_BIT_MASK;4117return Float.intBitsToFloat(bits);4118}41194120/**4121* Converts this BigInteger to a {@code double}. This4122* conversion is similar to the4123* <i>narrowing primitive conversion</i> from {@code double} to4124* {@code float} as defined in section 5.1.3 of4125* <cite>The Java™ Language Specification</cite>:4126* if this BigInteger has too great a magnitude4127* to represent as a {@code double}, it will be converted to4128* {@link Double#NEGATIVE_INFINITY} or {@link4129* Double#POSITIVE_INFINITY} as appropriate. Note that even when4130* the return value is finite, this conversion can lose4131* information about the precision of the BigInteger value.4132*4133* @return this BigInteger converted to a {@code double}.4134*/4135public double doubleValue() {4136if (signum == 0) {4137return 0.0;4138}41394140int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;41414142// exponent == floor(log2(abs(this))Double)4143if (exponent < Long.SIZE - 1) {4144return longValue();4145} else if (exponent > Double.MAX_EXPONENT) {4146return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;4147}41484149/*4150* We need the top SIGNIFICAND_WIDTH bits, including the "implicit"4151* one bit. To make rounding easier, we pick out the top4152* SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or4153* down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 14154* bits, and signifFloor the top SIGNIFICAND_WIDTH.4155*4156* It helps to consider the real number signif = abs(this) *4157* 2^(SIGNIFICAND_WIDTH - 1 - exponent).4158*/4159int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH;41604161long twiceSignifFloor;4162// twiceSignifFloor will be == abs().shiftRight(shift).longValue()4163// We do the shift into a long directly to improve performance.41644165int nBits = shift & 0x1f;4166int nBits2 = 32 - nBits;41674168int highBits;4169int lowBits;4170if (nBits == 0) {4171highBits = mag[0];4172lowBits = mag[1];4173} else {4174highBits = mag[0] >>> nBits;4175lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits);4176if (highBits == 0) {4177highBits = lowBits;4178lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits);4179}4180}41814182twiceSignifFloor = ((highBits & LONG_MASK) << 32)4183| (lowBits & LONG_MASK);41844185long signifFloor = twiceSignifFloor >> 1;4186signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit41874188/*4189* We round up if either the fractional part of signif is strictly4190* greater than 0.5 (which is true if the 0.5 bit is set and any lower4191* bit is set), or if the fractional part of signif is >= 0.5 and4192* signifFloor is odd (which is true if both the 0.5 bit and the 1 bit4193* are set). This is equivalent to the desired HALF_EVEN rounding.4194*/4195boolean increment = (twiceSignifFloor & 1) != 04196&& ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);4197long signifRounded = increment ? signifFloor + 1 : signifFloor;4198long bits = (long) ((exponent + DoubleConsts.EXP_BIAS))4199<< (DoubleConsts.SIGNIFICAND_WIDTH - 1);4200bits += signifRounded;4201/*4202* If signifRounded == 2^53, we'd need to set all of the significand4203* bits to zero and add 1 to the exponent. This is exactly the behavior4204* we get from just adding signifRounded to bits directly. If the4205* exponent is Double.MAX_EXPONENT, we round up (correctly) to4206* Double.POSITIVE_INFINITY.4207*/4208bits |= signum & DoubleConsts.SIGN_BIT_MASK;4209return Double.longBitsToDouble(bits);4210}42114212/**4213* Returns a copy of the input array stripped of any leading zero bytes.4214*/4215private static int[] stripLeadingZeroInts(int val[]) {4216int vlen = val.length;4217int keep;42184219// Find first nonzero byte4220for (keep = 0; keep < vlen && val[keep] == 0; keep++)4221;4222return java.util.Arrays.copyOfRange(val, keep, vlen);4223}42244225/**4226* Returns the input array stripped of any leading zero bytes.4227* Since the source is trusted the copying may be skipped.4228*/4229private static int[] trustedStripLeadingZeroInts(int val[]) {4230int vlen = val.length;4231int keep;42324233// Find first nonzero byte4234for (keep = 0; keep < vlen && val[keep] == 0; keep++)4235;4236return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen);4237}42384239/**4240* Returns a copy of the input array stripped of any leading zero bytes.4241*/4242private static int[] stripLeadingZeroBytes(byte a[]) {4243int byteLength = a.length;4244int keep;42454246// Find first nonzero byte4247for (keep = 0; keep < byteLength && a[keep] == 0; keep++)4248;42494250// Allocate new array and copy relevant part of input array4251int intLength = ((byteLength - keep) + 3) >>> 2;4252int[] result = new int[intLength];4253int b = byteLength - 1;4254for (int i = intLength-1; i >= 0; i--) {4255result[i] = a[b--] & 0xff;4256int bytesRemaining = b - keep + 1;4257int bytesToTransfer = Math.min(3, bytesRemaining);4258for (int j=8; j <= (bytesToTransfer << 3); j += 8)4259result[i] |= ((a[b--] & 0xff) << j);4260}4261return result;4262}42634264/**4265* Takes an array a representing a negative 2's-complement number and4266* returns the minimal (no leading zero bytes) unsigned whose value is -a.4267*/4268private static int[] makePositive(byte a[]) {4269int keep, k;4270int byteLength = a.length;42714272// Find first non-sign (0xff) byte of input4273for (keep=0; keep < byteLength && a[keep] == -1; keep++)4274;427542764277/* Allocate output array. If all non-sign bytes are 0x00, we must4278* allocate space for one extra output byte. */4279for (k=keep; k < byteLength && a[k] == 0; k++)4280;42814282int extraByte = (k == byteLength) ? 1 : 0;4283int intLength = ((byteLength - keep + extraByte) + 3) >>> 2;4284int result[] = new int[intLength];42854286/* Copy one's complement of input into output, leaving extra4287* byte (if it exists) == 0x00 */4288int b = byteLength - 1;4289for (int i = intLength-1; i >= 0; i--) {4290result[i] = a[b--] & 0xff;4291int numBytesToTransfer = Math.min(3, b-keep+1);4292if (numBytesToTransfer < 0)4293numBytesToTransfer = 0;4294for (int j=8; j <= 8*numBytesToTransfer; j += 8)4295result[i] |= ((a[b--] & 0xff) << j);42964297// Mask indicates which bits must be complemented4298int mask = -1 >>> (8*(3-numBytesToTransfer));4299result[i] = ~result[i] & mask;4300}43014302// Add one to one's complement to generate two's complement4303for (int i=result.length-1; i >= 0; i--) {4304result[i] = (int)((result[i] & LONG_MASK) + 1);4305if (result[i] != 0)4306break;4307}43084309return result;4310}43114312/**4313* Takes an array a representing a negative 2's-complement number and4314* returns the minimal (no leading zero ints) unsigned whose value is -a.4315*/4316private static int[] makePositive(int a[]) {4317int keep, j;43184319// Find first non-sign (0xffffffff) int of input4320for (keep=0; keep < a.length && a[keep] == -1; keep++)4321;43224323/* Allocate output array. If all non-sign ints are 0x00, we must4324* allocate space for one extra output int. */4325for (j=keep; j < a.length && a[j] == 0; j++)4326;4327int extraInt = (j == a.length ? 1 : 0);4328int result[] = new int[a.length - keep + extraInt];43294330/* Copy one's complement of input into output, leaving extra4331* int (if it exists) == 0x00 */4332for (int i = keep; i < a.length; i++)4333result[i - keep + extraInt] = ~a[i];43344335// Add one to one's complement to generate two's complement4336for (int i=result.length-1; ++result[i] == 0; i--)4337;43384339return result;4340}43414342/*4343* The following two arrays are used for fast String conversions. Both4344* are indexed by radix. The first is the number of digits of the given4345* radix that can fit in a Java long without "going negative", i.e., the4346* highest integer n such that radix**n < 2**63. The second is the4347* "long radix" that tears each number into "long digits", each of which4348* consists of the number of digits in the corresponding element in4349* digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have4350* nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not4351* used.4352*/4353private static int digitsPerLong[] = {0, 0,435462, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,435514, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};43564357private static BigInteger longRadix[] = {null, null,4358valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),4359valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),4360valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),4361valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),4362valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),4363valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),4364valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),4365valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),4366valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),4367valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),4368valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),4369valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),4370valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),4371valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),4372valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),4373valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),4374valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),4375valueOf(0x41c21cb8e1000000L)};43764377/*4378* These two arrays are the integer analogue of above.4379*/4380private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11,438111, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,43826, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};43834384private static int intRadix[] = {0, 0,43850x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,43860x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,43870x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000,43880x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,43890x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40,43900x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,43910x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa4004392};43934394/**4395* These routines provide access to the two's complement representation4396* of BigIntegers.4397*/43984399/**4400* Returns the length of the two's complement representation in ints,4401* including space for at least one sign bit.4402*/4403private int intLength() {4404return (bitLength() >>> 5) + 1;4405}44064407/* Returns sign bit */4408private int signBit() {4409return signum < 0 ? 1 : 0;4410}44114412/* Returns an int of sign bits */4413private int signInt() {4414return signum < 0 ? -1 : 0;4415}44164417/**4418* Returns the specified int of the little-endian two's complement4419* representation (int 0 is the least significant). The int number can4420* be arbitrarily high (values are logically preceded by infinitely many4421* sign ints).4422*/4423private int getInt(int n) {4424if (n < 0)4425return 0;4426if (n >= mag.length)4427return signInt();44284429int magInt = mag[mag.length-n-1];44304431return (signum >= 0 ? magInt :4432(n <= firstNonzeroIntNum() ? -magInt : ~magInt));4433}44344435/**4436* Returns the index of the int that contains the first nonzero int in the4437* little-endian binary representation of the magnitude (int 0 is the4438* least significant). If the magnitude is zero, return value is undefined.4439*/4440private int firstNonzeroIntNum() {4441int fn = firstNonzeroIntNum - 2;4442if (fn == -2) { // firstNonzeroIntNum not initialized yet4443fn = 0;44444445// Search for the first nonzero int4446int i;4447int mlen = mag.length;4448for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)4449;4450fn = mlen - i - 1;4451firstNonzeroIntNum = fn + 2; // offset by two to initialize4452}4453return fn;4454}44554456/** use serialVersionUID from JDK 1.1. for interoperability */4457private static final long serialVersionUID = -8287574255936472291L;44584459/**4460* Serializable fields for BigInteger.4461*4462* @serialField signum int4463* signum of this BigInteger.4464* @serialField magnitude int[]4465* magnitude array of this BigInteger.4466* @serialField bitCount int4467* number of bits in this BigInteger4468* @serialField bitLength int4469* the number of bits in the minimal two's-complement4470* representation of this BigInteger4471* @serialField lowestSetBit int4472* lowest set bit in the twos complement representation4473*/4474private static final ObjectStreamField[] serialPersistentFields = {4475new ObjectStreamField("signum", Integer.TYPE),4476new ObjectStreamField("magnitude", byte[].class),4477new ObjectStreamField("bitCount", Integer.TYPE),4478new ObjectStreamField("bitLength", Integer.TYPE),4479new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),4480new ObjectStreamField("lowestSetBit", Integer.TYPE)4481};44824483/**4484* Reconstitute the {@code BigInteger} instance from a stream (that is,4485* deserialize it). The magnitude is read in as an array of bytes4486* for historical reasons, but it is converted to an array of ints4487* and the byte array is discarded.4488* Note:4489* The current convention is to initialize the cache fields, bitCount,4490* bitLength and lowestSetBit, to 0 rather than some other marker value.4491* Therefore, no explicit action to set these fields needs to be taken in4492* readObject because those fields already have a 0 value be default since4493* defaultReadObject is not being used.4494*/4495private void readObject(java.io.ObjectInputStream s)4496throws java.io.IOException, ClassNotFoundException {4497/*4498* In order to maintain compatibility with previous serialized forms,4499* the magnitude of a BigInteger is serialized as an array of bytes.4500* The magnitude field is used as a temporary store for the byte array4501* that is deserialized. The cached computation fields should be4502* transient but are serialized for compatibility reasons.4503*/45044505// prepare to read the alternate persistent fields4506ObjectInputStream.GetField fields = s.readFields();45074508// Read the alternate persistent fields that we care about4509int sign = fields.get("signum", -2);4510byte[] magnitude = (byte[])fields.get("magnitude", null);45114512// Validate signum4513if (sign < -1 || sign > 1) {4514String message = "BigInteger: Invalid signum value";4515if (fields.defaulted("signum"))4516message = "BigInteger: Signum not present in stream";4517throw new java.io.StreamCorruptedException(message);4518}4519int[] mag = stripLeadingZeroBytes(magnitude);4520if ((mag.length == 0) != (sign == 0)) {4521String message = "BigInteger: signum-magnitude mismatch";4522if (fields.defaulted("magnitude"))4523message = "BigInteger: Magnitude not present in stream";4524throw new java.io.StreamCorruptedException(message);4525}45264527// Commit final fields via Unsafe4528UnsafeHolder.putSign(this, sign);45294530// Calculate mag field from magnitude and discard magnitude4531UnsafeHolder.putMag(this, mag);4532if (mag.length >= MAX_MAG_LENGTH) {4533try {4534checkRange();4535} catch (ArithmeticException e) {4536throw new java.io.StreamCorruptedException("BigInteger: Out of the supported range");4537}4538}4539}45404541// Support for resetting final fields while deserializing4542private static class UnsafeHolder {4543private static final sun.misc.Unsafe unsafe;4544private static final long signumOffset;4545private static final long magOffset;4546static {4547try {4548unsafe = sun.misc.Unsafe.getUnsafe();4549signumOffset = unsafe.objectFieldOffset4550(BigInteger.class.getDeclaredField("signum"));4551magOffset = unsafe.objectFieldOffset4552(BigInteger.class.getDeclaredField("mag"));4553} catch (Exception ex) {4554throw new ExceptionInInitializerError(ex);4555}4556}45574558static void putSign(BigInteger bi, int sign) {4559unsafe.putIntVolatile(bi, signumOffset, sign);4560}45614562static void putMag(BigInteger bi, int[] magnitude) {4563unsafe.putObjectVolatile(bi, magOffset, magnitude);4564}4565}45664567/**4568* Save the {@code BigInteger} instance to a stream.4569* The magnitude of a BigInteger is serialized as a byte array for4570* historical reasons.4571*4572* @serialData two necessary fields are written as well as obsolete4573* fields for compatibility with older versions.4574*/4575private void writeObject(ObjectOutputStream s) throws IOException {4576// set the values of the Serializable fields4577ObjectOutputStream.PutField fields = s.putFields();4578fields.put("signum", signum);4579fields.put("magnitude", magSerializedForm());4580// The values written for cached fields are compatible with older4581// versions, but are ignored in readObject so don't otherwise matter.4582fields.put("bitCount", -1);4583fields.put("bitLength", -1);4584fields.put("lowestSetBit", -2);4585fields.put("firstNonzeroByteNum", -2);45864587// save them4588s.writeFields();4589}45904591/**4592* Returns the mag array as an array of bytes.4593*/4594private byte[] magSerializedForm() {4595int len = mag.length;45964597int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0]));4598int byteLen = (bitLen + 7) >>> 3;4599byte[] result = new byte[byteLen];46004601for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;4602i >= 0; i--) {4603if (bytesCopied == 4) {4604nextInt = mag[intIndex--];4605bytesCopied = 1;4606} else {4607nextInt >>>= 8;4608bytesCopied++;4609}4610result[i] = (byte)nextInt;4611}4612return result;4613}46144615/**4616* Converts this {@code BigInteger} to a {@code long}, checking4617* for lost information. If the value of this {@code BigInteger}4618* is out of the range of the {@code long} type, then an4619* {@code ArithmeticException} is thrown.4620*4621* @return this {@code BigInteger} converted to a {@code long}.4622* @throws ArithmeticException if the value of {@code this} will4623* not exactly fit in a {@code long}.4624* @see BigInteger#longValue4625* @since 1.84626*/4627public long longValueExact() {4628if (mag.length <= 2 && bitLength() <= 63)4629return longValue();4630else4631throw new ArithmeticException("BigInteger out of long range");4632}46334634/**4635* Converts this {@code BigInteger} to an {@code int}, checking4636* for lost information. If the value of this {@code BigInteger}4637* is out of the range of the {@code int} type, then an4638* {@code ArithmeticException} is thrown.4639*4640* @return this {@code BigInteger} converted to an {@code int}.4641* @throws ArithmeticException if the value of {@code this} will4642* not exactly fit in a {@code int}.4643* @see BigInteger#intValue4644* @since 1.84645*/4646public int intValueExact() {4647if (mag.length <= 1 && bitLength() <= 31)4648return intValue();4649else4650throw new ArithmeticException("BigInteger out of int range");4651}46524653/**4654* Converts this {@code BigInteger} to a {@code short}, checking4655* for lost information. If the value of this {@code BigInteger}4656* is out of the range of the {@code short} type, then an4657* {@code ArithmeticException} is thrown.4658*4659* @return this {@code BigInteger} converted to a {@code short}.4660* @throws ArithmeticException if the value of {@code this} will4661* not exactly fit in a {@code short}.4662* @see BigInteger#shortValue4663* @since 1.84664*/4665public short shortValueExact() {4666if (mag.length <= 1 && bitLength() <= 31) {4667int value = intValue();4668if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE)4669return shortValue();4670}4671throw new ArithmeticException("BigInteger out of short range");4672}46734674/**4675* Converts this {@code BigInteger} to a {@code byte}, checking4676* for lost information. If the value of this {@code BigInteger}4677* is out of the range of the {@code byte} type, then an4678* {@code ArithmeticException} is thrown.4679*4680* @return this {@code BigInteger} converted to a {@code byte}.4681* @throws ArithmeticException if the value of {@code this} will4682* not exactly fit in a {@code byte}.4683* @see BigInteger#byteValue4684* @since 1.84685*/4686public byte byteValueExact() {4687if (mag.length <= 1 && bitLength() <= 31) {4688int value = intValue();4689if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE)4690return byteValue();4691}4692throw new ArithmeticException("BigInteger out of byte range");4693}4694}469546964697