Path: blob/master/src/java.base/share/classes/java/math/BigInteger.java
41152 views
/*1* Copyright (c) 1996, 2021, 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.Objects;37import java.util.Random;38import java.util.concurrent.ThreadLocalRandom;3940import jdk.internal.math.DoubleConsts;41import jdk.internal.math.FloatConsts;42import jdk.internal.vm.annotation.ForceInline;43import jdk.internal.vm.annotation.IntrinsicCandidate;44import jdk.internal.vm.annotation.Stable;4546/**47* Immutable arbitrary-precision integers. All operations behave as if48* BigIntegers were represented in two's-complement notation (like Java's49* primitive integer types). BigInteger provides analogues to all of Java's50* primitive integer operators, and all relevant methods from java.lang.Math.51* Additionally, BigInteger provides operations for modular arithmetic, GCD52* calculation, primality testing, prime generation, bit manipulation,53* and a few other miscellaneous operations.54*55* <p>Semantics of arithmetic operations exactly mimic those of Java's integer56* arithmetic operators, as defined in <i>The Java Language Specification</i>.57* For example, division by zero throws an {@code ArithmeticException}, and58* division of a negative by a positive yields a negative (or zero) remainder.59*60* <p>Semantics of shift operations extend those of Java's shift operators61* to allow for negative shift distances. A right-shift with a negative62* shift distance results in a left shift, and vice-versa. The unsigned63* right shift operator ({@code >>>}) is omitted since this operation64* only makes sense for a fixed sized word and not for a65* representation conceptually having an infinite number of leading66* virtual sign bits.67*68* <p>Semantics of bitwise logical operations exactly mimic those of Java's69* bitwise integer operators. The binary operators ({@code and},70* {@code or}, {@code xor}) implicitly perform sign extension on the shorter71* of the two operands prior to performing the operation.72*73* <p>Comparison operations perform signed integer comparisons, analogous to74* those performed by Java's relational and equality operators.75*76* <p>Modular arithmetic operations are provided to compute residues, perform77* exponentiation, and compute multiplicative inverses. These methods always78* return a non-negative result, between {@code 0} and {@code (modulus - 1)},79* inclusive.80*81* <p>Bit operations operate on a single bit of the two's-complement82* representation of their operand. If necessary, the operand is sign-extended83* so that it contains the designated bit. None of the single-bit84* operations can produce a BigInteger with a different sign from the85* BigInteger being operated on, as they affect only a single bit, and the86* arbitrarily large abstraction provided by this class ensures that conceptually87* there are infinitely many "virtual sign bits" preceding each BigInteger.88*89* <p>For the sake of brevity and clarity, pseudo-code is used throughout the90* descriptions of BigInteger methods. The pseudo-code expression91* {@code (i + j)} is shorthand for "a BigInteger whose value is92* that of the BigInteger {@code i} plus that of the BigInteger {@code j}."93* The pseudo-code expression {@code (i == j)} is shorthand for94* "{@code true} if and only if the BigInteger {@code i} represents the same95* value as the BigInteger {@code j}." Other pseudo-code expressions are96* interpreted similarly.97*98* <p>All methods and constructors in this class throw99* {@code NullPointerException} when passed100* a null object reference for any input parameter.101*102* BigInteger must support values in the range103* -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to104* +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive)105* and may support values outside of that range.106*107* An {@code ArithmeticException} is thrown when a BigInteger108* constructor or method would generate a value outside of the109* supported range.110*111* The range of probable prime values is limited and may be less than112* the full supported positive range of {@code BigInteger}.113* The range must be at least 1 to 2<sup>500000000</sup>.114*115* @implNote116* In the reference implementation, BigInteger constructors and117* operations throw {@code ArithmeticException} when the result is out118* of the supported range of119* -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to120* +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive).121*122* @see BigDecimal123* @jls 4.2.2 Integer Operations124* @author Josh Bloch125* @author Michael McCloskey126* @author Alan Eliasen127* @author Timothy Buktu128* @since 1.1129*/130131public class BigInteger extends Number implements Comparable<BigInteger> {132/**133* The signum of this BigInteger: -1 for negative, 0 for zero, or134* 1 for positive. Note that the BigInteger zero <em>must</em> have135* a signum of 0. This is necessary to ensures that there is exactly one136* representation for each BigInteger value.137*/138final int signum;139140/**141* The magnitude of this BigInteger, in <i>big-endian</i> order: the142* zeroth element of this array is the most-significant int of the143* magnitude. The magnitude must be "minimal" in that the most-significant144* int ({@code mag[0]}) must be non-zero. This is necessary to145* ensure that there is exactly one representation for each BigInteger146* value. Note that this implies that the BigInteger zero has a147* zero-length mag array.148*/149final int[] mag;150151// The following fields are stable variables. A stable variable's value152// changes at most once from the default zero value to a non-zero stable153// value. A stable value is calculated lazily on demand.154155/**156* One plus the bitCount of this BigInteger. This is a stable variable.157*158* @see #bitCount159*/160private int bitCountPlusOne;161162/**163* One plus the bitLength of this BigInteger. This is a stable variable.164* (either value is acceptable).165*166* @see #bitLength()167*/168private int bitLengthPlusOne;169170/**171* Two plus the lowest set bit of this BigInteger. This is a stable variable.172*173* @see #getLowestSetBit174*/175private int lowestSetBitPlusTwo;176177/**178* Two plus the index of the lowest-order int in the magnitude of this179* BigInteger that contains a nonzero int. This is a stable variable. The180* least significant int has int-number 0, the next int in order of181* increasing significance has int-number 1, and so forth.182*183* <p>Note: never used for a BigInteger with a magnitude of zero.184*185* @see #firstNonzeroIntNum()186*/187private int firstNonzeroIntNumPlusTwo;188189/**190* This mask is used to obtain the value of an int as if it were unsigned.191*/192static final long LONG_MASK = 0xffffffffL;193194/**195* This constant limits {@code mag.length} of BigIntegers to the supported196* range.197*/198private static final int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26)199200/**201* Bit lengths larger than this constant can cause overflow in searchLen202* calculation and in BitSieve.singleSearch method.203*/204private static final int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;205206/**207* The threshold value for using Karatsuba multiplication. If the number208* of ints in both mag arrays are greater than this number, then209* Karatsuba multiplication will be used. This value is found210* experimentally to work well.211*/212private static final int KARATSUBA_THRESHOLD = 80;213214/**215* The threshold value for using 3-way Toom-Cook multiplication.216* If the number of ints in each mag array is greater than the217* Karatsuba threshold, and the number of ints in at least one of218* the mag arrays is greater than this threshold, then Toom-Cook219* multiplication will be used.220*/221private static final int TOOM_COOK_THRESHOLD = 240;222223/**224* The threshold value for using Karatsuba squaring. If the number225* of ints in the number are larger than this value,226* Karatsuba squaring will be used. This value is found227* experimentally to work well.228*/229private static final int KARATSUBA_SQUARE_THRESHOLD = 128;230231/**232* The threshold value for using Toom-Cook squaring. If the number233* of ints in the number are larger than this value,234* Toom-Cook squaring will be used. This value is found235* experimentally to work well.236*/237private static final int TOOM_COOK_SQUARE_THRESHOLD = 216;238239/**240* The threshold value for using Burnikel-Ziegler division. If the number241* of ints in the divisor are larger than this value, Burnikel-Ziegler242* division may be used. This value is found experimentally to work well.243*/244static final int BURNIKEL_ZIEGLER_THRESHOLD = 80;245246/**247* The offset value for using Burnikel-Ziegler division. If the number248* of ints in the divisor exceeds the Burnikel-Ziegler threshold, and the249* number of ints in the dividend is greater than the number of ints in the250* divisor plus this value, Burnikel-Ziegler division will be used. This251* value is found experimentally to work well.252*/253static final int BURNIKEL_ZIEGLER_OFFSET = 40;254255/**256* The threshold value for using Schoenhage recursive base conversion. If257* the number of ints in the number are larger than this value,258* the Schoenhage algorithm will be used. In practice, it appears that the259* Schoenhage routine is faster for any threshold down to 2, and is260* relatively flat for thresholds between 2-25, so this choice may be261* varied within this range for very small effect.262*/263private static final int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20;264265/**266* The threshold value for using squaring code to perform multiplication267* of a {@code BigInteger} instance by itself. If the number of ints in268* the number are larger than this value, {@code multiply(this)} will269* return {@code square()}.270*/271private static final int MULTIPLY_SQUARE_THRESHOLD = 20;272273/**274* The threshold for using an intrinsic version of275* implMontgomeryXXX to perform Montgomery multiplication. If the276* number of ints in the number is more than this value we do not277* use the intrinsic.278*/279private static final int MONTGOMERY_INTRINSIC_THRESHOLD = 512;280281282// Constructors283284/**285* Translates a byte sub-array containing the two's-complement binary286* representation of a BigInteger into a BigInteger. The sub-array is287* specified via an offset into the array and a length. The sub-array is288* assumed to be in <i>big-endian</i> byte-order: the most significant289* byte is the element at index {@code off}. The {@code val} array is290* assumed to be unchanged for the duration of the constructor call.291*292* An {@code IndexOutOfBoundsException} is thrown if the length of the array293* {@code val} is non-zero and either {@code off} is negative, {@code len}294* is negative, or {@code off+len} is greater than the length of295* {@code val}.296*297* @param val byte array containing a sub-array which is the big-endian298* two's-complement binary representation of a BigInteger.299* @param off the start offset of the binary representation.300* @param len the number of bytes to use.301* @throws NumberFormatException {@code val} is zero bytes long.302* @throws IndexOutOfBoundsException if the provided array offset and303* length would cause an index into the byte array to be304* negative or greater than or equal to the array length.305* @since 9306*/307public BigInteger(byte[] val, int off, int len) {308if (val.length == 0) {309throw new NumberFormatException("Zero length BigInteger");310}311Objects.checkFromIndexSize(off, len, val.length);312313if (val[off] < 0) {314mag = makePositive(val, off, len);315signum = -1;316} else {317mag = stripLeadingZeroBytes(val, off, len);318signum = (mag.length == 0 ? 0 : 1);319}320if (mag.length >= MAX_MAG_LENGTH) {321checkRange();322}323}324325/**326* Translates a byte array containing the two's-complement binary327* representation of a BigInteger into a BigInteger. The input array is328* assumed to be in <i>big-endian</i> byte-order: the most significant329* byte is in the zeroth element. The {@code val} array is assumed to be330* unchanged for the duration of the constructor call.331*332* @param val big-endian two's-complement binary representation of a333* BigInteger.334* @throws NumberFormatException {@code val} is zero bytes long.335*/336public BigInteger(byte[] val) {337this(val, 0, val.length);338}339340/**341* This private constructor translates an int array containing the342* two's-complement binary representation of a BigInteger into a343* BigInteger. The input array is assumed to be in <i>big-endian</i>344* int-order: the most significant int is in the zeroth element. The345* {@code val} array is assumed to be unchanged for the duration of346* the constructor call.347*/348private BigInteger(int[] val) {349if (val.length == 0)350throw new NumberFormatException("Zero length BigInteger");351352if (val[0] < 0) {353mag = makePositive(val);354signum = -1;355} else {356mag = trustedStripLeadingZeroInts(val);357signum = (mag.length == 0 ? 0 : 1);358}359if (mag.length >= MAX_MAG_LENGTH) {360checkRange();361}362}363364/**365* Translates the sign-magnitude representation of a BigInteger into a366* BigInteger. The sign is represented as an integer signum value: -1 for367* negative, 0 for zero, or 1 for positive. The magnitude is a sub-array of368* a byte array in <i>big-endian</i> byte-order: the most significant byte369* is the element at index {@code off}. A zero value of the length370* {@code len} is permissible, and will result in a BigInteger value of 0,371* whether signum is -1, 0 or 1. The {@code magnitude} array is assumed to372* be unchanged for the duration of the constructor call.373*374* An {@code IndexOutOfBoundsException} is thrown if the length of the array375* {@code magnitude} is non-zero and either {@code off} is negative,376* {@code len} is negative, or {@code off+len} is greater than the length of377* {@code magnitude}.378*379* @param signum signum of the number (-1 for negative, 0 for zero, 1380* for positive).381* @param magnitude big-endian binary representation of the magnitude of382* the number.383* @param off the start offset of the binary representation.384* @param len the number of bytes to use.385* @throws NumberFormatException {@code signum} is not one of the three386* legal values (-1, 0, and 1), or {@code signum} is 0 and387* {@code magnitude} contains one or more non-zero bytes.388* @throws IndexOutOfBoundsException if the provided array offset and389* length would cause an index into the byte array to be390* negative or greater than or equal to the array length.391* @since 9392*/393public BigInteger(int signum, byte[] magnitude, int off, int len) {394if (signum < -1 || signum > 1) {395throw(new NumberFormatException("Invalid signum value"));396}397Objects.checkFromIndexSize(off, len, magnitude.length);398399// stripLeadingZeroBytes() returns a zero length array if len == 0400this.mag = stripLeadingZeroBytes(magnitude, off, len);401402if (this.mag.length == 0) {403this.signum = 0;404} else {405if (signum == 0)406throw(new NumberFormatException("signum-magnitude mismatch"));407this.signum = signum;408}409if (mag.length >= MAX_MAG_LENGTH) {410checkRange();411}412}413414/**415* Translates the sign-magnitude representation of a BigInteger into a416* BigInteger. The sign is represented as an integer signum value: -1 for417* negative, 0 for zero, or 1 for positive. The magnitude is a byte array418* in <i>big-endian</i> byte-order: the most significant byte is the419* zeroth element. A zero-length magnitude array is permissible, and will420* result in a BigInteger value of 0, whether signum is -1, 0 or 1. The421* {@code magnitude} array is assumed to be unchanged for the duration of422* the constructor call.423*424* @param signum signum of the number (-1 for negative, 0 for zero, 1425* for positive).426* @param magnitude big-endian binary representation of the magnitude of427* the number.428* @throws NumberFormatException {@code signum} is not one of the three429* legal values (-1, 0, and 1), or {@code signum} is 0 and430* {@code magnitude} contains one or more non-zero bytes.431*/432public BigInteger(int signum, byte[] magnitude) {433this(signum, magnitude, 0, magnitude.length);434}435436/**437* A constructor for internal use that translates the sign-magnitude438* representation of a BigInteger into a BigInteger. It checks the439* arguments and copies the magnitude so this constructor would be440* safe for external use. The {@code magnitude} array is assumed to be441* unchanged for the duration of the constructor call.442*/443private BigInteger(int signum, int[] magnitude) {444this.mag = stripLeadingZeroInts(magnitude);445446if (signum < -1 || signum > 1)447throw(new NumberFormatException("Invalid signum value"));448449if (this.mag.length == 0) {450this.signum = 0;451} else {452if (signum == 0)453throw(new NumberFormatException("signum-magnitude mismatch"));454this.signum = signum;455}456if (mag.length >= MAX_MAG_LENGTH) {457checkRange();458}459}460461/**462* Translates the String representation of a BigInteger in the463* specified radix into a BigInteger. The String representation464* consists of an optional minus or plus sign followed by a465* sequence of one or more digits in the specified radix. The466* character-to-digit mapping is provided by {@link467* Character#digit(char, int) Character.digit}. The String may468* not contain any extraneous characters (whitespace, for469* example).470*471* @param val String representation of BigInteger.472* @param radix radix to be used in interpreting {@code val}.473* @throws NumberFormatException {@code val} is not a valid representation474* of a BigInteger in the specified radix, or {@code radix} is475* outside the range from {@link Character#MIN_RADIX} to476* {@link Character#MAX_RADIX}, inclusive.477*/478public BigInteger(String val, int radix) {479int cursor = 0, numDigits;480final int len = val.length();481482if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)483throw new NumberFormatException("Radix out of range");484if (len == 0)485throw new NumberFormatException("Zero length BigInteger");486487// Check for at most one leading sign488int sign = 1;489int index1 = val.lastIndexOf('-');490int index2 = val.lastIndexOf('+');491if (index1 >= 0) {492if (index1 != 0 || index2 >= 0) {493throw new NumberFormatException("Illegal embedded sign character");494}495sign = -1;496cursor = 1;497} else if (index2 >= 0) {498if (index2 != 0) {499throw new NumberFormatException("Illegal embedded sign character");500}501cursor = 1;502}503if (cursor == len)504throw new NumberFormatException("Zero length BigInteger");505506// Skip leading zeros and compute number of digits in magnitude507while (cursor < len &&508Character.digit(val.charAt(cursor), radix) == 0) {509cursor++;510}511512if (cursor == len) {513signum = 0;514mag = ZERO.mag;515return;516}517518numDigits = len - cursor;519signum = sign;520521// Pre-allocate array of expected size. May be too large but can522// never be too small. Typically exact.523long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1;524if (numBits + 31 >= (1L << 32)) {525reportOverflow();526}527int numWords = (int) (numBits + 31) >>> 5;528int[] magnitude = new int[numWords];529530// Process first (potentially short) digit group531int firstGroupLen = numDigits % digitsPerInt[radix];532if (firstGroupLen == 0)533firstGroupLen = digitsPerInt[radix];534String group = val.substring(cursor, cursor += firstGroupLen);535magnitude[numWords - 1] = Integer.parseInt(group, radix);536if (magnitude[numWords - 1] < 0)537throw new NumberFormatException("Illegal digit");538539// Process remaining digit groups540int superRadix = intRadix[radix];541int groupVal = 0;542while (cursor < len) {543group = val.substring(cursor, cursor += digitsPerInt[radix]);544groupVal = Integer.parseInt(group, radix);545if (groupVal < 0)546throw new NumberFormatException("Illegal digit");547destructiveMulAdd(magnitude, superRadix, groupVal);548}549// Required for cases where the array was overallocated.550mag = trustedStripLeadingZeroInts(magnitude);551if (mag.length >= MAX_MAG_LENGTH) {552checkRange();553}554}555556/*557* Constructs a new BigInteger using a char array with radix=10.558* Sign is precalculated outside and not allowed in the val. The {@code val}559* array is assumed to be unchanged for the duration of the constructor560* call.561*/562BigInteger(char[] val, int sign, int len) {563int cursor = 0, numDigits;564565// Skip leading zeros and compute number of digits in magnitude566while (cursor < len && Character.digit(val[cursor], 10) == 0) {567cursor++;568}569if (cursor == len) {570signum = 0;571mag = ZERO.mag;572return;573}574575numDigits = len - cursor;576signum = sign;577// Pre-allocate array of expected size578int numWords;579if (len < 10) {580numWords = 1;581} else {582long numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1;583if (numBits + 31 >= (1L << 32)) {584reportOverflow();585}586numWords = (int) (numBits + 31) >>> 5;587}588int[] magnitude = new int[numWords];589590// Process first (potentially short) digit group591int firstGroupLen = numDigits % digitsPerInt[10];592if (firstGroupLen == 0)593firstGroupLen = digitsPerInt[10];594magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen);595596// Process remaining digit groups597while (cursor < len) {598int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);599destructiveMulAdd(magnitude, intRadix[10], groupVal);600}601mag = trustedStripLeadingZeroInts(magnitude);602if (mag.length >= MAX_MAG_LENGTH) {603checkRange();604}605}606607// Create an integer with the digits between the two indexes608// Assumes start < end. The result may be negative, but it609// is to be treated as an unsigned value.610private int parseInt(char[] source, int start, int end) {611int result = Character.digit(source[start++], 10);612if (result == -1)613throw new NumberFormatException(new String(source));614615for (int index = start; index < end; index++) {616int nextVal = Character.digit(source[index], 10);617if (nextVal == -1)618throw new NumberFormatException(new String(source));619result = 10*result + nextVal;620}621622return result;623}624625// bitsPerDigit in the given radix times 1024626// Rounded up to avoid underallocation.627private static long bitsPerDigit[] = { 0, 0,6281024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,6293790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,6304696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,6315253, 5295};632633// Multiply x array times word y in place, and add word z634private static void destructiveMulAdd(int[] x, int y, int z) {635// Perform the multiplication word by word636long ylong = y & LONG_MASK;637long zlong = z & LONG_MASK;638int len = x.length;639640long product = 0;641long carry = 0;642for (int i = len-1; i >= 0; i--) {643product = ylong * (x[i] & LONG_MASK) + carry;644x[i] = (int)product;645carry = product >>> 32;646}647648// Perform the addition649long sum = (x[len-1] & LONG_MASK) + zlong;650x[len-1] = (int)sum;651carry = sum >>> 32;652for (int i = len-2; i >= 0; i--) {653sum = (x[i] & LONG_MASK) + carry;654x[i] = (int)sum;655carry = sum >>> 32;656}657}658659/**660* Translates the decimal String representation of a BigInteger661* into a BigInteger. The String representation consists of an662* optional minus or plus sign followed by a sequence of one or663* more decimal digits. The character-to-digit mapping is664* provided by {@link Character#digit(char, int)665* Character.digit}. The String may not contain any extraneous666* characters (whitespace, for example).667*668* @param val decimal String representation of BigInteger.669* @throws NumberFormatException {@code val} is not a valid representation670* of a BigInteger.671*/672public BigInteger(String val) {673this(val, 10);674}675676/**677* Constructs a randomly generated BigInteger, uniformly distributed over678* the range 0 to (2<sup>{@code numBits}</sup> - 1), inclusive.679* The uniformity of the distribution assumes that a fair source of random680* bits is provided in {@code rnd}. Note that this constructor always681* constructs a non-negative BigInteger.682*683* @param numBits maximum bitLength of the new BigInteger.684* @param rnd source of randomness to be used in computing the new685* BigInteger.686* @throws IllegalArgumentException {@code numBits} is negative.687* @see #bitLength()688*/689public BigInteger(int numBits, Random rnd) {690byte[] magnitude = randomBits(numBits, rnd);691692try {693// stripLeadingZeroBytes() returns a zero length array if len == 0694this.mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);695696if (this.mag.length == 0) {697this.signum = 0;698} else {699this.signum = 1;700}701if (mag.length >= MAX_MAG_LENGTH) {702checkRange();703}704} finally {705Arrays.fill(magnitude, (byte)0);706}707}708709private static byte[] randomBits(int numBits, Random rnd) {710if (numBits < 0)711throw new IllegalArgumentException("numBits must be non-negative");712int numBytes = (int)(((long)numBits+7)/8); // avoid overflow713byte[] randomBits = new byte[numBytes];714715// Generate random bytes and mask out any excess bits716if (numBytes > 0) {717rnd.nextBytes(randomBits);718int excessBits = 8*numBytes - numBits;719randomBits[0] &= (1 << (8-excessBits)) - 1;720}721return randomBits;722}723724/**725* Constructs a randomly generated positive BigInteger that is probably726* prime, with the specified bitLength.727*728* @apiNote It is recommended that the {@link #probablePrime probablePrime}729* method be used in preference to this constructor unless there730* is a compelling need to specify a certainty.731*732* @param bitLength bitLength of the returned BigInteger.733* @param certainty a measure of the uncertainty that the caller is734* willing to tolerate. The probability that the new BigInteger735* represents a prime number will exceed736* (1 - 1/2<sup>{@code certainty}</sup>). The execution time of737* this constructor is proportional to the value of this parameter.738* @param rnd source of random bits used to select candidates to be739* tested for primality.740* @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.741* @see #bitLength()742*/743public BigInteger(int bitLength, int certainty, Random rnd) {744BigInteger prime;745746if (bitLength < 2)747throw new ArithmeticException("bitLength < 2");748prime = (bitLength < SMALL_PRIME_THRESHOLD749? smallPrime(bitLength, certainty, rnd)750: largePrime(bitLength, certainty, rnd));751signum = 1;752mag = prime.mag;753}754755// Minimum size in bits that the requested prime number has756// before we use the large prime number generating algorithms.757// The cutoff of 95 was chosen empirically for best performance.758private static final int SMALL_PRIME_THRESHOLD = 95;759760// Certainty required to meet the spec of probablePrime761private static final int DEFAULT_PRIME_CERTAINTY = 100;762763/**764* Returns a positive BigInteger that is probably prime, with the765* specified bitLength. The probability that a BigInteger returned766* by this method is composite does not exceed 2<sup>-100</sup>.767*768* @param bitLength bitLength of the returned BigInteger.769* @param rnd source of random bits used to select candidates to be770* tested for primality.771* @return a BigInteger of {@code bitLength} bits that is probably prime772* @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.773* @see #bitLength()774* @since 1.4775*/776public static BigInteger probablePrime(int bitLength, Random rnd) {777if (bitLength < 2)778throw new ArithmeticException("bitLength < 2");779780return (bitLength < SMALL_PRIME_THRESHOLD ?781smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :782largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));783}784785/**786* Find a random number of the specified bitLength that is probably prime.787* This method is used for smaller primes, its performance degrades on788* larger bitlengths.789*790* This method assumes bitLength > 1.791*/792private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {793int magLen = (bitLength + 31) >>> 5;794int temp[] = new int[magLen];795int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int796int highMask = (highBit << 1) - 1; // Bits to keep in high int797798while (true) {799// Construct a candidate800for (int i=0; i < magLen; i++)801temp[i] = rnd.nextInt();802temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length803if (bitLength > 2)804temp[magLen-1] |= 1; // Make odd if bitlen > 2805806BigInteger p = new BigInteger(temp, 1);807808// Do cheap "pre-test" if applicable809if (bitLength > 6) {810long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();811if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||812(r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||813(r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))814continue; // Candidate is composite; try another815}816817// All candidates of bitLength 2 and 3 are prime by this point818if (bitLength < 4)819return p;820821// Do expensive test if we survive pre-test (or it's inapplicable)822if (p.primeToCertainty(certainty, rnd))823return p;824}825}826827private static final BigInteger SMALL_PRIME_PRODUCT828= valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);829830/**831* Find a random number of the specified bitLength that is probably prime.832* This method is more appropriate for larger bitlengths since it uses833* a sieve to eliminate most composites before using a more expensive834* test.835*/836private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {837BigInteger p;838p = new BigInteger(bitLength, rnd).setBit(bitLength-1);839p.mag[p.mag.length-1] &= 0xfffffffe;840841// Use a sieve length likely to contain the next prime number842int searchLen = getPrimeSearchLen(bitLength);843BitSieve searchSieve = new BitSieve(p, searchLen);844BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);845846while ((candidate == null) || (candidate.bitLength() != bitLength)) {847p = p.add(BigInteger.valueOf(2*searchLen));848if (p.bitLength() != bitLength)849p = new BigInteger(bitLength, rnd).setBit(bitLength-1);850p.mag[p.mag.length-1] &= 0xfffffffe;851searchSieve = new BitSieve(p, searchLen);852candidate = searchSieve.retrieve(p, certainty, rnd);853}854return candidate;855}856857/**858* Returns the first integer greater than this {@code BigInteger} that859* is probably prime. The probability that the number returned by this860* method is composite does not exceed 2<sup>-100</sup>. This method will861* never skip over a prime when searching: if it returns {@code p}, there862* is no prime {@code q} such that {@code this < q < p}.863*864* @return the first integer greater than this {@code BigInteger} that865* is probably prime.866* @throws ArithmeticException {@code this < 0} or {@code this} is too large.867* @since 1.5868*/869public BigInteger nextProbablePrime() {870if (this.signum < 0)871throw new ArithmeticException("start < 0: " + this);872873// Handle trivial cases874if ((this.signum == 0) || this.equals(ONE))875return TWO;876877BigInteger result = this.add(ONE);878879// Fastpath for small numbers880if (result.bitLength() < SMALL_PRIME_THRESHOLD) {881882// Ensure an odd number883if (!result.testBit(0))884result = result.add(ONE);885886while (true) {887// Do cheap "pre-test" if applicable888if (result.bitLength() > 6) {889long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();890if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||891(r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||892(r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {893result = result.add(TWO);894continue; // Candidate is composite; try another895}896}897898// All candidates of bitLength 2 and 3 are prime by this point899if (result.bitLength() < 4)900return result;901902// The expensive test903if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))904return result;905906result = result.add(TWO);907}908}909910// Start at previous even number911if (result.testBit(0))912result = result.subtract(ONE);913914// Looking for the next large prime915int searchLen = getPrimeSearchLen(result.bitLength());916917while (true) {918BitSieve searchSieve = new BitSieve(result, searchLen);919BigInteger candidate = searchSieve.retrieve(result,920DEFAULT_PRIME_CERTAINTY, null);921if (candidate != null)922return candidate;923result = result.add(BigInteger.valueOf(2 * searchLen));924}925}926927private static int getPrimeSearchLen(int bitLength) {928if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) {929throw new ArithmeticException("Prime search implementation restriction on bitLength");930}931return bitLength / 20 * 64;932}933934/**935* Returns {@code true} if this BigInteger is probably prime,936* {@code false} if it's definitely composite.937*938* This method assumes bitLength > 2.939*940* @param certainty a measure of the uncertainty that the caller is941* willing to tolerate: if the call returns {@code true}942* the probability that this BigInteger is prime exceeds943* {@code (1 - 1/2<sup>certainty</sup>)}. The execution time of944* this method is proportional to the value of this parameter.945* @return {@code true} if this BigInteger is probably prime,946* {@code false} if it's definitely composite.947*/948boolean primeToCertainty(int certainty, Random random) {949int rounds = 0;950int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;951952// The relationship between the certainty and the number of rounds953// we perform is given in the draft standard ANSI X9.80, "PRIME954// NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".955int sizeInBits = this.bitLength();956if (sizeInBits < 100) {957rounds = 50;958rounds = n < rounds ? n : rounds;959return passesMillerRabin(rounds, random);960}961962if (sizeInBits < 256) {963rounds = 27;964} else if (sizeInBits < 512) {965rounds = 15;966} else if (sizeInBits < 768) {967rounds = 8;968} else if (sizeInBits < 1024) {969rounds = 4;970} else {971rounds = 2;972}973rounds = n < rounds ? n : rounds;974975return passesMillerRabin(rounds, random) && passesLucasLehmer();976}977978/**979* Returns true iff this BigInteger is a Lucas-Lehmer probable prime.980*981* The following assumptions are made:982* This BigInteger is a positive, odd number.983*/984private boolean passesLucasLehmer() {985BigInteger thisPlusOne = this.add(ONE);986987// Step 1988int d = 5;989while (jacobiSymbol(d, this) != -1) {990// 5, -7, 9, -11, ...991d = (d < 0) ? Math.abs(d)+2 : -(d+2);992}993994// Step 2995BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);996997// Step 3998return u.mod(this).equals(ZERO);999}10001001/**1002* Computes Jacobi(p,n).1003* Assumes n positive, odd, n>=3.1004*/1005private static int jacobiSymbol(int p, BigInteger n) {1006if (p == 0)1007return 0;10081009// Algorithm and comments adapted from Colin Plumb's C library.1010int j = 1;1011int u = n.mag[n.mag.length-1];10121013// Make p positive1014if (p < 0) {1015p = -p;1016int n8 = u & 7;1017if ((n8 == 3) || (n8 == 7))1018j = -j; // 3 (011) or 7 (111) mod 81019}10201021// Get rid of factors of 2 in p1022while ((p & 3) == 0)1023p >>= 2;1024if ((p & 1) == 0) {1025p >>= 1;1026if (((u ^ (u>>1)) & 2) != 0)1027j = -j; // 3 (011) or 5 (101) mod 81028}1029if (p == 1)1030return j;1031// Then, apply quadratic reciprocity1032if ((p & u & 2) != 0) // p = u = 3 (mod 4)?1033j = -j;1034// And reduce u mod p1035u = n.mod(BigInteger.valueOf(p)).intValue();10361037// Now compute Jacobi(u,p), u < p1038while (u != 0) {1039while ((u & 3) == 0)1040u >>= 2;1041if ((u & 1) == 0) {1042u >>= 1;1043if (((p ^ (p>>1)) & 2) != 0)1044j = -j; // 3 (011) or 5 (101) mod 81045}1046if (u == 1)1047return j;1048// Now both u and p are odd, so use quadratic reciprocity1049assert (u < p);1050int t = u; u = p; p = t;1051if ((u & p & 2) != 0) // u = p = 3 (mod 4)?1052j = -j;1053// Now u >= p, so it can be reduced1054u %= p;1055}1056return 0;1057}10581059private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {1060BigInteger d = BigInteger.valueOf(z);1061BigInteger u = ONE; BigInteger u2;1062BigInteger v = ONE; BigInteger v2;10631064for (int i=k.bitLength()-2; i >= 0; i--) {1065u2 = u.multiply(v).mod(n);10661067v2 = v.square().add(d.multiply(u.square())).mod(n);1068if (v2.testBit(0))1069v2 = v2.subtract(n);10701071v2 = v2.shiftRight(1);10721073u = u2; v = v2;1074if (k.testBit(i)) {1075u2 = u.add(v).mod(n);1076if (u2.testBit(0))1077u2 = u2.subtract(n);10781079u2 = u2.shiftRight(1);1080v2 = v.add(d.multiply(u)).mod(n);1081if (v2.testBit(0))1082v2 = v2.subtract(n);1083v2 = v2.shiftRight(1);10841085u = u2; v = v2;1086}1087}1088return u;1089}10901091/**1092* Returns true iff this BigInteger passes the specified number of1093* Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS1094* 186-2).1095*1096* The following assumptions are made:1097* This BigInteger is a positive, odd number greater than 2.1098* iterations<=50.1099*/1100private boolean passesMillerRabin(int iterations, Random rnd) {1101// Find a and m such that m is odd and this == 1 + 2**a * m1102BigInteger thisMinusOne = this.subtract(ONE);1103BigInteger m = thisMinusOne;1104int a = m.getLowestSetBit();1105m = m.shiftRight(a);11061107// Do the tests1108if (rnd == null) {1109rnd = ThreadLocalRandom.current();1110}1111for (int i=0; i < iterations; i++) {1112// Generate a uniform random on (1, this)1113BigInteger b;1114do {1115b = new BigInteger(this.bitLength(), rnd);1116} while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);11171118int j = 0;1119BigInteger z = b.modPow(m, this);1120while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {1121if (j > 0 && z.equals(ONE) || ++j == a)1122return false;1123z = z.modPow(TWO, this);1124}1125}1126return true;1127}11281129/**1130* This internal constructor differs from its public cousin1131* with the arguments reversed in two ways: it assumes that its1132* arguments are correct, and it doesn't copy the magnitude array.1133*/1134BigInteger(int[] magnitude, int signum) {1135this.signum = (magnitude.length == 0 ? 0 : signum);1136this.mag = magnitude;1137if (mag.length >= MAX_MAG_LENGTH) {1138checkRange();1139}1140}11411142/**1143* This private constructor is for internal use and assumes that its1144* arguments are correct. The {@code magnitude} array is assumed to be1145* unchanged for the duration of the constructor call.1146*/1147private BigInteger(byte[] magnitude, int signum) {1148this.signum = (magnitude.length == 0 ? 0 : signum);1149this.mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);1150if (mag.length >= MAX_MAG_LENGTH) {1151checkRange();1152}1153}11541155/**1156* Throws an {@code ArithmeticException} if the {@code BigInteger} would be1157* out of the supported range.1158*1159* @throws ArithmeticException if {@code this} exceeds the supported range.1160*/1161private void checkRange() {1162if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) {1163reportOverflow();1164}1165}11661167private static void reportOverflow() {1168throw new ArithmeticException("BigInteger would overflow supported range");1169}11701171//Static Factory Methods11721173/**1174* Returns a BigInteger whose value is equal to that of the1175* specified {@code long}.1176*1177* @apiNote This static factory method is provided in preference1178* to a ({@code long}) constructor because it allows for reuse of1179* frequently used BigIntegers.1180*1181* @param val value of the BigInteger to return.1182* @return a BigInteger with the specified value.1183*/1184public static BigInteger valueOf(long val) {1185// If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant1186if (val == 0)1187return ZERO;1188if (val > 0 && val <= MAX_CONSTANT)1189return posConst[(int) val];1190else if (val < 0 && val >= -MAX_CONSTANT)1191return negConst[(int) -val];11921193return new BigInteger(val);1194}11951196/**1197* Constructs a BigInteger with the specified value, which may not be zero.1198*/1199private BigInteger(long val) {1200if (val < 0) {1201val = -val;1202signum = -1;1203} else {1204signum = 1;1205}12061207int highWord = (int)(val >>> 32);1208if (highWord == 0) {1209mag = new int[1];1210mag[0] = (int)val;1211} else {1212mag = new int[2];1213mag[0] = highWord;1214mag[1] = (int)val;1215}1216}12171218/**1219* Returns a BigInteger with the given two's complement representation.1220* Assumes that the input array will not be modified (the returned1221* BigInteger will reference the input array if feasible).1222*/1223private static BigInteger valueOf(int val[]) {1224return (val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val));1225}12261227// Constants12281229/**1230* Initialize static constant array when class is loaded.1231*/1232private static final int MAX_CONSTANT = 16;1233@Stable1234private static final BigInteger[] posConst = new BigInteger[MAX_CONSTANT+1];1235@Stable1236private static final BigInteger[] negConst = new BigInteger[MAX_CONSTANT+1];12371238/**1239* The cache of powers of each radix. This allows us to not have to1240* recalculate powers of radix^(2^n) more than once. This speeds1241* Schoenhage recursive base conversion significantly.1242*/1243private static volatile BigInteger[][] powerCache;12441245/** The cache of logarithms of radices for base conversion. */1246private static final double[] logCache;12471248/** The natural log of 2. This is used in computing cache indices. */1249private static final double LOG_TWO = Math.log(2.0);12501251static {1252assert 0 < KARATSUBA_THRESHOLD1253&& KARATSUBA_THRESHOLD < TOOM_COOK_THRESHOLD1254&& TOOM_COOK_THRESHOLD < Integer.MAX_VALUE1255&& 0 < KARATSUBA_SQUARE_THRESHOLD1256&& KARATSUBA_SQUARE_THRESHOLD < TOOM_COOK_SQUARE_THRESHOLD1257&& TOOM_COOK_SQUARE_THRESHOLD < Integer.MAX_VALUE :1258"Algorithm thresholds are inconsistent";12591260for (int i = 1; i <= MAX_CONSTANT; i++) {1261int[] magnitude = new int[1];1262magnitude[0] = i;1263posConst[i] = new BigInteger(magnitude, 1);1264negConst[i] = new BigInteger(magnitude, -1);1265}12661267/*1268* Initialize the cache of radix^(2^x) values used for base conversion1269* with just the very first value. Additional values will be created1270* on demand.1271*/1272powerCache = new BigInteger[Character.MAX_RADIX+1][];1273logCache = new double[Character.MAX_RADIX+1];12741275for (int i=Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {1276powerCache[i] = new BigInteger[] { BigInteger.valueOf(i) };1277logCache[i] = Math.log(i);1278}1279}12801281/**1282* The BigInteger constant zero.1283*1284* @since 1.21285*/1286public static final BigInteger ZERO = new BigInteger(new int[0], 0);12871288/**1289* The BigInteger constant one.1290*1291* @since 1.21292*/1293public static final BigInteger ONE = valueOf(1);12941295/**1296* The BigInteger constant two.1297*1298* @since 91299*/1300public static final BigInteger TWO = valueOf(2);13011302/**1303* The BigInteger constant -1. (Not exported.)1304*/1305private static final BigInteger NEGATIVE_ONE = valueOf(-1);13061307/**1308* The BigInteger constant ten.1309*1310* @since 1.51311*/1312public static final BigInteger TEN = valueOf(10);13131314// Arithmetic Operations13151316/**1317* Returns a BigInteger whose value is {@code (this + val)}.1318*1319* @param val value to be added to this BigInteger.1320* @return {@code this + val}1321*/1322public BigInteger add(BigInteger val) {1323if (val.signum == 0)1324return this;1325if (signum == 0)1326return val;1327if (val.signum == signum)1328return new BigInteger(add(mag, val.mag), signum);13291330int cmp = compareMagnitude(val);1331if (cmp == 0)1332return ZERO;1333int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)1334: subtract(val.mag, mag));1335resultMag = trustedStripLeadingZeroInts(resultMag);13361337return new BigInteger(resultMag, cmp == signum ? 1 : -1);1338}13391340/**1341* Package private methods used by BigDecimal code to add a BigInteger1342* with a long. Assumes val is not equal to INFLATED.1343*/1344BigInteger add(long val) {1345if (val == 0)1346return this;1347if (signum == 0)1348return valueOf(val);1349if (Long.signum(val) == signum)1350return new BigInteger(add(mag, Math.abs(val)), signum);1351int cmp = compareMagnitude(val);1352if (cmp == 0)1353return ZERO;1354int[] resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag));1355resultMag = trustedStripLeadingZeroInts(resultMag);1356return new BigInteger(resultMag, cmp == signum ? 1 : -1);1357}13581359/**1360* Adds the contents of the int array x and long value val. This1361* method allocates a new int array to hold the answer and returns1362* a reference to that array. Assumes x.length > 0 and val is1363* non-negative1364*/1365private static int[] add(int[] x, long val) {1366int[] y;1367long sum = 0;1368int xIndex = x.length;1369int[] result;1370int highWord = (int)(val >>> 32);1371if (highWord == 0) {1372result = new int[xIndex];1373sum = (x[--xIndex] & LONG_MASK) + val;1374result[xIndex] = (int)sum;1375} else {1376if (xIndex == 1) {1377result = new int[2];1378sum = val + (x[0] & LONG_MASK);1379result[1] = (int)sum;1380result[0] = (int)(sum >>> 32);1381return result;1382} else {1383result = new int[xIndex];1384sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK);1385result[xIndex] = (int)sum;1386sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32);1387result[xIndex] = (int)sum;1388}1389}1390// Copy remainder of longer number while carry propagation is required1391boolean carry = (sum >>> 32 != 0);1392while (xIndex > 0 && carry)1393carry = ((result[--xIndex] = x[xIndex] + 1) == 0);1394// Copy remainder of longer number1395while (xIndex > 0)1396result[--xIndex] = x[xIndex];1397// Grow result if necessary1398if (carry) {1399int bigger[] = new int[result.length + 1];1400System.arraycopy(result, 0, bigger, 1, result.length);1401bigger[0] = 0x01;1402return bigger;1403}1404return result;1405}14061407/**1408* Adds the contents of the int arrays x and y. This method allocates1409* a new int array to hold the answer and returns a reference to that1410* array.1411*/1412private static int[] add(int[] x, int[] y) {1413// If x is shorter, swap the two arrays1414if (x.length < y.length) {1415int[] tmp = x;1416x = y;1417y = tmp;1418}14191420int xIndex = x.length;1421int yIndex = y.length;1422int result[] = new int[xIndex];1423long sum = 0;1424if (yIndex == 1) {1425sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ;1426result[xIndex] = (int)sum;1427} else {1428// Add common parts of both numbers1429while (yIndex > 0) {1430sum = (x[--xIndex] & LONG_MASK) +1431(y[--yIndex] & LONG_MASK) + (sum >>> 32);1432result[xIndex] = (int)sum;1433}1434}1435// Copy remainder of longer number while carry propagation is required1436boolean carry = (sum >>> 32 != 0);1437while (xIndex > 0 && carry)1438carry = ((result[--xIndex] = x[xIndex] + 1) == 0);14391440// Copy remainder of longer number1441while (xIndex > 0)1442result[--xIndex] = x[xIndex];14431444// Grow result if necessary1445if (carry) {1446int bigger[] = new int[result.length + 1];1447System.arraycopy(result, 0, bigger, 1, result.length);1448bigger[0] = 0x01;1449return bigger;1450}1451return result;1452}14531454private static int[] subtract(long val, int[] little) {1455int highWord = (int)(val >>> 32);1456if (highWord == 0) {1457int result[] = new int[1];1458result[0] = (int)(val - (little[0] & LONG_MASK));1459return result;1460} else {1461int result[] = new int[2];1462if (little.length == 1) {1463long difference = ((int)val & LONG_MASK) - (little[0] & LONG_MASK);1464result[1] = (int)difference;1465// Subtract remainder of longer number while borrow propagates1466boolean borrow = (difference >> 32 != 0);1467if (borrow) {1468result[0] = highWord - 1;1469} else { // Copy remainder of longer number1470result[0] = highWord;1471}1472return result;1473} else { // little.length == 21474long difference = ((int)val & LONG_MASK) - (little[1] & LONG_MASK);1475result[1] = (int)difference;1476difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32);1477result[0] = (int)difference;1478return result;1479}1480}1481}14821483/**1484* Subtracts the contents of the second argument (val) from the1485* first (big). The first int array (big) must represent a larger number1486* than the second. This method allocates the space necessary to hold the1487* answer.1488* assumes val >= 01489*/1490private static int[] subtract(int[] big, long val) {1491int highWord = (int)(val >>> 32);1492int bigIndex = big.length;1493int result[] = new int[bigIndex];1494long difference = 0;14951496if (highWord == 0) {1497difference = (big[--bigIndex] & LONG_MASK) - val;1498result[bigIndex] = (int)difference;1499} else {1500difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK);1501result[bigIndex] = (int)difference;1502difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32);1503result[bigIndex] = (int)difference;1504}15051506// Subtract remainder of longer number while borrow propagates1507boolean borrow = (difference >> 32 != 0);1508while (bigIndex > 0 && borrow)1509borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);15101511// Copy remainder of longer number1512while (bigIndex > 0)1513result[--bigIndex] = big[bigIndex];15141515return result;1516}15171518/**1519* Returns a BigInteger whose value is {@code (this - val)}.1520*1521* @param val value to be subtracted from this BigInteger.1522* @return {@code this - val}1523*/1524public BigInteger subtract(BigInteger val) {1525if (val.signum == 0)1526return this;1527if (signum == 0)1528return val.negate();1529if (val.signum != signum)1530return new BigInteger(add(mag, val.mag), signum);15311532int cmp = compareMagnitude(val);1533if (cmp == 0)1534return ZERO;1535int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)1536: subtract(val.mag, mag));1537resultMag = trustedStripLeadingZeroInts(resultMag);1538return new BigInteger(resultMag, cmp == signum ? 1 : -1);1539}15401541/**1542* Subtracts the contents of the second int arrays (little) from the1543* first (big). The first int array (big) must represent a larger number1544* than the second. This method allocates the space necessary to hold the1545* answer.1546*/1547private static int[] subtract(int[] big, int[] little) {1548int bigIndex = big.length;1549int result[] = new int[bigIndex];1550int littleIndex = little.length;1551long difference = 0;15521553// Subtract common parts of both numbers1554while (littleIndex > 0) {1555difference = (big[--bigIndex] & LONG_MASK) -1556(little[--littleIndex] & LONG_MASK) +1557(difference >> 32);1558result[bigIndex] = (int)difference;1559}15601561// Subtract remainder of longer number while borrow propagates1562boolean borrow = (difference >> 32 != 0);1563while (bigIndex > 0 && borrow)1564borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);15651566// Copy remainder of longer number1567while (bigIndex > 0)1568result[--bigIndex] = big[bigIndex];15691570return result;1571}15721573/**1574* Returns a BigInteger whose value is {@code (this * val)}.1575*1576* @implNote An implementation may offer better algorithmic1577* performance when {@code val == this}.1578*1579* @param val value to be multiplied by this BigInteger.1580* @return {@code this * val}1581*/1582public BigInteger multiply(BigInteger val) {1583return multiply(val, false);1584}15851586/**1587* Returns a BigInteger whose value is {@code (this * val)}. If1588* the invocation is recursive certain overflow checks are skipped.1589*1590* @param val value to be multiplied by this BigInteger.1591* @param isRecursion whether this is a recursive invocation1592* @return {@code this * val}1593*/1594private BigInteger multiply(BigInteger val, boolean isRecursion) {1595if (val.signum == 0 || signum == 0)1596return ZERO;15971598int xlen = mag.length;15991600if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD) {1601return square();1602}16031604int ylen = val.mag.length;16051606if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD)) {1607int resultSign = signum == val.signum ? 1 : -1;1608if (val.mag.length == 1) {1609return multiplyByInt(mag,val.mag[0], resultSign);1610}1611if (mag.length == 1) {1612return multiplyByInt(val.mag,mag[0], resultSign);1613}1614int[] result = multiplyToLen(mag, xlen,1615val.mag, ylen, null);1616result = trustedStripLeadingZeroInts(result);1617return new BigInteger(result, resultSign);1618} else {1619if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {1620return multiplyKaratsuba(this, val);1621} else {1622//1623// In "Hacker's Delight" section 2-13, p.33, it is explained1624// that if x and y are unsigned 32-bit quantities and m and n1625// are their respective numbers of leading zeros within 32 bits,1626// then the number of leading zeros within their product as a1627// 64-bit unsigned quantity is either m + n or m + n + 1. If1628// their product is not to overflow, it cannot exceed 32 bits,1629// and so the number of leading zeros of the product within 641630// bits must be at least 32, i.e., the leftmost set bit is at1631// zero-relative position 31 or less.1632//1633// From the above there are three cases:1634//1635// m + n leftmost set bit condition1636// ----- ---------------- ---------1637// >= 32 x <= 64 - 32 = 32 no overflow1638// == 31 x >= 64 - 32 = 32 possible overflow1639// <= 30 x >= 64 - 31 = 33 definite overflow1640//1641// The "possible overflow" condition cannot be detected by1642// examning data lengths alone and requires further calculation.1643//1644// By analogy, if 'this' and 'val' have m and n as their1645// respective numbers of leading zeros within 32*MAX_MAG_LENGTH1646// bits, then:1647//1648// m + n >= 32*MAX_MAG_LENGTH no overflow1649// m + n == 32*MAX_MAG_LENGTH - 1 possible overflow1650// m + n <= 32*MAX_MAG_LENGTH - 2 definite overflow1651//1652// Note however that if the number of ints in the result1653// were to be MAX_MAG_LENGTH and mag[0] < 0, then there would1654// be overflow. As a result the leftmost bit (of mag[0]) cannot1655// be used and the constraints must be adjusted by one bit to:1656//1657// m + n > 32*MAX_MAG_LENGTH no overflow1658// m + n == 32*MAX_MAG_LENGTH possible overflow1659// m + n < 32*MAX_MAG_LENGTH definite overflow1660//1661// The foregoing leading zero-based discussion is for clarity1662// only. The actual calculations use the estimated bit length1663// of the product as this is more natural to the internal1664// array representation of the magnitude which has no leading1665// zero elements.1666//1667if (!isRecursion) {1668// The bitLength() instance method is not used here as we1669// are only considering the magnitudes as non-negative. The1670// Toom-Cook multiplication algorithm determines the sign1671// at its end from the two signum values.1672if (bitLength(mag, mag.length) +1673bitLength(val.mag, val.mag.length) >167432L*MAX_MAG_LENGTH) {1675reportOverflow();1676}1677}16781679return multiplyToomCook3(this, val);1680}1681}1682}16831684private static BigInteger multiplyByInt(int[] x, int y, int sign) {1685if (Integer.bitCount(y) == 1) {1686return new BigInteger(shiftLeft(x,Integer.numberOfTrailingZeros(y)), sign);1687}1688int xlen = x.length;1689int[] rmag = new int[xlen + 1];1690long carry = 0;1691long yl = y & LONG_MASK;1692int rstart = rmag.length - 1;1693for (int i = xlen - 1; i >= 0; i--) {1694long product = (x[i] & LONG_MASK) * yl + carry;1695rmag[rstart--] = (int)product;1696carry = product >>> 32;1697}1698if (carry == 0L) {1699rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);1700} else {1701rmag[rstart] = (int)carry;1702}1703return new BigInteger(rmag, sign);1704}17051706/**1707* Package private methods used by BigDecimal code to multiply a BigInteger1708* with a long. Assumes v is not equal to INFLATED.1709*/1710BigInteger multiply(long v) {1711if (v == 0 || signum == 0)1712return ZERO;1713if (v == BigDecimal.INFLATED)1714return multiply(BigInteger.valueOf(v));1715int rsign = (v > 0 ? signum : -signum);1716if (v < 0)1717v = -v;1718long dh = v >>> 32; // higher order bits1719long dl = v & LONG_MASK; // lower order bits17201721int xlen = mag.length;1722int[] value = mag;1723int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]);1724long carry = 0;1725int rstart = rmag.length - 1;1726for (int i = xlen - 1; i >= 0; i--) {1727long product = (value[i] & LONG_MASK) * dl + carry;1728rmag[rstart--] = (int)product;1729carry = product >>> 32;1730}1731rmag[rstart] = (int)carry;1732if (dh != 0L) {1733carry = 0;1734rstart = rmag.length - 2;1735for (int i = xlen - 1; i >= 0; i--) {1736long product = (value[i] & LONG_MASK) * dh +1737(rmag[rstart] & LONG_MASK) + carry;1738rmag[rstart--] = (int)product;1739carry = product >>> 32;1740}1741rmag[0] = (int)carry;1742}1743if (carry == 0L)1744rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);1745return new BigInteger(rmag, rsign);1746}17471748/**1749* Multiplies int arrays x and y to the specified lengths and places1750* the result into z. There will be no leading zeros in the resultant array.1751*/1752private static int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {1753multiplyToLenCheck(x, xlen);1754multiplyToLenCheck(y, ylen);1755return implMultiplyToLen(x, xlen, y, ylen, z);1756}17571758@IntrinsicCandidate1759private static int[] implMultiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {1760int xstart = xlen - 1;1761int ystart = ylen - 1;17621763if (z == null || z.length < (xlen+ ylen))1764z = new int[xlen+ylen];17651766long carry = 0;1767for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {1768long product = (y[j] & LONG_MASK) *1769(x[xstart] & LONG_MASK) + carry;1770z[k] = (int)product;1771carry = product >>> 32;1772}1773z[xstart] = (int)carry;17741775for (int i = xstart-1; i >= 0; i--) {1776carry = 0;1777for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) {1778long product = (y[j] & LONG_MASK) *1779(x[i] & LONG_MASK) +1780(z[k] & LONG_MASK) + carry;1781z[k] = (int)product;1782carry = product >>> 32;1783}1784z[i] = (int)carry;1785}1786return z;1787}17881789private static void multiplyToLenCheck(int[] array, int length) {1790if (length <= 0) {1791return; // not an error because multiplyToLen won't execute if len <= 01792}17931794Objects.requireNonNull(array);17951796if (length > array.length) {1797throw new ArrayIndexOutOfBoundsException(length - 1);1798}1799}18001801/**1802* Multiplies two BigIntegers using the Karatsuba multiplication1803* algorithm. This is a recursive divide-and-conquer algorithm which is1804* more efficient for large numbers than what is commonly called the1805* "grade-school" algorithm used in multiplyToLen. If the numbers to be1806* multiplied have length n, the "grade-school" algorithm has an1807* asymptotic complexity of O(n^2). In contrast, the Karatsuba algorithm1808* has complexity of O(n^(log2(3))), or O(n^1.585). It achieves this1809* increased performance by doing 3 multiplies instead of 4 when1810* evaluating the product. As it has some overhead, should be used when1811* both numbers are larger than a certain threshold (found1812* experimentally).1813*1814* See: http://en.wikipedia.org/wiki/Karatsuba_algorithm1815*/1816private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) {1817int xlen = x.mag.length;1818int ylen = y.mag.length;18191820// The number of ints in each half of the number.1821int half = (Math.max(xlen, ylen)+1) / 2;18221823// xl and yl are the lower halves of x and y respectively,1824// xh and yh are the upper halves.1825BigInteger xl = x.getLower(half);1826BigInteger xh = x.getUpper(half);1827BigInteger yl = y.getLower(half);1828BigInteger yh = y.getUpper(half);18291830BigInteger p1 = xh.multiply(yh); // p1 = xh*yh1831BigInteger p2 = xl.multiply(yl); // p2 = xl*yl18321833// p3=(xh+xl)*(yh+yl)1834BigInteger p3 = xh.add(xl).multiply(yh.add(yl));18351836// result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p21837BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2);18381839if (x.signum != y.signum) {1840return result.negate();1841} else {1842return result;1843}1844}18451846/**1847* Multiplies two BigIntegers using a 3-way Toom-Cook multiplication1848* algorithm. This is a recursive divide-and-conquer algorithm which is1849* more efficient for large numbers than what is commonly called the1850* "grade-school" algorithm used in multiplyToLen. If the numbers to be1851* multiplied have length n, the "grade-school" algorithm has an1852* asymptotic complexity of O(n^2). In contrast, 3-way Toom-Cook has a1853* complexity of about O(n^1.465). It achieves this increased asymptotic1854* performance by breaking each number into three parts and by doing 51855* multiplies instead of 9 when evaluating the product. Due to overhead1856* (additions, shifts, and one division) in the Toom-Cook algorithm, it1857* should only be used when both numbers are larger than a certain1858* threshold (found experimentally). This threshold is generally larger1859* than that for Karatsuba multiplication, so this algorithm is generally1860* only used when numbers become significantly larger.1861*1862* The algorithm used is the "optimal" 3-way Toom-Cook algorithm outlined1863* by Marco Bodrato.1864*1865* See: http://bodrato.it/toom-cook/1866* http://bodrato.it/papers/#WAIFI20071867*1868* "Towards Optimal Toom-Cook Multiplication for Univariate and1869* Multivariate Polynomials in Characteristic 2 and 0." by Marco BODRATO;1870* In C.Carlet and B.Sunar, Eds., "WAIFI'07 proceedings", p. 116-133,1871* LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007.1872*1873*/1874private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) {1875int alen = a.mag.length;1876int blen = b.mag.length;18771878int largest = Math.max(alen, blen);18791880// k is the size (in ints) of the lower-order slices.1881int k = (largest+2)/3; // Equal to ceil(largest/3)18821883// r is the size (in ints) of the highest-order slice.1884int r = largest - 2*k;18851886// Obtain slices of the numbers. a2 and b2 are the most significant1887// bits of the numbers a and b, and a0 and b0 the least significant.1888BigInteger a0, a1, a2, b0, b1, b2;1889a2 = a.getToomSlice(k, r, 0, largest);1890a1 = a.getToomSlice(k, r, 1, largest);1891a0 = a.getToomSlice(k, r, 2, largest);1892b2 = b.getToomSlice(k, r, 0, largest);1893b1 = b.getToomSlice(k, r, 1, largest);1894b0 = b.getToomSlice(k, r, 2, largest);18951896BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;18971898v0 = a0.multiply(b0, true);1899da1 = a2.add(a0);1900db1 = b2.add(b0);1901vm1 = da1.subtract(a1).multiply(db1.subtract(b1), true);1902da1 = da1.add(a1);1903db1 = db1.add(b1);1904v1 = da1.multiply(db1, true);1905v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(1906db1.add(b2).shiftLeft(1).subtract(b0), true);1907vinf = a2.multiply(b2, true);19081909// The algorithm requires two divisions by 2 and one by 3.1910// All divisions are known to be exact, that is, they do not produce1911// remainders, and all results are positive. The divisions by 2 are1912// implemented as right shifts which are relatively efficient, leaving1913// only an exact division by 3, which is done by a specialized1914// linear-time algorithm.1915t2 = v2.subtract(vm1).exactDivideBy3();1916tm1 = v1.subtract(vm1).shiftRight(1);1917t1 = v1.subtract(v0);1918t2 = t2.subtract(t1).shiftRight(1);1919t1 = t1.subtract(tm1).subtract(vinf);1920t2 = t2.subtract(vinf.shiftLeft(1));1921tm1 = tm1.subtract(t2);19221923// Number of bits to shift left.1924int ss = k*32;19251926BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);19271928if (a.signum != b.signum) {1929return result.negate();1930} else {1931return result;1932}1933}193419351936/**1937* Returns a slice of a BigInteger for use in Toom-Cook multiplication.1938*1939* @param lowerSize The size of the lower-order bit slices.1940* @param upperSize The size of the higher-order bit slices.1941* @param slice The index of which slice is requested, which must be a1942* number from 0 to size-1. Slice 0 is the highest-order bits, and slice1943* size-1 are the lowest-order bits. Slice 0 may be of different size than1944* the other slices.1945* @param fullsize The size of the larger integer array, used to align1946* slices to the appropriate position when multiplying different-sized1947* numbers.1948*/1949private BigInteger getToomSlice(int lowerSize, int upperSize, int slice,1950int fullsize) {1951int start, end, sliceSize, len, offset;19521953len = mag.length;1954offset = fullsize - len;19551956if (slice == 0) {1957start = 0 - offset;1958end = upperSize - 1 - offset;1959} else {1960start = upperSize + (slice-1)*lowerSize - offset;1961end = start + lowerSize - 1;1962}19631964if (start < 0) {1965start = 0;1966}1967if (end < 0) {1968return ZERO;1969}19701971sliceSize = (end-start) + 1;19721973if (sliceSize <= 0) {1974return ZERO;1975}19761977// While performing Toom-Cook, all slices are positive and1978// the sign is adjusted when the final number is composed.1979if (start == 0 && sliceSize >= len) {1980return this.abs();1981}19821983int intSlice[] = new int[sliceSize];1984System.arraycopy(mag, start, intSlice, 0, sliceSize);19851986return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1);1987}19881989/**1990* Does an exact division (that is, the remainder is known to be zero)1991* of the specified number by 3. This is used in Toom-Cook1992* multiplication. This is an efficient algorithm that runs in linear1993* time. If the argument is not exactly divisible by 3, results are1994* undefined. Note that this is expected to be called with positive1995* arguments only.1996*/1997private BigInteger exactDivideBy3() {1998int len = mag.length;1999int[] result = new int[len];2000long x, w, q, borrow;2001borrow = 0L;2002for (int i=len-1; i >= 0; i--) {2003x = (mag[i] & LONG_MASK);2004w = x - borrow;2005if (borrow > x) { // Did we make the number go negative?2006borrow = 1L;2007} else {2008borrow = 0L;2009}20102011// 0xAAAAAAAB is the modular inverse of 3 (mod 2^32). Thus,2012// the effect of this is to divide by 3 (mod 2^32).2013// This is much faster than division on most architectures.2014q = (w * 0xAAAAAAABL) & LONG_MASK;2015result[i] = (int) q;20162017// Now check the borrow. The second check can of course be2018// eliminated if the first fails.2019if (q >= 0x55555556L) {2020borrow++;2021if (q >= 0xAAAAAAABL)2022borrow++;2023}2024}2025result = trustedStripLeadingZeroInts(result);2026return new BigInteger(result, signum);2027}20282029/**2030* Returns a new BigInteger representing n lower ints of the number.2031* This is used by Karatsuba multiplication and Karatsuba squaring.2032*/2033private BigInteger getLower(int n) {2034int len = mag.length;20352036if (len <= n) {2037return abs();2038}20392040int lowerInts[] = new int[n];2041System.arraycopy(mag, len-n, lowerInts, 0, n);20422043return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);2044}20452046/**2047* Returns a new BigInteger representing mag.length-n upper2048* ints of the number. This is used by Karatsuba multiplication and2049* Karatsuba squaring.2050*/2051private BigInteger getUpper(int n) {2052int len = mag.length;20532054if (len <= n) {2055return ZERO;2056}20572058int upperLen = len - n;2059int upperInts[] = new int[upperLen];2060System.arraycopy(mag, 0, upperInts, 0, upperLen);20612062return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1);2063}20642065// Squaring20662067/**2068* Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.2069*2070* @return {@code this<sup>2</sup>}2071*/2072private BigInteger square() {2073return square(false);2074}20752076/**2077* Returns a BigInteger whose value is {@code (this<sup>2</sup>)}. If2078* the invocation is recursive certain overflow checks are skipped.2079*2080* @param isRecursion whether this is a recursive invocation2081* @return {@code this<sup>2</sup>}2082*/2083private BigInteger square(boolean isRecursion) {2084if (signum == 0) {2085return ZERO;2086}2087int len = mag.length;20882089if (len < KARATSUBA_SQUARE_THRESHOLD) {2090int[] z = squareToLen(mag, len, null);2091return new BigInteger(trustedStripLeadingZeroInts(z), 1);2092} else {2093if (len < TOOM_COOK_SQUARE_THRESHOLD) {2094return squareKaratsuba();2095} else {2096//2097// For a discussion of overflow detection see multiply()2098//2099if (!isRecursion) {2100if (bitLength(mag, mag.length) > 16L*MAX_MAG_LENGTH) {2101reportOverflow();2102}2103}21042105return squareToomCook3();2106}2107}2108}21092110/**2111* Squares the contents of the int array x. The result is placed into the2112* int array z. The contents of x are not changed.2113*/2114private static final int[] squareToLen(int[] x, int len, int[] z) {2115int zlen = len << 1;2116if (z == null || z.length < zlen)2117z = new int[zlen];21182119// Execute checks before calling intrinsified method.2120implSquareToLenChecks(x, len, z, zlen);2121return implSquareToLen(x, len, z, zlen);2122}21232124/**2125* Parameters validation.2126*/2127private static void implSquareToLenChecks(int[] x, int len, int[] z, int zlen) throws RuntimeException {2128if (len < 1) {2129throw new IllegalArgumentException("invalid input length: " + len);2130}2131if (len > x.length) {2132throw new IllegalArgumentException("input length out of bound: " +2133len + " > " + x.length);2134}2135if (len * 2 > z.length) {2136throw new IllegalArgumentException("input length out of bound: " +2137(len * 2) + " > " + z.length);2138}2139if (zlen < 1) {2140throw new IllegalArgumentException("invalid input length: " + zlen);2141}2142if (zlen > z.length) {2143throw new IllegalArgumentException("input length out of bound: " +2144len + " > " + z.length);2145}2146}21472148/**2149* Java Runtime may use intrinsic for this method.2150*/2151@IntrinsicCandidate2152private static final int[] implSquareToLen(int[] x, int len, int[] z, int zlen) {2153/*2154* The algorithm used here is adapted from Colin Plumb's C library.2155* Technique: Consider the partial products in the multiplication2156* of "abcde" by itself:2157*2158* a b c d e2159* * a b c d e2160* ==================2161* ae be ce de ee2162* ad bd cd dd de2163* ac bc cc cd ce2164* ab bb bc bd be2165* aa ab ac ad ae2166*2167* Note that everything above the main diagonal:2168* ae be ce de = (abcd) * e2169* ad bd cd = (abc) * d2170* ac bc = (ab) * c2171* ab = (a) * b2172*2173* is a copy of everything below the main diagonal:2174* de2175* cd ce2176* bc bd be2177* ab ac ad ae2178*2179* Thus, the sum is 2 * (off the diagonal) + diagonal.2180*2181* This is accumulated beginning with the diagonal (which2182* consist of the squares of the digits of the input), which is then2183* divided by two, the off-diagonal added, and multiplied by two2184* again. The low bit is simply a copy of the low bit of the2185* input, so it doesn't need special care.2186*/21872188// Store the squares, right shifted one bit (i.e., divided by 2)2189int lastProductLowWord = 0;2190for (int j=0, i=0; j < len; j++) {2191long piece = (x[j] & LONG_MASK);2192long product = piece * piece;2193z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);2194z[i++] = (int)(product >>> 1);2195lastProductLowWord = (int)product;2196}21972198// Add in off-diagonal sums2199for (int i=len, offset=1; i > 0; i--, offset+=2) {2200int t = x[i-1];2201t = mulAdd(z, x, offset, i-1, t);2202addOne(z, offset-1, i, t);2203}22042205// Shift back up and set low bit2206primitiveLeftShift(z, zlen, 1);2207z[zlen-1] |= x[len-1] & 1;22082209return z;2210}22112212/**2213* Squares a BigInteger using the Karatsuba squaring algorithm. It should2214* be used when both numbers are larger than a certain threshold (found2215* experimentally). It is a recursive divide-and-conquer algorithm that2216* has better asymptotic performance than the algorithm used in2217* squareToLen.2218*/2219private BigInteger squareKaratsuba() {2220int half = (mag.length+1) / 2;22212222BigInteger xl = getLower(half);2223BigInteger xh = getUpper(half);22242225BigInteger xhs = xh.square(); // xhs = xh^22226BigInteger xls = xl.square(); // xls = xl^222272228// xh^2 << 64 + (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^22229return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls);2230}22312232/**2233* Squares a BigInteger using the 3-way Toom-Cook squaring algorithm. It2234* should be used when both numbers are larger than a certain threshold2235* (found experimentally). It is a recursive divide-and-conquer algorithm2236* that has better asymptotic performance than the algorithm used in2237* squareToLen or squareKaratsuba.2238*/2239private BigInteger squareToomCook3() {2240int len = mag.length;22412242// k is the size (in ints) of the lower-order slices.2243int k = (len+2)/3; // Equal to ceil(largest/3)22442245// r is the size (in ints) of the highest-order slice.2246int r = len - 2*k;22472248// Obtain slices of the numbers. a2 is the most significant2249// bits of the number, and a0 the least significant.2250BigInteger a0, a1, a2;2251a2 = getToomSlice(k, r, 0, len);2252a1 = getToomSlice(k, r, 1, len);2253a0 = getToomSlice(k, r, 2, len);2254BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;22552256v0 = a0.square(true);2257da1 = a2.add(a0);2258vm1 = da1.subtract(a1).square(true);2259da1 = da1.add(a1);2260v1 = da1.square(true);2261vinf = a2.square(true);2262v2 = da1.add(a2).shiftLeft(1).subtract(a0).square(true);22632264// The algorithm requires two divisions by 2 and one by 3.2265// All divisions are known to be exact, that is, they do not produce2266// remainders, and all results are positive. The divisions by 2 are2267// implemented as right shifts which are relatively efficient, leaving2268// only a division by 3.2269// The division by 3 is done by an optimized algorithm for this case.2270t2 = v2.subtract(vm1).exactDivideBy3();2271tm1 = v1.subtract(vm1).shiftRight(1);2272t1 = v1.subtract(v0);2273t2 = t2.subtract(t1).shiftRight(1);2274t1 = t1.subtract(tm1).subtract(vinf);2275t2 = t2.subtract(vinf.shiftLeft(1));2276tm1 = tm1.subtract(t2);22772278// Number of bits to shift left.2279int ss = k*32;22802281return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);2282}22832284// Division22852286/**2287* Returns a BigInteger whose value is {@code (this / val)}.2288*2289* @param val value by which this BigInteger is to be divided.2290* @return {@code this / val}2291* @throws ArithmeticException if {@code val} is zero.2292*/2293public BigInteger divide(BigInteger val) {2294if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||2295mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {2296return divideKnuth(val);2297} else {2298return divideBurnikelZiegler(val);2299}2300}23012302/**2303* Returns a BigInteger whose value is {@code (this / val)} using an O(n^2) algorithm from Knuth.2304*2305* @param val value by which this BigInteger is to be divided.2306* @return {@code this / val}2307* @throws ArithmeticException if {@code val} is zero.2308* @see MutableBigInteger#divideKnuth(MutableBigInteger, MutableBigInteger, boolean)2309*/2310private BigInteger divideKnuth(BigInteger val) {2311MutableBigInteger q = new MutableBigInteger(),2312a = new MutableBigInteger(this.mag),2313b = new MutableBigInteger(val.mag);23142315a.divideKnuth(b, q, false);2316return q.toBigInteger(this.signum * val.signum);2317}23182319/**2320* Returns an array of two BigIntegers containing {@code (this / val)}2321* followed by {@code (this % val)}.2322*2323* @param val value by which this BigInteger is to be divided, and the2324* remainder computed.2325* @return an array of two BigIntegers: the quotient {@code (this / val)}2326* is the initial element, and the remainder {@code (this % val)}2327* is the final element.2328* @throws ArithmeticException if {@code val} is zero.2329*/2330public BigInteger[] divideAndRemainder(BigInteger val) {2331if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||2332mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {2333return divideAndRemainderKnuth(val);2334} else {2335return divideAndRemainderBurnikelZiegler(val);2336}2337}23382339/** Long division */2340private BigInteger[] divideAndRemainderKnuth(BigInteger val) {2341BigInteger[] result = new BigInteger[2];2342MutableBigInteger q = new MutableBigInteger(),2343a = new MutableBigInteger(this.mag),2344b = new MutableBigInteger(val.mag);2345MutableBigInteger r = a.divideKnuth(b, q);2346result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);2347result[1] = r.toBigInteger(this.signum);2348return result;2349}23502351/**2352* Returns a BigInteger whose value is {@code (this % val)}.2353*2354* @param val value by which this BigInteger is to be divided, and the2355* remainder computed.2356* @return {@code this % val}2357* @throws ArithmeticException if {@code val} is zero.2358*/2359public BigInteger remainder(BigInteger val) {2360if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||2361mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {2362return remainderKnuth(val);2363} else {2364return remainderBurnikelZiegler(val);2365}2366}23672368/** Long division */2369private BigInteger remainderKnuth(BigInteger val) {2370MutableBigInteger q = new MutableBigInteger(),2371a = new MutableBigInteger(this.mag),2372b = new MutableBigInteger(val.mag);23732374return a.divideKnuth(b, q).toBigInteger(this.signum);2375}23762377/**2378* Calculates {@code this / val} using the Burnikel-Ziegler algorithm.2379* @param val the divisor2380* @return {@code this / val}2381*/2382private BigInteger divideBurnikelZiegler(BigInteger val) {2383return divideAndRemainderBurnikelZiegler(val)[0];2384}23852386/**2387* Calculates {@code this % val} using the Burnikel-Ziegler algorithm.2388* @param val the divisor2389* @return {@code this % val}2390*/2391private BigInteger remainderBurnikelZiegler(BigInteger val) {2392return divideAndRemainderBurnikelZiegler(val)[1];2393}23942395/**2396* Computes {@code this / val} and {@code this % val} using the2397* Burnikel-Ziegler algorithm.2398* @param val the divisor2399* @return an array containing the quotient and remainder2400*/2401private BigInteger[] divideAndRemainderBurnikelZiegler(BigInteger val) {2402MutableBigInteger q = new MutableBigInteger();2403MutableBigInteger r = new MutableBigInteger(this).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q);2404BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum);2405BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum);2406return new BigInteger[] {qBigInt, rBigInt};2407}24082409/**2410* Returns a BigInteger whose value is <code>(this<sup>exponent</sup>)</code>.2411* Note that {@code exponent} is an integer rather than a BigInteger.2412*2413* @param exponent exponent to which this BigInteger is to be raised.2414* @return <code>this<sup>exponent</sup></code>2415* @throws ArithmeticException {@code exponent} is negative. (This would2416* cause the operation to yield a non-integer value.)2417*/2418public BigInteger pow(int exponent) {2419if (exponent < 0) {2420throw new ArithmeticException("Negative exponent");2421}2422if (signum == 0) {2423return (exponent == 0 ? ONE : this);2424}24252426BigInteger partToSquare = this.abs();24272428// Factor out powers of two from the base, as the exponentiation of2429// these can be done by left shifts only.2430// The remaining part can then be exponentiated faster. The2431// powers of two will be multiplied back at the end.2432int powersOfTwo = partToSquare.getLowestSetBit();2433long bitsToShiftLong = (long)powersOfTwo * exponent;2434if (bitsToShiftLong > Integer.MAX_VALUE) {2435reportOverflow();2436}2437int bitsToShift = (int)bitsToShiftLong;24382439int remainingBits;24402441// Factor the powers of two out quickly by shifting right, if needed.2442if (powersOfTwo > 0) {2443partToSquare = partToSquare.shiftRight(powersOfTwo);2444remainingBits = partToSquare.bitLength();2445if (remainingBits == 1) { // Nothing left but +/- 1?2446if (signum < 0 && (exponent&1) == 1) {2447return NEGATIVE_ONE.shiftLeft(bitsToShift);2448} else {2449return ONE.shiftLeft(bitsToShift);2450}2451}2452} else {2453remainingBits = partToSquare.bitLength();2454if (remainingBits == 1) { // Nothing left but +/- 1?2455if (signum < 0 && (exponent&1) == 1) {2456return NEGATIVE_ONE;2457} else {2458return ONE;2459}2460}2461}24622463// This is a quick way to approximate the size of the result,2464// similar to doing log2[n] * exponent. This will give an upper bound2465// of how big the result can be, and which algorithm to use.2466long scaleFactor = (long)remainingBits * exponent;24672468// Use slightly different algorithms for small and large operands.2469// See if the result will safely fit into a long. (Largest 2^63-1)2470if (partToSquare.mag.length == 1 && scaleFactor <= 62) {2471// Small number algorithm. Everything fits into a long.2472int newSign = (signum <0 && (exponent&1) == 1 ? -1 : 1);2473long result = 1;2474long baseToPow2 = partToSquare.mag[0] & LONG_MASK;24752476int workingExponent = exponent;24772478// Perform exponentiation using repeated squaring trick2479while (workingExponent != 0) {2480if ((workingExponent & 1) == 1) {2481result = result * baseToPow2;2482}24832484if ((workingExponent >>>= 1) != 0) {2485baseToPow2 = baseToPow2 * baseToPow2;2486}2487}24882489// Multiply back the powers of two (quickly, by shifting left)2490if (powersOfTwo > 0) {2491if (bitsToShift + scaleFactor <= 62) { // Fits in long?2492return valueOf((result << bitsToShift) * newSign);2493} else {2494return valueOf(result*newSign).shiftLeft(bitsToShift);2495}2496} else {2497return valueOf(result*newSign);2498}2499} else {2500if ((long)bitLength() * exponent / Integer.SIZE > MAX_MAG_LENGTH) {2501reportOverflow();2502}25032504// Large number algorithm. This is basically identical to2505// the algorithm above, but calls multiply() and square()2506// which may use more efficient algorithms for large numbers.2507BigInteger answer = ONE;25082509int workingExponent = exponent;2510// Perform exponentiation using repeated squaring trick2511while (workingExponent != 0) {2512if ((workingExponent & 1) == 1) {2513answer = answer.multiply(partToSquare);2514}25152516if ((workingExponent >>>= 1) != 0) {2517partToSquare = partToSquare.square();2518}2519}2520// Multiply back the (exponentiated) powers of two (quickly,2521// by shifting left)2522if (powersOfTwo > 0) {2523answer = answer.shiftLeft(bitsToShift);2524}25252526if (signum < 0 && (exponent&1) == 1) {2527return answer.negate();2528} else {2529return answer;2530}2531}2532}25332534/**2535* Returns the integer square root of this BigInteger. The integer square2536* root of the corresponding mathematical integer {@code n} is the largest2537* mathematical integer {@code s} such that {@code s*s <= n}. It is equal2538* to the value of {@code floor(sqrt(n))}, where {@code sqrt(n)} denotes the2539* real square root of {@code n} treated as a real. Note that the integer2540* square root will be less than the real square root if the latter is not2541* representable as an integral value.2542*2543* @return the integer square root of {@code this}2544* @throws ArithmeticException if {@code this} is negative. (The square2545* root of a negative integer {@code val} is2546* {@code (i * sqrt(-val))} where <i>i</i> is the2547* <i>imaginary unit</i> and is equal to2548* {@code sqrt(-1)}.)2549* @since 92550*/2551public BigInteger sqrt() {2552if (this.signum < 0) {2553throw new ArithmeticException("Negative BigInteger");2554}25552556return new MutableBigInteger(this.mag).sqrt().toBigInteger();2557}25582559/**2560* Returns an array of two BigIntegers containing the integer square root2561* {@code s} of {@code this} and its remainder {@code this - s*s},2562* respectively.2563*2564* @return an array of two BigIntegers with the integer square root at2565* offset 0 and the remainder at offset 12566* @throws ArithmeticException if {@code this} is negative. (The square2567* root of a negative integer {@code val} is2568* {@code (i * sqrt(-val))} where <i>i</i> is the2569* <i>imaginary unit</i> and is equal to2570* {@code sqrt(-1)}.)2571* @see #sqrt()2572* @since 92573*/2574public BigInteger[] sqrtAndRemainder() {2575BigInteger s = sqrt();2576BigInteger r = this.subtract(s.square());2577assert r.compareTo(BigInteger.ZERO) >= 0;2578return new BigInteger[] {s, r};2579}25802581/**2582* Returns a BigInteger whose value is the greatest common divisor of2583* {@code abs(this)} and {@code abs(val)}. Returns 0 if2584* {@code this == 0 && val == 0}.2585*2586* @param val value with which the GCD is to be computed.2587* @return {@code GCD(abs(this), abs(val))}2588*/2589public BigInteger gcd(BigInteger val) {2590if (val.signum == 0)2591return this.abs();2592else if (this.signum == 0)2593return val.abs();25942595MutableBigInteger a = new MutableBigInteger(this);2596MutableBigInteger b = new MutableBigInteger(val);25972598MutableBigInteger result = a.hybridGCD(b);25992600return result.toBigInteger(1);2601}26022603/**2604* Package private method to return bit length for an integer.2605*/2606static int bitLengthForInt(int n) {2607return 32 - Integer.numberOfLeadingZeros(n);2608}26092610/**2611* Left shift int array a up to len by n bits. Returns the array that2612* results from the shift since space may have to be reallocated.2613*/2614private static int[] leftShift(int[] a, int len, int n) {2615int nInts = n >>> 5;2616int nBits = n&0x1F;2617int bitsInHighWord = bitLengthForInt(a[0]);26182619// If shift can be done without recopy, do so2620if (n <= (32-bitsInHighWord)) {2621primitiveLeftShift(a, len, nBits);2622return a;2623} else { // Array must be resized2624if (nBits <= (32-bitsInHighWord)) {2625int result[] = new int[nInts+len];2626System.arraycopy(a, 0, result, 0, len);2627primitiveLeftShift(result, result.length, nBits);2628return result;2629} else {2630int result[] = new int[nInts+len+1];2631System.arraycopy(a, 0, result, 0, len);2632primitiveRightShift(result, result.length, 32 - nBits);2633return result;2634}2635}2636}26372638// shifts a up to len right n bits assumes no leading zeros, 0<n<322639static void primitiveRightShift(int[] a, int len, int n) {2640Objects.checkFromToIndex(0, len, a.length);2641shiftRightImplWorker(a, a, 1, n, len-1);2642a[0] >>>= n;2643}26442645// shifts a up to len left n bits assumes no leading zeros, 0<=n<322646static void primitiveLeftShift(int[] a, int len, int n) {2647if (len == 0 || n == 0)2648return;2649Objects.checkFromToIndex(0, len, a.length);2650shiftLeftImplWorker(a, a, 0, n, len-1);2651a[len-1] <<= n;2652}26532654/**2655* Calculate bitlength of contents of the first len elements an int array,2656* assuming there are no leading zero ints.2657*/2658private static int bitLength(int[] val, int len) {2659if (len == 0)2660return 0;2661return ((len - 1) << 5) + bitLengthForInt(val[0]);2662}26632664/**2665* Returns a BigInteger whose value is the absolute value of this2666* BigInteger.2667*2668* @return {@code abs(this)}2669*/2670public BigInteger abs() {2671return (signum >= 0 ? this : this.negate());2672}26732674/**2675* Returns a BigInteger whose value is {@code (-this)}.2676*2677* @return {@code -this}2678*/2679public BigInteger negate() {2680return new BigInteger(this.mag, -this.signum);2681}26822683/**2684* Returns the signum function of this BigInteger.2685*2686* @return -1, 0 or 1 as the value of this BigInteger is negative, zero or2687* positive.2688*/2689public int signum() {2690return this.signum;2691}26922693// Modular Arithmetic Operations26942695/**2696* Returns a BigInteger whose value is {@code (this mod m}). This method2697* differs from {@code remainder} in that it always returns a2698* <i>non-negative</i> BigInteger.2699*2700* @param m the modulus.2701* @return {@code this mod m}2702* @throws ArithmeticException {@code m} ≤ 02703* @see #remainder2704*/2705public BigInteger mod(BigInteger m) {2706if (m.signum <= 0)2707throw new ArithmeticException("BigInteger: modulus not positive");27082709BigInteger result = this.remainder(m);2710return (result.signum >= 0 ? result : result.add(m));2711}27122713/**2714* Returns a BigInteger whose value is2715* <code>(this<sup>exponent</sup> mod m)</code>. (Unlike {@code pow}, this2716* method permits negative exponents.)2717*2718* @param exponent the exponent.2719* @param m the modulus.2720* @return <code>this<sup>exponent</sup> mod m</code>2721* @throws ArithmeticException {@code m} ≤ 0 or the exponent is2722* negative and this BigInteger is not <i>relatively2723* prime</i> to {@code m}.2724* @see #modInverse2725*/2726public BigInteger modPow(BigInteger exponent, BigInteger m) {2727if (m.signum <= 0)2728throw new ArithmeticException("BigInteger: modulus not positive");27292730// Trivial cases2731if (exponent.signum == 0)2732return (m.equals(ONE) ? ZERO : ONE);27332734if (this.equals(ONE))2735return (m.equals(ONE) ? ZERO : ONE);27362737if (this.equals(ZERO) && exponent.signum >= 0)2738return ZERO;27392740if (this.equals(negConst[1]) && (!exponent.testBit(0)))2741return (m.equals(ONE) ? ZERO : ONE);27422743boolean invertResult;2744if ((invertResult = (exponent.signum < 0)))2745exponent = exponent.negate();27462747BigInteger base = (this.signum < 0 || this.compareTo(m) >= 02748? this.mod(m) : this);2749BigInteger result;2750if (m.testBit(0)) { // odd modulus2751result = base.oddModPow(exponent, m);2752} else {2753/*2754* Even modulus. Tear it into an "odd part" (m1) and power of two2755* (m2), exponentiate mod m1, manually exponentiate mod m2, and2756* use Chinese Remainder Theorem to combine results.2757*/27582759// Tear m apart into odd part (m1) and power of 2 (m2)2760int p = m.getLowestSetBit(); // Max pow of 2 that divides m27612762BigInteger m1 = m.shiftRight(p); // m/2**p2763BigInteger m2 = ONE.shiftLeft(p); // 2**p27642765// Calculate new base from m12766BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 02767? this.mod(m1) : this);27682769// Calculate (base ** exponent) mod m1.2770BigInteger a1 = (m1.equals(ONE) ? ZERO :2771base2.oddModPow(exponent, m1));27722773// Calculate (this ** exponent) mod m22774BigInteger a2 = base.modPow2(exponent, p);27752776// Combine results using Chinese Remainder Theorem2777BigInteger y1 = m2.modInverse(m1);2778BigInteger y2 = m1.modInverse(m2);27792780if (m.mag.length < MAX_MAG_LENGTH / 2) {2781result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);2782} else {2783MutableBigInteger t1 = new MutableBigInteger();2784new MutableBigInteger(a1.multiply(m2)).multiply(new MutableBigInteger(y1), t1);2785MutableBigInteger t2 = new MutableBigInteger();2786new MutableBigInteger(a2.multiply(m1)).multiply(new MutableBigInteger(y2), t2);2787t1.add(t2);2788MutableBigInteger q = new MutableBigInteger();2789result = t1.divide(new MutableBigInteger(m), q).toBigInteger();2790}2791}27922793return (invertResult ? result.modInverse(m) : result);2794}27952796// Montgomery multiplication. These are wrappers for2797// implMontgomeryXX routines which are expected to be replaced by2798// virtual machine intrinsics. We don't use the intrinsics for2799// very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be2800// larger than any reasonable crypto key.2801private static int[] montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv,2802int[] product) {2803implMontgomeryMultiplyChecks(a, b, n, len, product);2804if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {2805// Very long argument: do not use an intrinsic2806product = multiplyToLen(a, len, b, len, product);2807return montReduce(product, n, len, (int)inv);2808} else {2809return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len));2810}2811}2812private static int[] montgomerySquare(int[] a, int[] n, int len, long inv,2813int[] product) {2814implMontgomeryMultiplyChecks(a, a, n, len, product);2815if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {2816// Very long argument: do not use an intrinsic2817product = squareToLen(a, len, product);2818return montReduce(product, n, len, (int)inv);2819} else {2820return implMontgomerySquare(a, n, len, inv, materialize(product, len));2821}2822}28232824// Range-check everything.2825private static void implMontgomeryMultiplyChecks2826(int[] a, int[] b, int[] n, int len, int[] product) throws RuntimeException {2827if (len % 2 != 0) {2828throw new IllegalArgumentException("input array length must be even: " + len);2829}28302831if (len < 1) {2832throw new IllegalArgumentException("invalid input length: " + len);2833}28342835if (len > a.length ||2836len > b.length ||2837len > n.length ||2838(product != null && len > product.length)) {2839throw new IllegalArgumentException("input array length out of bound: " + len);2840}2841}28422843// Make sure that the int array z (which is expected to contain2844// the result of a Montgomery multiplication) is present and2845// sufficiently large.2846private static int[] materialize(int[] z, int len) {2847if (z == null || z.length < len)2848z = new int[len];2849return z;2850}28512852// These methods are intended to be replaced by virtual machine2853// intrinsics.2854@IntrinsicCandidate2855private static int[] implMontgomeryMultiply(int[] a, int[] b, int[] n, int len,2856long inv, int[] product) {2857product = multiplyToLen(a, len, b, len, product);2858return montReduce(product, n, len, (int)inv);2859}2860@IntrinsicCandidate2861private static int[] implMontgomerySquare(int[] a, int[] n, int len,2862long inv, int[] product) {2863product = squareToLen(a, len, product);2864return montReduce(product, n, len, (int)inv);2865}28662867static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,2868Integer.MAX_VALUE}; // Sentinel28692870/**2871* Returns a BigInteger whose value is x to the power of y mod z.2872* Assumes: z is odd && x < z.2873*/2874private BigInteger oddModPow(BigInteger y, BigInteger z) {2875/*2876* The algorithm is adapted from Colin Plumb's C library.2877*2878* The window algorithm:2879* The idea is to keep a running product of b1 = n^(high-order bits of exp)2880* and then keep appending exponent bits to it. The following patterns2881* apply to a 3-bit window (k = 3):2882* To append 0: square2883* To append 1: square, multiply by n^12884* To append 10: square, multiply by n^1, square2885* To append 11: square, square, multiply by n^32886* To append 100: square, multiply by n^1, square, square2887* To append 101: square, square, square, multiply by n^52888* To append 110: square, square, multiply by n^3, square2889* To append 111: square, square, square, multiply by n^72890*2891* Since each pattern involves only one multiply, the longer the pattern2892* the better, except that a 0 (no multiplies) can be appended directly.2893* We precompute a table of odd powers of n, up to 2^k, and can then2894* multiply k bits of exponent at a time. Actually, assuming random2895* exponents, there is on average one zero bit between needs to2896* multiply (1/2 of the time there's none, 1/4 of the time there's 1,2897* 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so2898* you have to do one multiply per k+1 bits of exponent.2899*2900* The loop walks down the exponent, squaring the result buffer as2901* it goes. There is a wbits+1 bit lookahead buffer, buf, that is2902* filled with the upcoming exponent bits. (What is read after the2903* end of the exponent is unimportant, but it is filled with zero here.)2904* When the most-significant bit of this buffer becomes set, i.e.2905* (buf & tblmask) != 0, we have to decide what pattern to multiply2906* by, and when to do it. We decide, remember to do it in future2907* after a suitable number of squarings have passed (e.g. a pattern2908* of "100" in the buffer requires that we multiply by n^1 immediately;2909* a pattern of "110" calls for multiplying by n^3 after one more2910* squaring), clear the buffer, and continue.2911*2912* When we start, there is one more optimization: the result buffer2913* is implcitly one, so squaring it or multiplying by it can be2914* optimized away. Further, if we start with a pattern like "100"2915* in the lookahead window, rather than placing n into the buffer2916* and then starting to square it, we have already computed n^22917* to compute the odd-powers table, so we can place that into2918* the buffer and save a squaring.2919*2920* This means that if you have a k-bit window, to compute n^z,2921* where z is the high k bits of the exponent, 1/2 of the time2922* it requires no squarings. 1/4 of the time, it requires 12923* squaring, ... 1/2^(k-1) of the time, it requires k-2 squarings.2924* And the remaining 1/2^(k-1) of the time, the top k bits are a2925* 1 followed by k-1 0 bits, so it again only requires k-22926* squarings, not k-1. The average of these is 1. Add that2927* to the one squaring we have to do to compute the table,2928* and you'll see that a k-bit window saves k-2 squarings2929* as well as reducing the multiplies. (It actually doesn't2930* hurt in the case k = 1, either.)2931*/2932// Special case for exponent of one2933if (y.equals(ONE))2934return this;29352936// Special case for base of zero2937if (signum == 0)2938return ZERO;29392940int[] base = mag.clone();2941int[] exp = y.mag;2942int[] mod = z.mag;2943int modLen = mod.length;29442945// Make modLen even. It is conventional to use a cryptographic2946// modulus that is 512, 768, 1024, or 2048 bits, so this code2947// will not normally be executed. However, it is necessary for2948// the correct functioning of the HotSpot intrinsics.2949if ((modLen & 1) != 0) {2950int[] x = new int[modLen + 1];2951System.arraycopy(mod, 0, x, 1, modLen);2952mod = x;2953modLen++;2954}29552956// Select an appropriate window size2957int wbits = 0;2958int ebits = bitLength(exp, exp.length);2959// if exponent is 65537 (0x10001), use minimum window size2960if ((ebits != 17) || (exp[0] != 65537)) {2961while (ebits > bnExpModThreshTable[wbits]) {2962wbits++;2963}2964}29652966// Calculate appropriate table size2967int tblmask = 1 << wbits;29682969// Allocate table for precomputed odd powers of base in Montgomery form2970int[][] table = new int[tblmask][];2971for (int i=0; i < tblmask; i++)2972table[i] = new int[modLen];29732974// Compute the modular inverse of the least significant 64-bit2975// digit of the modulus2976long n0 = (mod[modLen-1] & LONG_MASK) + ((mod[modLen-2] & LONG_MASK) << 32);2977long inv = -MutableBigInteger.inverseMod64(n0);29782979// Convert base to Montgomery form2980int[] a = leftShift(base, base.length, modLen << 5);29812982MutableBigInteger q = new MutableBigInteger(),2983a2 = new MutableBigInteger(a),2984b2 = new MutableBigInteger(mod);2985b2.normalize(); // MutableBigInteger.divide() assumes that its2986// divisor is in normal form.29872988MutableBigInteger r= a2.divide(b2, q);2989table[0] = r.toIntArray();29902991// Pad table[0] with leading zeros so its length is at least modLen2992if (table[0].length < modLen) {2993int offset = modLen - table[0].length;2994int[] t2 = new int[modLen];2995System.arraycopy(table[0], 0, t2, offset, table[0].length);2996table[0] = t2;2997}29982999// Set b to the square of the base3000int[] b = montgomerySquare(table[0], mod, modLen, inv, null);30013002// Set t to high half of b3003int[] t = Arrays.copyOf(b, modLen);30043005// Fill in the table with odd powers of the base3006for (int i=1; i < tblmask; i++) {3007table[i] = montgomeryMultiply(t, table[i-1], mod, modLen, inv, null);3008}30093010// Pre load the window that slides over the exponent3011int bitpos = 1 << ((ebits-1) & (32-1));30123013int buf = 0;3014int elen = exp.length;3015int eIndex = 0;3016for (int i = 0; i <= wbits; i++) {3017buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);3018bitpos >>>= 1;3019if (bitpos == 0) {3020eIndex++;3021bitpos = 1 << (32-1);3022elen--;3023}3024}30253026int multpos = ebits;30273028// The first iteration, which is hoisted out of the main loop3029ebits--;3030boolean isone = true;30313032multpos = ebits - wbits;3033while ((buf & 1) == 0) {3034buf >>>= 1;3035multpos++;3036}30373038int[] mult = table[buf >>> 1];30393040buf = 0;3041if (multpos == ebits)3042isone = false;30433044// The main loop3045while (true) {3046ebits--;3047// Advance the window3048buf <<= 1;30493050if (elen != 0) {3051buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;3052bitpos >>>= 1;3053if (bitpos == 0) {3054eIndex++;3055bitpos = 1 << (32-1);3056elen--;3057}3058}30593060// Examine the window for pending multiplies3061if ((buf & tblmask) != 0) {3062multpos = ebits - wbits;3063while ((buf & 1) == 0) {3064buf >>>= 1;3065multpos++;3066}3067mult = table[buf >>> 1];3068buf = 0;3069}30703071// Perform multiply3072if (ebits == multpos) {3073if (isone) {3074b = mult.clone();3075isone = false;3076} else {3077t = b;3078a = montgomeryMultiply(t, mult, mod, modLen, inv, a);3079t = a; a = b; b = t;3080}3081}30823083// Check if done3084if (ebits == 0)3085break;30863087// Square the input3088if (!isone) {3089t = b;3090a = montgomerySquare(t, mod, modLen, inv, a);3091t = a; a = b; b = t;3092}3093}30943095// Convert result out of Montgomery form and return3096int[] t2 = new int[2*modLen];3097System.arraycopy(b, 0, t2, modLen, modLen);30983099b = montReduce(t2, mod, modLen, (int)inv);31003101t2 = Arrays.copyOf(b, modLen);31023103return new BigInteger(1, t2);3104}31053106/**3107* Montgomery reduce n, modulo mod. This reduces modulo mod and divides3108* by 2^(32*mlen). Adapted from Colin Plumb's C library.3109*/3110private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {3111int c=0;3112int len = mlen;3113int offset=0;31143115do {3116int nEnd = n[n.length-1-offset];3117int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);3118c += addOne(n, offset, mlen, carry);3119offset++;3120} while (--len > 0);31213122while (c > 0)3123c += subN(n, mod, mlen);31243125while (intArrayCmpToLen(n, mod, mlen) >= 0)3126subN(n, mod, mlen);31273128return n;3129}313031313132/*3133* Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,3134* equal to, or greater than arg2 up to length len.3135*/3136private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {3137for (int i=0; i < len; i++) {3138long b1 = arg1[i] & LONG_MASK;3139long b2 = arg2[i] & LONG_MASK;3140if (b1 < b2)3141return -1;3142if (b1 > b2)3143return 1;3144}3145return 0;3146}31473148/**3149* Subtracts two numbers of same length, returning borrow.3150*/3151private static int subN(int[] a, int[] b, int len) {3152long sum = 0;31533154while (--len >= 0) {3155sum = (a[len] & LONG_MASK) -3156(b[len] & LONG_MASK) + (sum >> 32);3157a[len] = (int)sum;3158}31593160return (int)(sum >> 32);3161}31623163/**3164* Multiply an array by one word k and add to result, return the carry3165*/3166static int mulAdd(int[] out, int[] in, int offset, int len, int k) {3167implMulAddCheck(out, in, offset, len, k);3168return implMulAdd(out, in, offset, len, k);3169}31703171/**3172* Parameters validation.3173*/3174private static void implMulAddCheck(int[] out, int[] in, int offset, int len, int k) {3175if (len > in.length) {3176throw new IllegalArgumentException("input length is out of bound: " + len + " > " + in.length);3177}3178if (offset < 0) {3179throw new IllegalArgumentException("input offset is invalid: " + offset);3180}3181if (offset > (out.length - 1)) {3182throw new IllegalArgumentException("input offset is out of bound: " + offset + " > " + (out.length - 1));3183}3184if (len > (out.length - offset)) {3185throw new IllegalArgumentException("input len is out of bound: " + len + " > " + (out.length - offset));3186}3187}31883189/**3190* Java Runtime may use intrinsic for this method.3191*/3192@IntrinsicCandidate3193private static int implMulAdd(int[] out, int[] in, int offset, int len, int k) {3194long kLong = k & LONG_MASK;3195long carry = 0;31963197offset = out.length-offset - 1;3198for (int j=len-1; j >= 0; j--) {3199long product = (in[j] & LONG_MASK) * kLong +3200(out[offset] & LONG_MASK) + carry;3201out[offset--] = (int)product;3202carry = product >>> 32;3203}3204return (int)carry;3205}32063207/**3208* Add one word to the number a mlen words into a. Return the resulting3209* carry.3210*/3211static int addOne(int[] a, int offset, int mlen, int carry) {3212offset = a.length-1-mlen-offset;3213long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);32143215a[offset] = (int)t;3216if ((t >>> 32) == 0)3217return 0;3218while (--mlen >= 0) {3219if (--offset < 0) { // Carry out of number3220return 1;3221} else {3222a[offset]++;3223if (a[offset] != 0)3224return 0;3225}3226}3227return 1;3228}32293230/**3231* Returns a BigInteger whose value is (this ** exponent) mod (2**p)3232*/3233private BigInteger modPow2(BigInteger exponent, int p) {3234/*3235* Perform exponentiation using repeated squaring trick, chopping off3236* high order bits as indicated by modulus.3237*/3238BigInteger result = ONE;3239BigInteger baseToPow2 = this.mod2(p);3240int expOffset = 0;32413242int limit = exponent.bitLength();32433244if (this.testBit(0))3245limit = (p-1) < limit ? (p-1) : limit;32463247while (expOffset < limit) {3248if (exponent.testBit(expOffset))3249result = result.multiply(baseToPow2).mod2(p);3250expOffset++;3251if (expOffset < limit)3252baseToPow2 = baseToPow2.square().mod2(p);3253}32543255return result;3256}32573258/**3259* Returns a BigInteger whose value is this mod(2**p).3260* Assumes that this {@code BigInteger >= 0} and {@code p > 0}.3261*/3262private BigInteger mod2(int p) {3263if (bitLength() <= p)3264return this;32653266// Copy remaining ints of mag3267int numInts = (p + 31) >>> 5;3268int[] mag = new int[numInts];3269System.arraycopy(this.mag, (this.mag.length - numInts), mag, 0, numInts);32703271// Mask out any excess bits3272int excessBits = (numInts << 5) - p;3273mag[0] &= (1L << (32-excessBits)) - 1;32743275return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));3276}32773278/**3279* Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}.3280*3281* @param m the modulus.3282* @return {@code this}<sup>-1</sup> {@code mod m}.3283* @throws ArithmeticException {@code m} ≤ 0, or this BigInteger3284* has no multiplicative inverse mod m (that is, this BigInteger3285* is not <i>relatively prime</i> to m).3286*/3287public BigInteger modInverse(BigInteger m) {3288if (m.signum != 1)3289throw new ArithmeticException("BigInteger: modulus not positive");32903291if (m.equals(ONE))3292return ZERO;32933294// Calculate (this mod m)3295BigInteger modVal = this;3296if (signum < 0 || (this.compareMagnitude(m) >= 0))3297modVal = this.mod(m);32983299if (modVal.equals(ONE))3300return ONE;33013302MutableBigInteger a = new MutableBigInteger(modVal);3303MutableBigInteger b = new MutableBigInteger(m);33043305MutableBigInteger result = a.mutableModInverse(b);3306return result.toBigInteger(1);3307}33083309// Shift Operations33103311/**3312* Returns a BigInteger whose value is {@code (this << n)}.3313* The shift distance, {@code n}, may be negative, in which case3314* this method performs a right shift.3315* (Computes <code>floor(this * 2<sup>n</sup>)</code>.)3316*3317* @param n shift distance, in bits.3318* @return {@code this << n}3319* @see #shiftRight3320*/3321public BigInteger shiftLeft(int n) {3322if (signum == 0)3323return ZERO;3324if (n > 0) {3325return new BigInteger(shiftLeft(mag, n), signum);3326} else if (n == 0) {3327return this;3328} else {3329// Possible int overflow in (-n) is not a trouble,3330// because shiftRightImpl considers its argument unsigned3331return shiftRightImpl(-n);3332}3333}33343335/**3336* Returns a magnitude array whose value is {@code (mag << n)}.3337* The shift distance, {@code n}, is considered unnsigned.3338* (Computes <code>this * 2<sup>n</sup></code>.)3339*3340* @param mag magnitude, the most-significant int ({@code mag[0]}) must be non-zero.3341* @param n unsigned shift distance, in bits.3342* @return {@code mag << n}3343*/3344private static int[] shiftLeft(int[] mag, int n) {3345int nInts = n >>> 5;3346int nBits = n & 0x1f;3347int magLen = mag.length;3348int newMag[] = null;33493350if (nBits == 0) {3351newMag = new int[magLen + nInts];3352System.arraycopy(mag, 0, newMag, 0, magLen);3353} else {3354int i = 0;3355int nBits2 = 32 - nBits;3356int highBits = mag[0] >>> nBits2;3357if (highBits != 0) {3358newMag = new int[magLen + nInts + 1];3359newMag[i++] = highBits;3360} else {3361newMag = new int[magLen + nInts];3362}3363int numIter = magLen - 1;3364Objects.checkFromToIndex(0, numIter + 1, mag.length);3365Objects.checkFromToIndex(i, numIter + i + 1, newMag.length);3366shiftLeftImplWorker(newMag, mag, i, nBits, numIter);3367newMag[numIter + i] = mag[numIter] << nBits;3368}3369return newMag;3370}33713372@ForceInline3373@IntrinsicCandidate3374private static void shiftLeftImplWorker(int[] newArr, int[] oldArr, int newIdx, int shiftCount, int numIter) {3375int shiftCountRight = 32 - shiftCount;3376int oldIdx = 0;3377while (oldIdx < numIter) {3378newArr[newIdx++] = (oldArr[oldIdx++] << shiftCount) | (oldArr[oldIdx] >>> shiftCountRight);3379}3380}33813382/**3383* Returns a BigInteger whose value is {@code (this >> n)}. Sign3384* extension is performed. The shift distance, {@code n}, may be3385* negative, in which case this method performs a left shift.3386* (Computes <code>floor(this / 2<sup>n</sup>)</code>.)3387*3388* @param n shift distance, in bits.3389* @return {@code this >> n}3390* @see #shiftLeft3391*/3392public BigInteger shiftRight(int n) {3393if (signum == 0)3394return ZERO;3395if (n > 0) {3396return shiftRightImpl(n);3397} else if (n == 0) {3398return this;3399} else {3400// Possible int overflow in {@code -n} is not a trouble,3401// because shiftLeft considers its argument unsigned3402return new BigInteger(shiftLeft(mag, -n), signum);3403}3404}34053406/**3407* Returns a BigInteger whose value is {@code (this >> n)}. The shift3408* distance, {@code n}, is considered unsigned.3409* (Computes <code>floor(this * 2<sup>-n</sup>)</code>.)3410*3411* @param n unsigned shift distance, in bits.3412* @return {@code this >> n}3413*/3414private BigInteger shiftRightImpl(int n) {3415int nInts = n >>> 5;3416int nBits = n & 0x1f;3417int magLen = mag.length;3418int newMag[] = null;34193420// Special case: entire contents shifted off the end3421if (nInts >= magLen)3422return (signum >= 0 ? ZERO : negConst[1]);34233424if (nBits == 0) {3425int newMagLen = magLen - nInts;3426newMag = Arrays.copyOf(mag, newMagLen);3427} else {3428int i = 0;3429int highBits = mag[0] >>> nBits;3430if (highBits != 0) {3431newMag = new int[magLen - nInts];3432newMag[i++] = highBits;3433} else {3434newMag = new int[magLen - nInts -1];3435}3436int numIter = magLen - nInts - 1;3437Objects.checkFromToIndex(0, numIter + 1, mag.length);3438Objects.checkFromToIndex(i, numIter + i, newMag.length);3439shiftRightImplWorker(newMag, mag, i, nBits, numIter);3440}34413442if (signum < 0) {3443// Find out whether any one-bits were shifted off the end.3444boolean onesLost = false;3445for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--)3446onesLost = (mag[i] != 0);3447if (!onesLost && nBits != 0)3448onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);34493450if (onesLost)3451newMag = javaIncrement(newMag);3452}34533454return new BigInteger(newMag, signum);3455}34563457@ForceInline3458@IntrinsicCandidate3459private static void shiftRightImplWorker(int[] newArr, int[] oldArr, int newIdx, int shiftCount, int numIter) {3460int shiftCountLeft = 32 - shiftCount;3461int idx = numIter;3462int nidx = (newIdx == 0) ? numIter - 1 : numIter;3463while (nidx >= newIdx) {3464newArr[nidx--] = (oldArr[idx--] >>> shiftCount) | (oldArr[idx] << shiftCountLeft);3465}3466}34673468int[] javaIncrement(int[] val) {3469int lastSum = 0;3470for (int i=val.length-1; i >= 0 && lastSum == 0; i--)3471lastSum = (val[i] += 1);3472if (lastSum == 0) {3473val = new int[val.length+1];3474val[0] = 1;3475}3476return val;3477}34783479// Bitwise Operations34803481/**3482* Returns a BigInteger whose value is {@code (this & val)}. (This3483* method returns a negative BigInteger if and only if this and val are3484* both negative.)3485*3486* @param val value to be AND'ed with this BigInteger.3487* @return {@code this & val}3488*/3489public BigInteger and(BigInteger val) {3490int[] result = new int[Math.max(intLength(), val.intLength())];3491for (int i=0; i < result.length; i++)3492result[i] = (getInt(result.length-i-1)3493& val.getInt(result.length-i-1));34943495return valueOf(result);3496}34973498/**3499* Returns a BigInteger whose value is {@code (this | val)}. (This method3500* returns a negative BigInteger if and only if either this or val is3501* negative.)3502*3503* @param val value to be OR'ed with this BigInteger.3504* @return {@code this | val}3505*/3506public BigInteger or(BigInteger val) {3507int[] result = new int[Math.max(intLength(), val.intLength())];3508for (int i=0; i < result.length; i++)3509result[i] = (getInt(result.length-i-1)3510| val.getInt(result.length-i-1));35113512return valueOf(result);3513}35143515/**3516* Returns a BigInteger whose value is {@code (this ^ val)}. (This method3517* returns a negative BigInteger if and only if exactly one of this and3518* val are negative.)3519*3520* @param val value to be XOR'ed with this BigInteger.3521* @return {@code this ^ val}3522*/3523public BigInteger xor(BigInteger val) {3524int[] result = new int[Math.max(intLength(), val.intLength())];3525for (int i=0; i < result.length; i++)3526result[i] = (getInt(result.length-i-1)3527^ val.getInt(result.length-i-1));35283529return valueOf(result);3530}35313532/**3533* Returns a BigInteger whose value is {@code (~this)}. (This method3534* returns a negative value if and only if this BigInteger is3535* non-negative.)3536*3537* @return {@code ~this}3538*/3539public BigInteger not() {3540int[] result = new int[intLength()];3541for (int i=0; i < result.length; i++)3542result[i] = ~getInt(result.length-i-1);35433544return valueOf(result);3545}35463547/**3548* Returns a BigInteger whose value is {@code (this & ~val)}. This3549* method, which is equivalent to {@code and(val.not())}, is provided as3550* a convenience for masking operations. (This method returns a negative3551* BigInteger if and only if {@code this} is negative and {@code val} is3552* positive.)3553*3554* @param val value to be complemented and AND'ed with this BigInteger.3555* @return {@code this & ~val}3556*/3557public BigInteger andNot(BigInteger val) {3558int[] result = new int[Math.max(intLength(), val.intLength())];3559for (int i=0; i < result.length; i++)3560result[i] = (getInt(result.length-i-1)3561& ~val.getInt(result.length-i-1));35623563return valueOf(result);3564}356535663567// Single Bit Operations35683569/**3570* Returns {@code true} if and only if the designated bit is set.3571* (Computes {@code ((this & (1<<n)) != 0)}.)3572*3573* @param n index of bit to test.3574* @return {@code true} if and only if the designated bit is set.3575* @throws ArithmeticException {@code n} is negative.3576*/3577public boolean testBit(int n) {3578if (n < 0)3579throw new ArithmeticException("Negative bit address");35803581return (getInt(n >>> 5) & (1 << (n & 31))) != 0;3582}35833584/**3585* Returns a BigInteger whose value is equivalent to this BigInteger3586* with the designated bit set. (Computes {@code (this | (1<<n))}.)3587*3588* @param n index of bit to set.3589* @return {@code this | (1<<n)}3590* @throws ArithmeticException {@code n} is negative.3591*/3592public BigInteger setBit(int n) {3593if (n < 0)3594throw new ArithmeticException("Negative bit address");35953596int intNum = n >>> 5;3597int[] result = new int[Math.max(intLength(), intNum+2)];35983599for (int i=0; i < result.length; i++)3600result[result.length-i-1] = getInt(i);36013602result[result.length-intNum-1] |= (1 << (n & 31));36033604return valueOf(result);3605}36063607/**3608* Returns a BigInteger whose value is equivalent to this BigInteger3609* with the designated bit cleared.3610* (Computes {@code (this & ~(1<<n))}.)3611*3612* @param n index of bit to clear.3613* @return {@code this & ~(1<<n)}3614* @throws ArithmeticException {@code n} is negative.3615*/3616public BigInteger clearBit(int n) {3617if (n < 0)3618throw new ArithmeticException("Negative bit address");36193620int intNum = n >>> 5;3621int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];36223623for (int i=0; i < result.length; i++)3624result[result.length-i-1] = getInt(i);36253626result[result.length-intNum-1] &= ~(1 << (n & 31));36273628return valueOf(result);3629}36303631/**3632* Returns a BigInteger whose value is equivalent to this BigInteger3633* with the designated bit flipped.3634* (Computes {@code (this ^ (1<<n))}.)3635*3636* @param n index of bit to flip.3637* @return {@code this ^ (1<<n)}3638* @throws ArithmeticException {@code n} is negative.3639*/3640public BigInteger flipBit(int n) {3641if (n < 0)3642throw new ArithmeticException("Negative bit address");36433644int intNum = n >>> 5;3645int[] result = new int[Math.max(intLength(), intNum+2)];36463647for (int i=0; i < result.length; i++)3648result[result.length-i-1] = getInt(i);36493650result[result.length-intNum-1] ^= (1 << (n & 31));36513652return valueOf(result);3653}36543655/**3656* Returns the index of the rightmost (lowest-order) one bit in this3657* BigInteger (the number of zero bits to the right of the rightmost3658* one bit). Returns -1 if this BigInteger contains no one bits.3659* (Computes {@code (this == 0? -1 : log2(this & -this))}.)3660*3661* @return index of the rightmost one bit in this BigInteger.3662*/3663public int getLowestSetBit() {3664int lsb = lowestSetBitPlusTwo - 2;3665if (lsb == -2) { // lowestSetBit not initialized yet3666lsb = 0;3667if (signum == 0) {3668lsb -= 1;3669} else {3670// Search for lowest order nonzero int3671int i,b;3672for (i=0; (b = getInt(i)) == 0; i++)3673;3674lsb += (i << 5) + Integer.numberOfTrailingZeros(b);3675}3676lowestSetBitPlusTwo = lsb + 2;3677}3678return lsb;3679}368036813682// Miscellaneous Bit Operations36833684/**3685* Returns the number of bits in the minimal two's-complement3686* representation of this BigInteger, <em>excluding</em> a sign bit.3687* For positive BigIntegers, this is equivalent to the number of bits in3688* the ordinary binary representation. For zero this method returns3689* {@code 0}. (Computes {@code (ceil(log2(this < 0 ? -this : this+1)))}.)3690*3691* @return number of bits in the minimal two's-complement3692* representation of this BigInteger, <em>excluding</em> a sign bit.3693*/3694public int bitLength() {3695int n = bitLengthPlusOne - 1;3696if (n == -1) { // bitLength not initialized yet3697int[] m = mag;3698int len = m.length;3699if (len == 0) {3700n = 0; // offset by one to initialize3701} else {3702// Calculate the bit length of the magnitude3703int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);3704if (signum < 0) {3705// Check if magnitude is a power of two3706boolean pow2 = (Integer.bitCount(mag[0]) == 1);3707for (int i=1; i< len && pow2; i++)3708pow2 = (mag[i] == 0);37093710n = (pow2 ? magBitLength - 1 : magBitLength);3711} else {3712n = magBitLength;3713}3714}3715bitLengthPlusOne = n + 1;3716}3717return n;3718}37193720/**3721* Returns the number of bits in the two's complement representation3722* of this BigInteger that differ from its sign bit. This method is3723* useful when implementing bit-vector style sets atop BigIntegers.3724*3725* @return number of bits in the two's complement representation3726* of this BigInteger that differ from its sign bit.3727*/3728public int bitCount() {3729int bc = bitCountPlusOne - 1;3730if (bc == -1) { // bitCount not initialized yet3731bc = 0; // offset by one to initialize3732// Count the bits in the magnitude3733for (int i=0; i < mag.length; i++)3734bc += Integer.bitCount(mag[i]);3735if (signum < 0) {3736// Count the trailing zeros in the magnitude3737int magTrailingZeroCount = 0, j;3738for (j=mag.length-1; mag[j] == 0; j--)3739magTrailingZeroCount += 32;3740magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);3741bc += magTrailingZeroCount - 1;3742}3743bitCountPlusOne = bc + 1;3744}3745return bc;3746}37473748// Primality Testing37493750/**3751* Returns {@code true} if this BigInteger is probably prime,3752* {@code false} if it's definitely composite. If3753* {@code certainty} is ≤ 0, {@code true} is3754* returned.3755*3756* @param certainty a measure of the uncertainty that the caller is3757* willing to tolerate: if the call returns {@code true}3758* the probability that this BigInteger is prime exceeds3759* (1 - 1/2<sup>{@code certainty}</sup>). The execution time of3760* this method is proportional to the value of this parameter.3761* @return {@code true} if this BigInteger is probably prime,3762* {@code false} if it's definitely composite.3763*/3764public boolean isProbablePrime(int certainty) {3765if (certainty <= 0)3766return true;3767BigInteger w = this.abs();3768if (w.equals(TWO))3769return true;3770if (!w.testBit(0) || w.equals(ONE))3771return false;37723773return w.primeToCertainty(certainty, null);3774}37753776// Comparison Operations37773778/**3779* Compares this BigInteger with the specified BigInteger. This3780* method is provided in preference to individual methods for each3781* of the six boolean comparison operators ({@literal <}, ==,3782* {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested3783* idiom for performing these comparisons is: {@code3784* (x.compareTo(y)} <<i>op</i>> {@code 0)}, where3785* <<i>op</i>> is one of the six comparison operators.3786*3787* @param val BigInteger to which this BigInteger is to be compared.3788* @return -1, 0 or 1 as this BigInteger is numerically less than, equal3789* to, or greater than {@code val}.3790*/3791public int compareTo(BigInteger val) {3792if (signum == val.signum) {3793return switch (signum) {3794case 1 -> compareMagnitude(val);3795case -1 -> val.compareMagnitude(this);3796default -> 0;3797};3798}3799return signum > val.signum ? 1 : -1;3800}38013802/**3803* Compares the magnitude array of this BigInteger with the specified3804* BigInteger's. This is the version of compareTo ignoring sign.3805*3806* @param val BigInteger whose magnitude array to be compared.3807* @return -1, 0 or 1 as this magnitude array is less than, equal to or3808* greater than the magnitude aray for the specified BigInteger's.3809*/3810final int compareMagnitude(BigInteger val) {3811int[] m1 = mag;3812int len1 = m1.length;3813int[] m2 = val.mag;3814int len2 = m2.length;3815if (len1 < len2)3816return -1;3817if (len1 > len2)3818return 1;3819for (int i = 0; i < len1; i++) {3820int a = m1[i];3821int b = m2[i];3822if (a != b)3823return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;3824}3825return 0;3826}38273828/**3829* Version of compareMagnitude that compares magnitude with long value.3830* val can't be Long.MIN_VALUE.3831*/3832final int compareMagnitude(long val) {3833assert val != Long.MIN_VALUE;3834int[] m1 = mag;3835int len = m1.length;3836if (len > 2) {3837return 1;3838}3839if (val < 0) {3840val = -val;3841}3842int highWord = (int)(val >>> 32);3843if (highWord == 0) {3844if (len < 1)3845return -1;3846if (len > 1)3847return 1;3848int a = m1[0];3849int b = (int)val;3850if (a != b) {3851return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;3852}3853return 0;3854} else {3855if (len < 2)3856return -1;3857int a = m1[0];3858int b = highWord;3859if (a != b) {3860return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;3861}3862a = m1[1];3863b = (int)val;3864if (a != b) {3865return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;3866}3867return 0;3868}3869}38703871/**3872* Compares this BigInteger with the specified Object for equality.3873*3874* @param x Object to which this BigInteger is to be compared.3875* @return {@code true} if and only if the specified Object is a3876* BigInteger whose value is numerically equal to this BigInteger.3877*/3878public boolean equals(Object x) {3879// This test is just an optimization, which may or may not help3880if (x == this)3881return true;38823883if (!(x instanceof BigInteger xInt))3884return false;38853886if (xInt.signum != signum)3887return false;38883889int[] m = mag;3890int len = m.length;3891int[] xm = xInt.mag;3892if (len != xm.length)3893return false;38943895for (int i = 0; i < len; i++)3896if (xm[i] != m[i])3897return false;38983899return true;3900}39013902/**3903* Returns the minimum of this BigInteger and {@code val}.3904*3905* @param val value with which the minimum is to be computed.3906* @return the BigInteger whose value is the lesser of this BigInteger and3907* {@code val}. If they are equal, either may be returned.3908*/3909public BigInteger min(BigInteger val) {3910return (compareTo(val) < 0 ? this : val);3911}39123913/**3914* Returns the maximum of this BigInteger and {@code val}.3915*3916* @param val value with which the maximum is to be computed.3917* @return the BigInteger whose value is the greater of this and3918* {@code val}. If they are equal, either may be returned.3919*/3920public BigInteger max(BigInteger val) {3921return (compareTo(val) > 0 ? this : val);3922}392339243925// Hash Function39263927/**3928* Returns the hash code for this BigInteger.3929*3930* @return hash code for this BigInteger.3931*/3932public int hashCode() {3933int hashCode = 0;39343935for (int i=0; i < mag.length; i++)3936hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));39373938return hashCode * signum;3939}39403941/**3942* Returns the String representation of this BigInteger in the3943* given radix. If the radix is outside the range from {@link3944* Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive,3945* it will default to 10 (as is the case for3946* {@code Integer.toString}). The digit-to-character mapping3947* provided by {@code Character.forDigit} is used, and a minus3948* sign is prepended if appropriate. (This representation is3949* compatible with the {@link #BigInteger(String, int) (String,3950* int)} constructor.)3951*3952* @param radix radix of the String representation.3953* @return String representation of this BigInteger in the given radix.3954* @see Integer#toString3955* @see Character#forDigit3956* @see #BigInteger(java.lang.String, int)3957*/3958public String toString(int radix) {3959if (signum == 0)3960return "0";3961if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)3962radix = 10;39633964BigInteger abs = this.abs();39653966// Ensure buffer capacity sufficient to contain string representation3967// floor(bitLength*log(2)/log(radix)) + 13968// plus an additional character for the sign if negative.3969int b = abs.bitLength();3970int numChars = (int)(Math.floor(b*LOG_TWO/logCache[radix]) + 1) +3971(signum < 0 ? 1 : 0);3972StringBuilder sb = new StringBuilder(numChars);39733974if (signum < 0) {3975sb.append('-');3976}39773978// Use recursive toString.3979toString(abs, sb, radix, 0);39803981return sb.toString();3982}39833984/**3985* If {@code numZeros > 0}, appends that many zeros to the3986* specified StringBuilder; otherwise, does nothing.3987*3988* @param buf The StringBuilder that will be appended to.3989* @param numZeros The number of zeros to append.3990*/3991private static void padWithZeros(StringBuilder buf, int numZeros) {3992while (numZeros >= NUM_ZEROS) {3993buf.append(ZEROS);3994numZeros -= NUM_ZEROS;3995}3996if (numZeros > 0) {3997buf.append(ZEROS, 0, numZeros);3998}3999}40004001/**4002* This method is used to perform toString when arguments are small.4003* The value must be non-negative. If {@code digits <= 0} no padding4004* (pre-pending with zeros) will be effected.4005*4006* @param radix The base to convert to.4007* @param buf The StringBuilder that will be appended to in place.4008* @param digits The minimum number of digits to pad to.4009*/4010private void smallToString(int radix, StringBuilder buf, int digits) {4011assert signum >= 0;40124013if (signum == 0) {4014padWithZeros(buf, digits);4015return;4016}40174018// Compute upper bound on number of digit groups and allocate space4019int maxNumDigitGroups = (4*mag.length + 6)/7;4020long[] digitGroups = new long[maxNumDigitGroups];40214022// Translate number to string, a digit group at a time4023BigInteger tmp = this;4024int numGroups = 0;4025while (tmp.signum != 0) {4026BigInteger d = longRadix[radix];40274028MutableBigInteger q = new MutableBigInteger(),4029a = new MutableBigInteger(tmp.mag),4030b = new MutableBigInteger(d.mag);4031MutableBigInteger r = a.divide(b, q);4032BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);4033BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);40344035digitGroups[numGroups++] = r2.longValue();4036tmp = q2;4037}40384039// Get string version of first digit group4040String s = Long.toString(digitGroups[numGroups-1], radix);40414042// Pad with internal zeros if necessary.4043padWithZeros(buf, digits - (s.length() +4044(numGroups - 1)*digitsPerLong[radix]));40454046// Put first digit group into result buffer4047buf.append(s);40484049// Append remaining digit groups each padded with leading zeros4050for (int i=numGroups-2; i >= 0; i--) {4051// Prepend (any) leading zeros for this digit group4052s = Long.toString(digitGroups[i], radix);4053int numLeadingZeros = digitsPerLong[radix] - s.length();4054if (numLeadingZeros != 0) {4055buf.append(ZEROS, 0, numLeadingZeros);4056}4057buf.append(s);4058}4059}40604061/**4062* Converts the specified BigInteger to a string and appends to4063* {@code sb}. This implements the recursive Schoenhage algorithm4064* for base conversions. This method can only be called for non-negative4065* numbers.4066* <p>4067* See Knuth, Donald, _The Art of Computer Programming_, Vol. 2,4068* Answers to Exercises (4.4) Question 14.4069*4070* @param u The number to convert to a string.4071* @param sb The StringBuilder that will be appended to in place.4072* @param radix The base to convert to.4073* @param digits The minimum number of digits to pad to.4074*/4075private static void toString(BigInteger u, StringBuilder sb,4076int radix, int digits) {4077assert u.signum() >= 0;40784079// If we're smaller than a certain threshold, use the smallToString4080// method, padding with leading zeroes when necessary unless we're4081// at the beginning of the string or digits <= 0. As u.signum() >= 0,4082// smallToString() will not prepend a negative sign.4083if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {4084u.smallToString(radix, sb, digits);4085return;4086}40874088// Calculate a value for n in the equation radix^(2^n) = u4089// and subtract 1 from that value. This is used to find the4090// cache index that contains the best value to divide u.4091int b = u.bitLength();4092int n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) /4093LOG_TWO - 1.0);40944095BigInteger v = getRadixConversionCache(radix, n);4096BigInteger[] results;4097results = u.divideAndRemainder(v);40984099int expectedDigits = 1 << n;41004101// Now recursively build the two halves of each number.4102toString(results[0], sb, radix, digits - expectedDigits);4103toString(results[1], sb, radix, expectedDigits);4104}41054106/**4107* Returns the value radix^(2^exponent) from the cache.4108* If this value doesn't already exist in the cache, it is added.4109* <p>4110* This could be changed to a more complicated caching method using4111* {@code Future}.4112*/4113private static BigInteger getRadixConversionCache(int radix, int exponent) {4114BigInteger[] cacheLine = powerCache[radix]; // volatile read4115if (exponent < cacheLine.length) {4116return cacheLine[exponent];4117}41184119int oldLength = cacheLine.length;4120cacheLine = Arrays.copyOf(cacheLine, exponent + 1);4121for (int i = oldLength; i <= exponent; i++) {4122cacheLine[i] = cacheLine[i - 1].pow(2);4123}41244125BigInteger[][] pc = powerCache; // volatile read again4126if (exponent >= pc[radix].length) {4127pc = pc.clone();4128pc[radix] = cacheLine;4129powerCache = pc; // volatile write, publish4130}4131return cacheLine[exponent];4132}41334134/* Size of ZEROS string. */4135private static int NUM_ZEROS = 63;41364137/* ZEROS is a string of NUM_ZEROS consecutive zeros. */4138private static final String ZEROS = "0".repeat(NUM_ZEROS);41394140/**4141* Returns the decimal String representation of this BigInteger.4142* The digit-to-character mapping provided by4143* {@code Character.forDigit} is used, and a minus sign is4144* prepended if appropriate. (This representation is compatible4145* with the {@link #BigInteger(String) (String)} constructor, and4146* allows for String concatenation with Java's + operator.)4147*4148* @return decimal String representation of this BigInteger.4149* @see Character#forDigit4150* @see #BigInteger(java.lang.String)4151*/4152public String toString() {4153return toString(10);4154}41554156/**4157* Returns a byte array containing the two's-complement4158* representation of this BigInteger. The byte array will be in4159* <i>big-endian</i> byte-order: the most significant byte is in4160* the zeroth element. The array will contain the minimum number4161* of bytes required to represent this BigInteger, including at4162* least one sign bit, which is {@code (ceil((this.bitLength() +4163* 1)/8))}. (This representation is compatible with the4164* {@link #BigInteger(byte[]) (byte[])} constructor.)4165*4166* @return a byte array containing the two's-complement representation of4167* this BigInteger.4168* @see #BigInteger(byte[])4169*/4170public byte[] toByteArray() {4171int byteLen = bitLength()/8 + 1;4172byte[] byteArray = new byte[byteLen];41734174for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {4175if (bytesCopied == 4) {4176nextInt = getInt(intIndex++);4177bytesCopied = 1;4178} else {4179nextInt >>>= 8;4180bytesCopied++;4181}4182byteArray[i] = (byte)nextInt;4183}4184return byteArray;4185}41864187/**4188* Converts this BigInteger to an {@code int}. This4189* conversion is analogous to a4190* <i>narrowing primitive conversion</i> from {@code long} to4191* {@code int} as defined in4192* <cite>The Java Language Specification</cite>:4193* if this BigInteger is too big to fit in an4194* {@code int}, only the low-order 32 bits are returned.4195* Note that this conversion can lose information about the4196* overall magnitude of the BigInteger value as well as return a4197* result with the opposite sign.4198*4199* @return this BigInteger converted to an {@code int}.4200* @see #intValueExact()4201* @jls 5.1.3 Narrowing Primitive Conversion4202*/4203public int intValue() {4204int result = 0;4205result = getInt(0);4206return result;4207}42084209/**4210* Converts this BigInteger to a {@code long}. This4211* conversion is analogous to a4212* <i>narrowing primitive conversion</i> from {@code long} to4213* {@code int} as defined in4214* <cite>The Java Language Specification</cite>:4215* if this BigInteger is too big to fit in a4216* {@code long}, only the low-order 64 bits are returned.4217* Note that this conversion can lose information about the4218* overall magnitude of the BigInteger value as well as return a4219* result with the opposite sign.4220*4221* @return this BigInteger converted to a {@code long}.4222* @see #longValueExact()4223* @jls 5.1.3 Narrowing Primitive Conversion4224*/4225public long longValue() {4226long result = 0;42274228for (int i=1; i >= 0; i--)4229result = (result << 32) + (getInt(i) & LONG_MASK);4230return result;4231}42324233/**4234* Converts this BigInteger to a {@code float}. This4235* conversion is similar to the4236* <i>narrowing primitive conversion</i> from {@code double} to4237* {@code float} as defined in4238* <cite>The Java Language Specification</cite>:4239* if this BigInteger has too great a magnitude4240* to represent as a {@code float}, it will be converted to4241* {@link Float#NEGATIVE_INFINITY} or {@link4242* Float#POSITIVE_INFINITY} as appropriate. Note that even when4243* the return value is finite, this conversion can lose4244* information about the precision of the BigInteger value.4245*4246* @return this BigInteger converted to a {@code float}.4247* @jls 5.1.3 Narrowing Primitive Conversion4248*/4249public float floatValue() {4250if (signum == 0) {4251return 0.0f;4252}42534254int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;42554256// exponent == floor(log2(abs(this)))4257if (exponent < Long.SIZE - 1) {4258return longValue();4259} else if (exponent > Float.MAX_EXPONENT) {4260return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;4261}42624263/*4264* We need the top SIGNIFICAND_WIDTH bits, including the "implicit"4265* one bit. To make rounding easier, we pick out the top4266* SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or4267* down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 14268* bits, and signifFloor the top SIGNIFICAND_WIDTH.4269*4270* It helps to consider the real number signif = abs(this) *4271* 2^(SIGNIFICAND_WIDTH - 1 - exponent).4272*/4273int shift = exponent - FloatConsts.SIGNIFICAND_WIDTH;42744275int twiceSignifFloor;4276// twiceSignifFloor will be == abs().shiftRight(shift).intValue()4277// We do the shift into an int directly to improve performance.42784279int nBits = shift & 0x1f;4280int nBits2 = 32 - nBits;42814282if (nBits == 0) {4283twiceSignifFloor = mag[0];4284} else {4285twiceSignifFloor = mag[0] >>> nBits;4286if (twiceSignifFloor == 0) {4287twiceSignifFloor = (mag[0] << nBits2) | (mag[1] >>> nBits);4288}4289}42904291int signifFloor = twiceSignifFloor >> 1;4292signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit42934294/*4295* We round up if either the fractional part of signif is strictly4296* greater than 0.5 (which is true if the 0.5 bit is set and any lower4297* bit is set), or if the fractional part of signif is >= 0.5 and4298* signifFloor is odd (which is true if both the 0.5 bit and the 1 bit4299* are set). This is equivalent to the desired HALF_EVEN rounding.4300*/4301boolean increment = (twiceSignifFloor & 1) != 04302&& ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);4303int signifRounded = increment ? signifFloor + 1 : signifFloor;4304int bits = ((exponent + FloatConsts.EXP_BIAS))4305<< (FloatConsts.SIGNIFICAND_WIDTH - 1);4306bits += signifRounded;4307/*4308* If signifRounded == 2^24, we'd need to set all of the significand4309* bits to zero and add 1 to the exponent. This is exactly the behavior4310* we get from just adding signifRounded to bits directly. If the4311* exponent is Float.MAX_EXPONENT, we round up (correctly) to4312* Float.POSITIVE_INFINITY.4313*/4314bits |= signum & FloatConsts.SIGN_BIT_MASK;4315return Float.intBitsToFloat(bits);4316}43174318/**4319* Converts this BigInteger to a {@code double}. This4320* conversion is similar to the4321* <i>narrowing primitive conversion</i> from {@code double} to4322* {@code float} as defined in4323* <cite>The Java Language Specification</cite>:4324* if this BigInteger has too great a magnitude4325* to represent as a {@code double}, it will be converted to4326* {@link Double#NEGATIVE_INFINITY} or {@link4327* Double#POSITIVE_INFINITY} as appropriate. Note that even when4328* the return value is finite, this conversion can lose4329* information about the precision of the BigInteger value.4330*4331* @return this BigInteger converted to a {@code double}.4332* @jls 5.1.3 Narrowing Primitive Conversion4333*/4334public double doubleValue() {4335if (signum == 0) {4336return 0.0;4337}43384339int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;43404341// exponent == floor(log2(abs(this))Double)4342if (exponent < Long.SIZE - 1) {4343return longValue();4344} else if (exponent > Double.MAX_EXPONENT) {4345return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;4346}43474348/*4349* We need the top SIGNIFICAND_WIDTH bits, including the "implicit"4350* one bit. To make rounding easier, we pick out the top4351* SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or4352* down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 14353* bits, and signifFloor the top SIGNIFICAND_WIDTH.4354*4355* It helps to consider the real number signif = abs(this) *4356* 2^(SIGNIFICAND_WIDTH - 1 - exponent).4357*/4358int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH;43594360long twiceSignifFloor;4361// twiceSignifFloor will be == abs().shiftRight(shift).longValue()4362// We do the shift into a long directly to improve performance.43634364int nBits = shift & 0x1f;4365int nBits2 = 32 - nBits;43664367int highBits;4368int lowBits;4369if (nBits == 0) {4370highBits = mag[0];4371lowBits = mag[1];4372} else {4373highBits = mag[0] >>> nBits;4374lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits);4375if (highBits == 0) {4376highBits = lowBits;4377lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits);4378}4379}43804381twiceSignifFloor = ((highBits & LONG_MASK) << 32)4382| (lowBits & LONG_MASK);43834384long signifFloor = twiceSignifFloor >> 1;4385signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit43864387/*4388* We round up if either the fractional part of signif is strictly4389* greater than 0.5 (which is true if the 0.5 bit is set and any lower4390* bit is set), or if the fractional part of signif is >= 0.5 and4391* signifFloor is odd (which is true if both the 0.5 bit and the 1 bit4392* are set). This is equivalent to the desired HALF_EVEN rounding.4393*/4394boolean increment = (twiceSignifFloor & 1) != 04395&& ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);4396long signifRounded = increment ? signifFloor + 1 : signifFloor;4397long bits = (long) ((exponent + DoubleConsts.EXP_BIAS))4398<< (DoubleConsts.SIGNIFICAND_WIDTH - 1);4399bits += signifRounded;4400/*4401* If signifRounded == 2^53, we'd need to set all of the significand4402* bits to zero and add 1 to the exponent. This is exactly the behavior4403* we get from just adding signifRounded to bits directly. If the4404* exponent is Double.MAX_EXPONENT, we round up (correctly) to4405* Double.POSITIVE_INFINITY.4406*/4407bits |= signum & DoubleConsts.SIGN_BIT_MASK;4408return Double.longBitsToDouble(bits);4409}44104411/**4412* Returns a copy of the input array stripped of any leading zero bytes.4413*/4414private static int[] stripLeadingZeroInts(int val[]) {4415int vlen = val.length;4416int keep;44174418// Find first nonzero byte4419for (keep = 0; keep < vlen && val[keep] == 0; keep++)4420;4421return java.util.Arrays.copyOfRange(val, keep, vlen);4422}44234424/**4425* Returns the input array stripped of any leading zero bytes.4426* Since the source is trusted the copying may be skipped.4427*/4428private static int[] trustedStripLeadingZeroInts(int val[]) {4429int vlen = val.length;4430int keep;44314432// Find first nonzero byte4433for (keep = 0; keep < vlen && val[keep] == 0; keep++)4434;4435return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen);4436}44374438/**4439* Returns a copy of the input array stripped of any leading zero bytes.4440*/4441private static int[] stripLeadingZeroBytes(byte a[], int off, int len) {4442int indexBound = off + len;4443int keep;44444445// Find first nonzero byte4446for (keep = off; keep < indexBound && a[keep] == 0; keep++)4447;44484449// Allocate new array and copy relevant part of input array4450int intLength = ((indexBound - keep) + 3) >>> 2;4451int[] result = new int[intLength];4452int b = indexBound - 1;4453for (int i = intLength-1; i >= 0; i--) {4454result[i] = a[b--] & 0xff;4455int bytesRemaining = b - keep + 1;4456int bytesToTransfer = Math.min(3, bytesRemaining);4457for (int j=8; j <= (bytesToTransfer << 3); j += 8)4458result[i] |= ((a[b--] & 0xff) << j);4459}4460return result;4461}44624463/**4464* Takes an array a representing a negative 2's-complement number and4465* returns the minimal (no leading zero bytes) unsigned whose value is -a.4466*/4467private static int[] makePositive(byte a[], int off, int len) {4468int keep, k;4469int indexBound = off + len;44704471// Find first non-sign (0xff) byte of input4472for (keep=off; keep < indexBound && a[keep] == -1; keep++)4473;447444754476/* Allocate output array. If all non-sign bytes are 0x00, we must4477* allocate space for one extra output byte. */4478for (k=keep; k < indexBound && a[k] == 0; k++)4479;44804481int extraByte = (k == indexBound) ? 1 : 0;4482int intLength = ((indexBound - keep + extraByte) + 3) >>> 2;4483int result[] = new int[intLength];44844485/* Copy one's complement of input into output, leaving extra4486* byte (if it exists) == 0x00 */4487int b = indexBound - 1;4488for (int i = intLength-1; i >= 0; i--) {4489result[i] = a[b--] & 0xff;4490int numBytesToTransfer = Math.min(3, b-keep+1);4491if (numBytesToTransfer < 0)4492numBytesToTransfer = 0;4493for (int j=8; j <= 8*numBytesToTransfer; j += 8)4494result[i] |= ((a[b--] & 0xff) << j);44954496// Mask indicates which bits must be complemented4497int mask = -1 >>> (8*(3-numBytesToTransfer));4498result[i] = ~result[i] & mask;4499}45004501// Add one to one's complement to generate two's complement4502for (int i=result.length-1; i >= 0; i--) {4503result[i] = (int)((result[i] & LONG_MASK) + 1);4504if (result[i] != 0)4505break;4506}45074508return result;4509}45104511/**4512* Takes an array a representing a negative 2's-complement number and4513* returns the minimal (no leading zero ints) unsigned whose value is -a.4514*/4515private static int[] makePositive(int a[]) {4516int keep, j;45174518// Find first non-sign (0xffffffff) int of input4519for (keep=0; keep < a.length && a[keep] == -1; keep++)4520;45214522/* Allocate output array. If all non-sign ints are 0x00, we must4523* allocate space for one extra output int. */4524for (j=keep; j < a.length && a[j] == 0; j++)4525;4526int extraInt = (j == a.length ? 1 : 0);4527int result[] = new int[a.length - keep + extraInt];45284529/* Copy one's complement of input into output, leaving extra4530* int (if it exists) == 0x00 */4531for (int i = keep; i < a.length; i++)4532result[i - keep + extraInt] = ~a[i];45334534// Add one to one's complement to generate two's complement4535for (int i=result.length-1; ++result[i] == 0; i--)4536;45374538return result;4539}45404541/*4542* The following two arrays are used for fast String conversions. Both4543* are indexed by radix. The first is the number of digits of the given4544* radix that can fit in a Java long without "going negative", i.e., the4545* highest integer n such that radix**n < 2**63. The second is the4546* "long radix" that tears each number into "long digits", each of which4547* consists of the number of digits in the corresponding element in4548* digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have4549* nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not4550* used.4551*/4552private static int digitsPerLong[] = {0, 0,455362, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,455414, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};45554556private static BigInteger longRadix[] = {null, null,4557valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),4558valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),4559valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),4560valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),4561valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),4562valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),4563valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),4564valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),4565valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),4566valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),4567valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),4568valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),4569valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),4570valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),4571valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),4572valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),4573valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),4574valueOf(0x41c21cb8e1000000L)};45754576/*4577* These two arrays are the integer analogue of above.4578*/4579private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11,458011, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,45816, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};45824583private static int intRadix[] = {0, 0,45840x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,45850x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,45860x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000,45870x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,45880x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40,45890x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,45900x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa4004591};45924593/**4594* These routines provide access to the two's complement representation4595* of BigIntegers.4596*/45974598/**4599* Returns the length of the two's complement representation in ints,4600* including space for at least one sign bit.4601*/4602private int intLength() {4603return (bitLength() >>> 5) + 1;4604}46054606/* Returns sign bit */4607private int signBit() {4608return signum < 0 ? 1 : 0;4609}46104611/* Returns an int of sign bits */4612private int signInt() {4613return signum < 0 ? -1 : 0;4614}46154616/**4617* Returns the specified int of the little-endian two's complement4618* representation (int 0 is the least significant). The int number can4619* be arbitrarily high (values are logically preceded by infinitely many4620* sign ints).4621*/4622private int getInt(int n) {4623if (n < 0)4624return 0;4625if (n >= mag.length)4626return signInt();46274628int magInt = mag[mag.length-n-1];46294630return (signum >= 0 ? magInt :4631(n <= firstNonzeroIntNum() ? -magInt : ~magInt));4632}46334634/**4635* Returns the index of the int that contains the first nonzero int in the4636* little-endian binary representation of the magnitude (int 0 is the4637* least significant). If the magnitude is zero, return value is undefined.4638*4639* <p>Note: never used for a BigInteger with a magnitude of zero.4640* @see #getInt4641*/4642private int firstNonzeroIntNum() {4643int fn = firstNonzeroIntNumPlusTwo - 2;4644if (fn == -2) { // firstNonzeroIntNum not initialized yet4645// Search for the first nonzero int4646int i;4647int mlen = mag.length;4648for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)4649;4650fn = mlen - i - 1;4651firstNonzeroIntNumPlusTwo = fn + 2; // offset by two to initialize4652}4653return fn;4654}46554656/** use serialVersionUID from JDK 1.1. for interoperability */4657@java.io.Serial4658private static final long serialVersionUID = -8287574255936472291L;46594660/**4661* Serializable fields for BigInteger.4662*4663* @serialField signum int4664* signum of this BigInteger4665* @serialField magnitude byte[]4666* magnitude array of this BigInteger4667* @serialField bitCount int4668* appears in the serialized form for backward compatibility4669* @serialField bitLength int4670* appears in the serialized form for backward compatibility4671* @serialField firstNonzeroByteNum int4672* appears in the serialized form for backward compatibility4673* @serialField lowestSetBit int4674* appears in the serialized form for backward compatibility4675*/4676@java.io.Serial4677private static final ObjectStreamField[] serialPersistentFields = {4678new ObjectStreamField("signum", Integer.TYPE),4679new ObjectStreamField("magnitude", byte[].class),4680new ObjectStreamField("bitCount", Integer.TYPE),4681new ObjectStreamField("bitLength", Integer.TYPE),4682new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),4683new ObjectStreamField("lowestSetBit", Integer.TYPE)4684};46854686/**4687* Reconstitute the {@code BigInteger} instance from a stream (that is,4688* deserialize it). The magnitude is read in as an array of bytes4689* for historical reasons, but it is converted to an array of ints4690* and the byte array is discarded.4691* Note:4692* The current convention is to initialize the cache fields, bitCountPlusOne,4693* bitLengthPlusOne and lowestSetBitPlusTwo, to 0 rather than some other4694* marker value. Therefore, no explicit action to set these fields needs to4695* be taken in readObject because those fields already have a 0 value by4696* default since defaultReadObject is not being used.4697*4698* @param s the stream being read.4699* @throws IOException if an I/O error occurs4700* @throws ClassNotFoundException if a serialized class cannot be loaded4701*/4702@java.io.Serial4703private void readObject(java.io.ObjectInputStream s)4704throws java.io.IOException, ClassNotFoundException {4705// prepare to read the alternate persistent fields4706ObjectInputStream.GetField fields = s.readFields();47074708// Read the alternate persistent fields that we care about4709int sign = fields.get("signum", -2);4710byte[] magnitude = (byte[])fields.get("magnitude", null);47114712// Validate signum4713if (sign < -1 || sign > 1) {4714String message = "BigInteger: Invalid signum value";4715if (fields.defaulted("signum"))4716message = "BigInteger: Signum not present in stream";4717throw new java.io.StreamCorruptedException(message);4718}4719int[] mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);4720if ((mag.length == 0) != (sign == 0)) {4721String message = "BigInteger: signum-magnitude mismatch";4722if (fields.defaulted("magnitude"))4723message = "BigInteger: Magnitude not present in stream";4724throw new java.io.StreamCorruptedException(message);4725}47264727// Commit final fields via Unsafe4728UnsafeHolder.putSign(this, sign);47294730// Calculate mag field from magnitude and discard magnitude4731UnsafeHolder.putMag(this, mag);4732if (mag.length >= MAX_MAG_LENGTH) {4733try {4734checkRange();4735} catch (ArithmeticException e) {4736throw new java.io.StreamCorruptedException("BigInteger: Out of the supported range");4737}4738}4739}47404741// Support for resetting final fields while deserializing4742private static class UnsafeHolder {4743private static final jdk.internal.misc.Unsafe unsafe4744= jdk.internal.misc.Unsafe.getUnsafe();4745private static final long signumOffset4746= unsafe.objectFieldOffset(BigInteger.class, "signum");4747private static final long magOffset4748= unsafe.objectFieldOffset(BigInteger.class, "mag");47494750static void putSign(BigInteger bi, int sign) {4751unsafe.putInt(bi, signumOffset, sign);4752}47534754static void putMag(BigInteger bi, int[] magnitude) {4755unsafe.putReference(bi, magOffset, magnitude);4756}4757}47584759/**4760* Save the {@code BigInteger} instance to a stream. The magnitude of a4761* {@code BigInteger} is serialized as a byte array for historical reasons.4762* To maintain compatibility with older implementations, the integers4763* -1, -1, -2, and -2 are written as the values of the obsolete fields4764* {@code bitCount}, {@code bitLength}, {@code lowestSetBit}, and4765* {@code firstNonzeroByteNum}, respectively. These values are compatible4766* with older implementations, but will be ignored by current4767* implementations.4768*4769* @param s the stream to serialize to.4770* @throws IOException if an I/O error occurs4771*/4772@java.io.Serial4773private void writeObject(ObjectOutputStream s) throws IOException {4774// set the values of the Serializable fields4775ObjectOutputStream.PutField fields = s.putFields();4776fields.put("signum", signum);4777fields.put("magnitude", magSerializedForm());4778// The values written for cached fields are compatible with older4779// versions, but are ignored in readObject so don't otherwise matter.4780fields.put("bitCount", -1);4781fields.put("bitLength", -1);4782fields.put("lowestSetBit", -2);4783fields.put("firstNonzeroByteNum", -2);47844785// save them4786s.writeFields();4787}47884789/**4790* Returns the mag array as an array of bytes.4791*/4792private byte[] magSerializedForm() {4793int len = mag.length;47944795int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0]));4796int byteLen = (bitLen + 7) >>> 3;4797byte[] result = new byte[byteLen];47984799for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;4800i >= 0; i--) {4801if (bytesCopied == 4) {4802nextInt = mag[intIndex--];4803bytesCopied = 1;4804} else {4805nextInt >>>= 8;4806bytesCopied++;4807}4808result[i] = (byte)nextInt;4809}4810return result;4811}48124813/**4814* Converts this {@code BigInteger} to a {@code long}, checking4815* for lost information. If the value of this {@code BigInteger}4816* is out of the range of the {@code long} type, then an4817* {@code ArithmeticException} is thrown.4818*4819* @return this {@code BigInteger} converted to a {@code long}.4820* @throws ArithmeticException if the value of {@code this} will4821* not exactly fit in a {@code long}.4822* @see BigInteger#longValue4823* @since 1.84824*/4825public long longValueExact() {4826if (mag.length <= 2 && bitLength() <= 63)4827return longValue();4828else4829throw new ArithmeticException("BigInteger out of long range");4830}48314832/**4833* Converts this {@code BigInteger} to an {@code int}, checking4834* for lost information. If the value of this {@code BigInteger}4835* is out of the range of the {@code int} type, then an4836* {@code ArithmeticException} is thrown.4837*4838* @return this {@code BigInteger} converted to an {@code int}.4839* @throws ArithmeticException if the value of {@code this} will4840* not exactly fit in an {@code int}.4841* @see BigInteger#intValue4842* @since 1.84843*/4844public int intValueExact() {4845if (mag.length <= 1 && bitLength() <= 31)4846return intValue();4847else4848throw new ArithmeticException("BigInteger out of int range");4849}48504851/**4852* Converts this {@code BigInteger} to a {@code short}, checking4853* for lost information. If the value of this {@code BigInteger}4854* is out of the range of the {@code short} type, then an4855* {@code ArithmeticException} is thrown.4856*4857* @return this {@code BigInteger} converted to a {@code short}.4858* @throws ArithmeticException if the value of {@code this} will4859* not exactly fit in a {@code short}.4860* @see BigInteger#shortValue4861* @since 1.84862*/4863public short shortValueExact() {4864if (mag.length <= 1 && bitLength() <= 31) {4865int value = intValue();4866if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE)4867return shortValue();4868}4869throw new ArithmeticException("BigInteger out of short range");4870}48714872/**4873* Converts this {@code BigInteger} to a {@code byte}, checking4874* for lost information. If the value of this {@code BigInteger}4875* is out of the range of the {@code byte} type, then an4876* {@code ArithmeticException} is thrown.4877*4878* @return this {@code BigInteger} converted to a {@code byte}.4879* @throws ArithmeticException if the value of {@code this} will4880* not exactly fit in a {@code byte}.4881* @see BigInteger#byteValue4882* @since 1.84883*/4884public byte byteValueExact() {4885if (mag.length <= 1 && bitLength() <= 31) {4886int value = intValue();4887if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE)4888return byteValue();4889}4890throw new ArithmeticException("BigInteger out of byte range");4891}4892}489348944895