Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/math/MutableBigInteger.java
38829 views
/*1* Copyright (c) 1999, 2020, 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*/2425package java.math;2627/**28* A class used to represent multiprecision integers that makes efficient29* use of allocated space by allowing a number to occupy only part of30* an array so that the arrays do not have to be reallocated as often.31* When performing an operation with many iterations the array used to32* hold a number is only reallocated when necessary and does not have to33* be the same size as the number it represents. A mutable number allows34* calculations to occur on the same number without having to create35* a new number for every step of the calculation as occurs with36* BigIntegers.37*38* @see BigInteger39* @author Michael McCloskey40* @author Timothy Buktu41* @since 1.342*/4344import static java.math.BigDecimal.INFLATED;45import static java.math.BigInteger.LONG_MASK;46import java.util.Arrays;4748class MutableBigInteger {49/**50* Holds the magnitude of this MutableBigInteger in big endian order.51* The magnitude may start at an offset into the value array, and it may52* end before the length of the value array.53*/54int[] value;5556/**57* The number of ints of the value array that are currently used58* to hold the magnitude of this MutableBigInteger. The magnitude starts59* at an offset and offset + intLen may be less than value.length.60*/61int intLen;6263/**64* The offset into the value array where the magnitude of this65* MutableBigInteger begins.66*/67int offset = 0;6869// Constants70/**71* MutableBigInteger with one element value array with the value 1. Used by72* BigDecimal divideAndRound to increment the quotient. Use this constant73* only when the method is not going to modify this object.74*/75static final MutableBigInteger ONE = new MutableBigInteger(1);7677/**78* The minimum {@code intLen} for cancelling powers of two before79* dividing.80* If the number of ints is less than this threshold,81* {@code divideKnuth} does not eliminate common powers of two from82* the dividend and divisor.83*/84static final int KNUTH_POW2_THRESH_LEN = 6;8586/**87* The minimum number of trailing zero ints for cancelling powers of two88* before dividing.89* If the dividend and divisor don't share at least this many zero ints90* at the end, {@code divideKnuth} does not eliminate common powers91* of two from the dividend and divisor.92*/93static final int KNUTH_POW2_THRESH_ZEROS = 3;9495// Constructors9697/**98* The default constructor. An empty MutableBigInteger is created with99* a one word capacity.100*/101MutableBigInteger() {102value = new int[1];103intLen = 0;104}105106/**107* Construct a new MutableBigInteger with a magnitude specified by108* the int val.109*/110MutableBigInteger(int val) {111value = new int[1];112intLen = 1;113value[0] = val;114}115116/**117* Construct a new MutableBigInteger with the specified value array118* up to the length of the array supplied.119*/120MutableBigInteger(int[] val) {121value = val;122intLen = val.length;123}124125/**126* Construct a new MutableBigInteger with a magnitude equal to the127* specified BigInteger.128*/129MutableBigInteger(BigInteger b) {130intLen = b.mag.length;131value = Arrays.copyOf(b.mag, intLen);132}133134/**135* Construct a new MutableBigInteger with a magnitude equal to the136* specified MutableBigInteger.137*/138MutableBigInteger(MutableBigInteger val) {139intLen = val.intLen;140value = Arrays.copyOfRange(val.value, val.offset, val.offset + intLen);141}142143/**144* Makes this number an {@code n}-int number all of whose bits are ones.145* Used by Burnikel-Ziegler division.146* @param n number of ints in the {@code value} array147* @return a number equal to {@code ((1<<(32*n)))-1}148*/149private void ones(int n) {150if (n > value.length)151value = new int[n];152Arrays.fill(value, -1);153offset = 0;154intLen = n;155}156157/**158* Internal helper method to return the magnitude array. The caller is not159* supposed to modify the returned array.160*/161private int[] getMagnitudeArray() {162if (offset > 0 || value.length != intLen)163return Arrays.copyOfRange(value, offset, offset + intLen);164return value;165}166167/**168* Convert this MutableBigInteger to a long value. The caller has to make169* sure this MutableBigInteger can be fit into long.170*/171private long toLong() {172assert (intLen <= 2) : "this MutableBigInteger exceeds the range of long";173if (intLen == 0)174return 0;175long d = value[offset] & LONG_MASK;176return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d;177}178179/**180* Convert this MutableBigInteger to a BigInteger object.181*/182BigInteger toBigInteger(int sign) {183if (intLen == 0 || sign == 0)184return BigInteger.ZERO;185return new BigInteger(getMagnitudeArray(), sign);186}187188/**189* Converts this number to a nonnegative {@code BigInteger}.190*/191BigInteger toBigInteger() {192normalize();193return toBigInteger(isZero() ? 0 : 1);194}195196/**197* Convert this MutableBigInteger to BigDecimal object with the specified sign198* and scale.199*/200BigDecimal toBigDecimal(int sign, int scale) {201if (intLen == 0 || sign == 0)202return BigDecimal.zeroValueOf(scale);203int[] mag = getMagnitudeArray();204int len = mag.length;205int d = mag[0];206// If this MutableBigInteger can't be fit into long, we need to207// make a BigInteger object for the resultant BigDecimal object.208if (len > 2 || (d < 0 && len == 2))209return new BigDecimal(new BigInteger(mag, sign), INFLATED, scale, 0);210long v = (len == 2) ?211((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) :212d & LONG_MASK;213return BigDecimal.valueOf(sign == -1 ? -v : v, scale);214}215216/**217* This is for internal use in converting from a MutableBigInteger218* object into a long value given a specified sign.219* returns INFLATED if value is not fit into long220*/221long toCompactValue(int sign) {222if (intLen == 0 || sign == 0)223return 0L;224int[] mag = getMagnitudeArray();225int len = mag.length;226int d = mag[0];227// If this MutableBigInteger can not be fitted into long, we need to228// make a BigInteger object for the resultant BigDecimal object.229if (len > 2 || (d < 0 && len == 2))230return INFLATED;231long v = (len == 2) ?232((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) :233d & LONG_MASK;234return sign == -1 ? -v : v;235}236237/**238* Clear out a MutableBigInteger for reuse.239*/240void clear() {241offset = intLen = 0;242for (int index=0, n=value.length; index < n; index++)243value[index] = 0;244}245246/**247* Set a MutableBigInteger to zero, removing its offset.248*/249void reset() {250offset = intLen = 0;251}252253/**254* Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1255* as this MutableBigInteger is numerically less than, equal to, or256* greater than <tt>b</tt>.257*/258final int compare(MutableBigInteger b) {259int blen = b.intLen;260if (intLen < blen)261return -1;262if (intLen > blen)263return 1;264265// Add Integer.MIN_VALUE to make the comparison act as unsigned integer266// comparison.267int[] bval = b.value;268for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) {269int b1 = value[i] + 0x80000000;270int b2 = bval[j] + 0x80000000;271if (b1 < b2)272return -1;273if (b1 > b2)274return 1;275}276return 0;277}278279/**280* Returns a value equal to what {@code b.leftShift(32*ints); return compare(b);}281* would return, but doesn't change the value of {@code b}.282*/283private int compareShifted(MutableBigInteger b, int ints) {284int blen = b.intLen;285int alen = intLen - ints;286if (alen < blen)287return -1;288if (alen > blen)289return 1;290291// Add Integer.MIN_VALUE to make the comparison act as unsigned integer292// comparison.293int[] bval = b.value;294for (int i = offset, j = b.offset; i < alen + offset; i++, j++) {295int b1 = value[i] + 0x80000000;296int b2 = bval[j] + 0x80000000;297if (b1 < b2)298return -1;299if (b1 > b2)300return 1;301}302return 0;303}304305/**306* Compare this against half of a MutableBigInteger object (Needed for307* remainder tests).308* Assumes no leading unnecessary zeros, which holds for results309* from divide().310*/311final int compareHalf(MutableBigInteger b) {312int blen = b.intLen;313int len = intLen;314if (len <= 0)315return blen <= 0 ? 0 : -1;316if (len > blen)317return 1;318if (len < blen - 1)319return -1;320int[] bval = b.value;321int bstart = 0;322int carry = 0;323// Only 2 cases left:len == blen or len == blen - 1324if (len != blen) { // len == blen - 1325if (bval[bstart] == 1) {326++bstart;327carry = 0x80000000;328} else329return -1;330}331// compare values with right-shifted values of b,332// carrying shifted-out bits across words333int[] val = value;334for (int i = offset, j = bstart; i < len + offset;) {335int bv = bval[j++];336long hb = ((bv >>> 1) + carry) & LONG_MASK;337long v = val[i++] & LONG_MASK;338if (v != hb)339return v < hb ? -1 : 1;340carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0341}342return carry == 0 ? 0 : -1;343}344345/**346* Return the index of the lowest set bit in this MutableBigInteger. If the347* magnitude of this MutableBigInteger is zero, -1 is returned.348*/349private final int getLowestSetBit() {350if (intLen == 0)351return -1;352int j, b;353for (j=intLen-1; (j > 0) && (value[j+offset] == 0); j--)354;355b = value[j+offset];356if (b == 0)357return -1;358return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b);359}360361/**362* Return the int in use in this MutableBigInteger at the specified363* index. This method is not used because it is not inlined on all364* platforms.365*/366private final int getInt(int index) {367return value[offset+index];368}369370/**371* Return a long which is equal to the unsigned value of the int in372* use in this MutableBigInteger at the specified index. This method is373* not used because it is not inlined on all platforms.374*/375private final long getLong(int index) {376return value[offset+index] & LONG_MASK;377}378379/**380* Ensure that the MutableBigInteger is in normal form, specifically381* making sure that there are no leading zeros, and that if the382* magnitude is zero, then intLen is zero.383*/384final void normalize() {385if (intLen == 0) {386offset = 0;387return;388}389390int index = offset;391if (value[index] != 0)392return;393394int indexBound = index+intLen;395do {396index++;397} while(index < indexBound && value[index] == 0);398399int numZeros = index - offset;400intLen -= numZeros;401offset = (intLen == 0 ? 0 : offset+numZeros);402}403404/**405* If this MutableBigInteger cannot hold len words, increase the size406* of the value array to len words.407*/408private final void ensureCapacity(int len) {409if (value.length < len) {410value = new int[len];411offset = 0;412intLen = len;413}414}415416/**417* Convert this MutableBigInteger into an int array with no leading418* zeros, of a length that is equal to this MutableBigInteger's intLen.419*/420int[] toIntArray() {421int[] result = new int[intLen];422for(int i=0; i < intLen; i++)423result[i] = value[offset+i];424return result;425}426427/**428* Sets the int at index+offset in this MutableBigInteger to val.429* This does not get inlined on all platforms so it is not used430* as often as originally intended.431*/432void setInt(int index, int val) {433value[offset + index] = val;434}435436/**437* Sets this MutableBigInteger's value array to the specified array.438* The intLen is set to the specified length.439*/440void setValue(int[] val, int length) {441value = val;442intLen = length;443offset = 0;444}445446/**447* Sets this MutableBigInteger's value array to a copy of the specified448* array. The intLen is set to the length of the new array.449*/450void copyValue(MutableBigInteger src) {451int len = src.intLen;452if (value.length < len)453value = new int[len];454System.arraycopy(src.value, src.offset, value, 0, len);455intLen = len;456offset = 0;457}458459/**460* Sets this MutableBigInteger's value array to a copy of the specified461* array. The intLen is set to the length of the specified array.462*/463void copyValue(int[] val) {464int len = val.length;465if (value.length < len)466value = new int[len];467System.arraycopy(val, 0, value, 0, len);468intLen = len;469offset = 0;470}471472/**473* Returns true iff this MutableBigInteger has a value of one.474*/475boolean isOne() {476return (intLen == 1) && (value[offset] == 1);477}478479/**480* Returns true iff this MutableBigInteger has a value of zero.481*/482boolean isZero() {483return (intLen == 0);484}485486/**487* Returns true iff this MutableBigInteger is even.488*/489boolean isEven() {490return (intLen == 0) || ((value[offset + intLen - 1] & 1) == 0);491}492493/**494* Returns true iff this MutableBigInteger is odd.495*/496boolean isOdd() {497return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1);498}499500/**501* Returns true iff this MutableBigInteger is in normal form. A502* MutableBigInteger is in normal form if it has no leading zeros503* after the offset, and intLen + offset <= value.length.504*/505boolean isNormal() {506if (intLen + offset > value.length)507return false;508if (intLen == 0)509return true;510return (value[offset] != 0);511}512513/**514* Returns a String representation of this MutableBigInteger in radix 10.515*/516public String toString() {517BigInteger b = toBigInteger(1);518return b.toString();519}520521/**522* Like {@link #rightShift(int)} but {@code n} can be greater than the length of the number.523*/524void safeRightShift(int n) {525if (n/32 >= intLen) {526reset();527} else {528rightShift(n);529}530}531532/**533* Right shift this MutableBigInteger n bits. The MutableBigInteger is left534* in normal form.535*/536void rightShift(int n) {537if (intLen == 0)538return;539int nInts = n >>> 5;540int nBits = n & 0x1F;541this.intLen -= nInts;542if (nBits == 0)543return;544int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);545if (nBits >= bitsInHighWord) {546this.primitiveLeftShift(32 - nBits);547this.intLen--;548} else {549primitiveRightShift(nBits);550}551}552553/**554* Like {@link #leftShift(int)} but {@code n} can be zero.555*/556void safeLeftShift(int n) {557if (n > 0) {558leftShift(n);559}560}561562/**563* Left shift this MutableBigInteger n bits.564*/565void leftShift(int n) {566/*567* If there is enough storage space in this MutableBigInteger already568* the available space will be used. Space to the right of the used569* ints in the value array is faster to utilize, so the extra space570* will be taken from the right if possible.571*/572if (intLen == 0)573return;574int nInts = n >>> 5;575int nBits = n&0x1F;576int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);577578// If shift can be done without moving words, do so579if (n <= (32-bitsInHighWord)) {580primitiveLeftShift(nBits);581return;582}583584int newLen = intLen + nInts +1;585if (nBits <= (32-bitsInHighWord))586newLen--;587if (value.length < newLen) {588// The array must grow589int[] result = new int[newLen];590for (int i=0; i < intLen; i++)591result[i] = value[offset+i];592setValue(result, newLen);593} else if (value.length - offset >= newLen) {594// Use space on right595for(int i=0; i < newLen - intLen; i++)596value[offset+intLen+i] = 0;597} else {598// Must use space on left599for (int i=0; i < intLen; i++)600value[i] = value[offset+i];601for (int i=intLen; i < newLen; i++)602value[i] = 0;603offset = 0;604}605intLen = newLen;606if (nBits == 0)607return;608if (nBits <= (32-bitsInHighWord))609primitiveLeftShift(nBits);610else611primitiveRightShift(32 -nBits);612}613614/**615* A primitive used for division. This method adds in one multiple of the616* divisor a back to the dividend result at a specified offset. It is used617* when qhat was estimated too large, and must be adjusted.618*/619private int divadd(int[] a, int[] result, int offset) {620long carry = 0;621622for (int j=a.length-1; j >= 0; j--) {623long sum = (a[j] & LONG_MASK) +624(result[j+offset] & LONG_MASK) + carry;625result[j+offset] = (int)sum;626carry = sum >>> 32;627}628return (int)carry;629}630631/**632* This method is used for division. It multiplies an n word input a by one633* word input x, and subtracts the n word product from q. This is needed634* when subtracting qhat*divisor from dividend.635*/636private int mulsub(int[] q, int[] a, int x, int len, int offset) {637long xLong = x & LONG_MASK;638long carry = 0;639offset += len;640641for (int j=len-1; j >= 0; j--) {642long product = (a[j] & LONG_MASK) * xLong + carry;643long difference = q[offset] - product;644q[offset--] = (int)difference;645carry = (product >>> 32)646+ (((difference & LONG_MASK) >647(((~(int)product) & LONG_MASK))) ? 1:0);648}649return (int)carry;650}651652/**653* The method is the same as mulsun, except the fact that q array is not654* updated, the only result of the method is borrow flag.655*/656private int mulsubBorrow(int[] q, int[] a, int x, int len, int offset) {657long xLong = x & LONG_MASK;658long carry = 0;659offset += len;660for (int j=len-1; j >= 0; j--) {661long product = (a[j] & LONG_MASK) * xLong + carry;662long difference = q[offset--] - product;663carry = (product >>> 32)664+ (((difference & LONG_MASK) >665(((~(int)product) & LONG_MASK))) ? 1:0);666}667return (int)carry;668}669670/**671* Right shift this MutableBigInteger n bits, where n is672* less than 32.673* Assumes that intLen > 0, n > 0 for speed674*/675private final void primitiveRightShift(int n) {676int[] val = value;677int n2 = 32 - n;678for (int i=offset+intLen-1, c=val[i]; i > offset; i--) {679int b = c;680c = val[i-1];681val[i] = (c << n2) | (b >>> n);682}683val[offset] >>>= n;684}685686/**687* Left shift this MutableBigInteger n bits, where n is688* less than 32.689* Assumes that intLen > 0, n > 0 for speed690*/691private final void primitiveLeftShift(int n) {692int[] val = value;693int n2 = 32 - n;694for (int i=offset, c=val[i], m=i+intLen-1; i < m; i++) {695int b = c;696c = val[i+1];697val[i] = (b << n) | (c >>> n2);698}699val[offset+intLen-1] <<= n;700}701702/**703* Returns a {@code BigInteger} equal to the {@code n}704* low ints of this number.705*/706private BigInteger getLower(int n) {707if (isZero()) {708return BigInteger.ZERO;709} else if (intLen < n) {710return toBigInteger(1);711} else {712// strip zeros713int len = n;714while (len > 0 && value[offset+intLen-len] == 0)715len--;716int sign = len > 0 ? 1 : 0;717return new BigInteger(Arrays.copyOfRange(value, offset+intLen-len, offset+intLen), sign);718}719}720721/**722* Discards all ints whose index is greater than {@code n}.723*/724private void keepLower(int n) {725if (intLen >= n) {726offset += intLen - n;727intLen = n;728}729}730731/**732* Adds the contents of two MutableBigInteger objects.The result733* is placed within this MutableBigInteger.734* The contents of the addend are not changed.735*/736void add(MutableBigInteger addend) {737int x = intLen;738int y = addend.intLen;739int resultLen = (intLen > addend.intLen ? intLen : addend.intLen);740int[] result = (value.length < resultLen ? new int[resultLen] : value);741742int rstart = result.length-1;743long sum;744long carry = 0;745746// Add common parts of both numbers747while(x > 0 && y > 0) {748x--; y--;749sum = (value[x+offset] & LONG_MASK) +750(addend.value[y+addend.offset] & LONG_MASK) + carry;751result[rstart--] = (int)sum;752carry = sum >>> 32;753}754755// Add remainder of the longer number756while(x > 0) {757x--;758if (carry == 0 && result == value && rstart == (x + offset))759return;760sum = (value[x+offset] & LONG_MASK) + carry;761result[rstart--] = (int)sum;762carry = sum >>> 32;763}764while(y > 0) {765y--;766sum = (addend.value[y+addend.offset] & LONG_MASK) + carry;767result[rstart--] = (int)sum;768carry = sum >>> 32;769}770771if (carry > 0) { // Result must grow in length772resultLen++;773if (result.length < resultLen) {774int temp[] = new int[resultLen];775// Result one word longer from carry-out; copy low-order776// bits into new result.777System.arraycopy(result, 0, temp, 1, result.length);778temp[0] = 1;779result = temp;780} else {781result[rstart--] = 1;782}783}784785value = result;786intLen = resultLen;787offset = result.length - resultLen;788}789790/**791* Adds the value of {@code addend} shifted {@code n} ints to the left.792* Has the same effect as {@code addend.leftShift(32*ints); add(addend);}793* but doesn't change the value of {@code addend}.794*/795void addShifted(MutableBigInteger addend, int n) {796if (addend.isZero()) {797return;798}799800int x = intLen;801int y = addend.intLen + n;802int resultLen = (intLen > y ? intLen : y);803int[] result = (value.length < resultLen ? new int[resultLen] : value);804805int rstart = result.length-1;806long sum;807long carry = 0;808809// Add common parts of both numbers810while (x > 0 && y > 0) {811x--; y--;812int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0;813sum = (value[x+offset] & LONG_MASK) +814(bval & LONG_MASK) + carry;815result[rstart--] = (int)sum;816carry = sum >>> 32;817}818819// Add remainder of the longer number820while (x > 0) {821x--;822if (carry == 0 && result == value && rstart == (x + offset)) {823return;824}825sum = (value[x+offset] & LONG_MASK) + carry;826result[rstart--] = (int)sum;827carry = sum >>> 32;828}829while (y > 0) {830y--;831int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0;832sum = (bval & LONG_MASK) + carry;833result[rstart--] = (int)sum;834carry = sum >>> 32;835}836837if (carry > 0) { // Result must grow in length838resultLen++;839if (result.length < resultLen) {840int temp[] = new int[resultLen];841// Result one word longer from carry-out; copy low-order842// bits into new result.843System.arraycopy(result, 0, temp, 1, result.length);844temp[0] = 1;845result = temp;846} else {847result[rstart--] = 1;848}849}850851value = result;852intLen = resultLen;853offset = result.length - resultLen;854}855856/**857* Like {@link #addShifted(MutableBigInteger, int)} but {@code this.intLen} must858* not be greater than {@code n}. In other words, concatenates {@code this}859* and {@code addend}.860*/861void addDisjoint(MutableBigInteger addend, int n) {862if (addend.isZero())863return;864865int x = intLen;866int y = addend.intLen + n;867int resultLen = (intLen > y ? intLen : y);868int[] result;869if (value.length < resultLen)870result = new int[resultLen];871else {872result = value;873Arrays.fill(value, offset+intLen, value.length, 0);874}875876int rstart = result.length-1;877878// copy from this if needed879System.arraycopy(value, offset, result, rstart+1-x, x);880y -= x;881rstart -= x;882883int len = Math.min(y, addend.value.length-addend.offset);884System.arraycopy(addend.value, addend.offset, result, rstart+1-y, len);885886// zero the gap887for (int i=rstart+1-y+len; i < rstart+1; i++)888result[i] = 0;889890value = result;891intLen = resultLen;892offset = result.length - resultLen;893}894895/**896* Adds the low {@code n} ints of {@code addend}.897*/898void addLower(MutableBigInteger addend, int n) {899MutableBigInteger a = new MutableBigInteger(addend);900if (a.offset + a.intLen >= n) {901a.offset = a.offset + a.intLen - n;902a.intLen = n;903}904a.normalize();905add(a);906}907908/**909* Subtracts the smaller of this and b from the larger and places the910* result into this MutableBigInteger.911*/912int subtract(MutableBigInteger b) {913MutableBigInteger a = this;914915int[] result = value;916int sign = a.compare(b);917918if (sign == 0) {919reset();920return 0;921}922if (sign < 0) {923MutableBigInteger tmp = a;924a = b;925b = tmp;926}927928int resultLen = a.intLen;929if (result.length < resultLen)930result = new int[resultLen];931932long diff = 0;933int x = a.intLen;934int y = b.intLen;935int rstart = result.length - 1;936937// Subtract common parts of both numbers938while (y > 0) {939x--; y--;940941diff = (a.value[x+a.offset] & LONG_MASK) -942(b.value[y+b.offset] & LONG_MASK) - ((int)-(diff>>32));943result[rstart--] = (int)diff;944}945// Subtract remainder of longer number946while (x > 0) {947x--;948diff = (a.value[x+a.offset] & LONG_MASK) - ((int)-(diff>>32));949result[rstart--] = (int)diff;950}951952value = result;953intLen = resultLen;954offset = value.length - resultLen;955normalize();956return sign;957}958959/**960* Subtracts the smaller of a and b from the larger and places the result961* into the larger. Returns 1 if the answer is in a, -1 if in b, 0 if no962* operation was performed.963*/964private int difference(MutableBigInteger b) {965MutableBigInteger a = this;966int sign = a.compare(b);967if (sign == 0)968return 0;969if (sign < 0) {970MutableBigInteger tmp = a;971a = b;972b = tmp;973}974975long diff = 0;976int x = a.intLen;977int y = b.intLen;978979// Subtract common parts of both numbers980while (y > 0) {981x--; y--;982diff = (a.value[a.offset+ x] & LONG_MASK) -983(b.value[b.offset+ y] & LONG_MASK) - ((int)-(diff>>32));984a.value[a.offset+x] = (int)diff;985}986// Subtract remainder of longer number987while (x > 0) {988x--;989diff = (a.value[a.offset+ x] & LONG_MASK) - ((int)-(diff>>32));990a.value[a.offset+x] = (int)diff;991}992993a.normalize();994return sign;995}996997/**998* Multiply the contents of two MutableBigInteger objects. The result is999* placed into MutableBigInteger z. The contents of y are not changed.1000*/1001void multiply(MutableBigInteger y, MutableBigInteger z) {1002int xLen = intLen;1003int yLen = y.intLen;1004int newLen = xLen + yLen;10051006// Put z into an appropriate state to receive product1007if (z.value.length < newLen)1008z.value = new int[newLen];1009z.offset = 0;1010z.intLen = newLen;10111012// The first iteration is hoisted out of the loop to avoid extra add1013long carry = 0;1014for (int j=yLen-1, k=yLen+xLen-1; j >= 0; j--, k--) {1015long product = (y.value[j+y.offset] & LONG_MASK) *1016(value[xLen-1+offset] & LONG_MASK) + carry;1017z.value[k] = (int)product;1018carry = product >>> 32;1019}1020z.value[xLen-1] = (int)carry;10211022// Perform the multiplication word by word1023for (int i = xLen-2; i >= 0; i--) {1024carry = 0;1025for (int j=yLen-1, k=yLen+i; j >= 0; j--, k--) {1026long product = (y.value[j+y.offset] & LONG_MASK) *1027(value[i+offset] & LONG_MASK) +1028(z.value[k] & LONG_MASK) + carry;1029z.value[k] = (int)product;1030carry = product >>> 32;1031}1032z.value[i] = (int)carry;1033}10341035// Remove leading zeros from product1036z.normalize();1037}10381039/**1040* Multiply the contents of this MutableBigInteger by the word y. The1041* result is placed into z.1042*/1043void mul(int y, MutableBigInteger z) {1044if (y == 1) {1045z.copyValue(this);1046return;1047}10481049if (y == 0) {1050z.clear();1051return;1052}10531054// Perform the multiplication word by word1055long ylong = y & LONG_MASK;1056int[] zval = (z.value.length < intLen+1 ? new int[intLen + 1]1057: z.value);1058long carry = 0;1059for (int i = intLen-1; i >= 0; i--) {1060long product = ylong * (value[i+offset] & LONG_MASK) + carry;1061zval[i+1] = (int)product;1062carry = product >>> 32;1063}10641065if (carry == 0) {1066z.offset = 1;1067z.intLen = intLen;1068} else {1069z.offset = 0;1070z.intLen = intLen + 1;1071zval[0] = (int)carry;1072}1073z.value = zval;1074}10751076/**1077* This method is used for division of an n word dividend by a one word1078* divisor. The quotient is placed into quotient. The one word divisor is1079* specified by divisor.1080*1081* @return the remainder of the division is returned.1082*1083*/1084int divideOneWord(int divisor, MutableBigInteger quotient) {1085long divisorLong = divisor & LONG_MASK;10861087// Special case of one word dividend1088if (intLen == 1) {1089long dividendValue = value[offset] & LONG_MASK;1090int q = (int) (dividendValue / divisorLong);1091int r = (int) (dividendValue - q * divisorLong);1092quotient.value[0] = q;1093quotient.intLen = (q == 0) ? 0 : 1;1094quotient.offset = 0;1095return r;1096}10971098if (quotient.value.length < intLen)1099quotient.value = new int[intLen];1100quotient.offset = 0;1101quotient.intLen = intLen;11021103// Normalize the divisor1104int shift = Integer.numberOfLeadingZeros(divisor);11051106int rem = value[offset];1107long remLong = rem & LONG_MASK;1108if (remLong < divisorLong) {1109quotient.value[0] = 0;1110} else {1111quotient.value[0] = (int)(remLong / divisorLong);1112rem = (int) (remLong - (quotient.value[0] * divisorLong));1113remLong = rem & LONG_MASK;1114}1115int xlen = intLen;1116while (--xlen > 0) {1117long dividendEstimate = (remLong << 32) |1118(value[offset + intLen - xlen] & LONG_MASK);1119int q;1120if (dividendEstimate >= 0) {1121q = (int) (dividendEstimate / divisorLong);1122rem = (int) (dividendEstimate - q * divisorLong);1123} else {1124long tmp = divWord(dividendEstimate, divisor);1125q = (int) (tmp & LONG_MASK);1126rem = (int) (tmp >>> 32);1127}1128quotient.value[intLen - xlen] = q;1129remLong = rem & LONG_MASK;1130}11311132quotient.normalize();1133// Unnormalize1134if (shift > 0)1135return rem % divisor;1136else1137return rem;1138}11391140/**1141* Calculates the quotient of this div b and places the quotient in the1142* provided MutableBigInteger objects and the remainder object is returned.1143*1144*/1145MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) {1146return divide(b,quotient,true);1147}11481149MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder) {1150if (b.intLen < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD ||1151intLen - b.intLen < BigInteger.BURNIKEL_ZIEGLER_OFFSET) {1152return divideKnuth(b, quotient, needRemainder);1153} else {1154return divideAndRemainderBurnikelZiegler(b, quotient);1155}1156}11571158/**1159* @see #divideKnuth(MutableBigInteger, MutableBigInteger, boolean)1160*/1161MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient) {1162return divideKnuth(b,quotient,true);1163}11641165/**1166* Calculates the quotient of this div b and places the quotient in the1167* provided MutableBigInteger objects and the remainder object is returned.1168*1169* Uses Algorithm D in Knuth section 4.3.1.1170* Many optimizations to that algorithm have been adapted from the Colin1171* Plumb C library.1172* It special cases one word divisors for speed. The content of b is not1173* changed.1174*1175*/1176MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder) {1177if (b.intLen == 0)1178throw new ArithmeticException("BigInteger divide by zero");11791180// Dividend is zero1181if (intLen == 0) {1182quotient.intLen = quotient.offset = 0;1183return needRemainder ? new MutableBigInteger() : null;1184}11851186int cmp = compare(b);1187// Dividend less than divisor1188if (cmp < 0) {1189quotient.intLen = quotient.offset = 0;1190return needRemainder ? new MutableBigInteger(this) : null;1191}1192// Dividend equal to divisor1193if (cmp == 0) {1194quotient.value[0] = quotient.intLen = 1;1195quotient.offset = 0;1196return needRemainder ? new MutableBigInteger() : null;1197}11981199quotient.clear();1200// Special case one word divisor1201if (b.intLen == 1) {1202int r = divideOneWord(b.value[b.offset], quotient);1203if(needRemainder) {1204if (r == 0)1205return new MutableBigInteger();1206return new MutableBigInteger(r);1207} else {1208return null;1209}1210}12111212// Cancel common powers of two if we're above the KNUTH_POW2_* thresholds1213if (intLen >= KNUTH_POW2_THRESH_LEN) {1214int trailingZeroBits = Math.min(getLowestSetBit(), b.getLowestSetBit());1215if (trailingZeroBits >= KNUTH_POW2_THRESH_ZEROS*32) {1216MutableBigInteger a = new MutableBigInteger(this);1217b = new MutableBigInteger(b);1218a.rightShift(trailingZeroBits);1219b.rightShift(trailingZeroBits);1220MutableBigInteger r = a.divideKnuth(b, quotient);1221r.leftShift(trailingZeroBits);1222return r;1223}1224}12251226return divideMagnitude(b, quotient, needRemainder);1227}12281229/**1230* Computes {@code this/b} and {@code this%b} using the1231* <a href="http://cr.yp.to/bib/1998/burnikel.ps"> Burnikel-Ziegler algorithm</a>.1232* This method implements algorithm 3 from pg. 9 of the Burnikel-Ziegler paper.1233* The parameter beta was chosen to b 2<sup>32</sup> so almost all shifts are1234* multiples of 32 bits.<br/>1235* {@code this} and {@code b} must be nonnegative.1236* @param b the divisor1237* @param quotient output parameter for {@code this/b}1238* @return the remainder1239*/1240MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) {1241int r = intLen;1242int s = b.intLen;12431244// Clear the quotient1245quotient.offset = quotient.intLen = 0;12461247if (r < s) {1248return this;1249} else {1250// Unlike Knuth division, we don't check for common powers of two here because1251// BZ already runs faster if both numbers contain powers of two and cancelling them has no1252// additional benefit.12531254// step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s}1255int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD));12561257int j = (s+m-1) / m; // step 2a: j = ceil(s/m)1258int n = j * m; // step 2b: block length in 32-bit units1259long n32 = 32L * n; // block length in bits1260int sigma = (int) Math.max(0, n32 - b.bitLength()); // step 3: sigma = max{T | (2^T)*B < beta^n}1261MutableBigInteger bShifted = new MutableBigInteger(b);1262bShifted.safeLeftShift(sigma); // step 4a: shift b so its length is a multiple of n1263MutableBigInteger aShifted = new MutableBigInteger (this);1264aShifted.safeLeftShift(sigma); // step 4b: shift a by the same amount12651266// step 5: t is the number of blocks needed to accommodate a plus one additional bit1267int t = (int) ((aShifted.bitLength()+n32) / n32);1268if (t < 2) {1269t = 2;1270}12711272// step 6: conceptually split a into blocks a[t-1], ..., a[0]1273MutableBigInteger a1 = aShifted.getBlock(t-1, t, n); // the most significant block of a12741275// step 7: z[t-2] = [a[t-1], a[t-2]]1276MutableBigInteger z = aShifted.getBlock(t-2, t, n); // the second to most significant block1277z.addDisjoint(a1, n); // z[t-2]12781279// do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers1280MutableBigInteger qi = new MutableBigInteger();1281MutableBigInteger ri;1282for (int i=t-2; i > 0; i--) {1283// step 8a: compute (qi,ri) such that z=b*qi+ri1284ri = z.divide2n1n(bShifted, qi);12851286// step 8b: z = [ri, a[i-1]]1287z = aShifted.getBlock(i-1, t, n); // a[i-1]1288z.addDisjoint(ri, n);1289quotient.addShifted(qi, i*n); // update q (part of step 9)1290}1291// final iteration of step 8: do the loop one more time for i=0 but leave z unchanged1292ri = z.divide2n1n(bShifted, qi);1293quotient.add(qi);12941295ri.rightShift(sigma); // step 9: a and b were shifted, so shift back1296return ri;1297}1298}12991300/**1301* This method implements algorithm 1 from pg. 4 of the Burnikel-Ziegler paper.1302* It divides a 2n-digit number by a n-digit number.<br/>1303* The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.1304* <br/>1305* {@code this} must be a nonnegative number such that {@code this.bitLength() <= 2*b.bitLength()}1306* @param b a positive number such that {@code b.bitLength()} is even1307* @param quotient output parameter for {@code this/b}1308* @return {@code this%b}1309*/1310private MutableBigInteger divide2n1n(MutableBigInteger b, MutableBigInteger quotient) {1311int n = b.intLen;13121313// step 1: base case1314if (n%2 != 0 || n < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD) {1315return divideKnuth(b, quotient);1316}13171318// step 2: view this as [a1,a2,a3,a4] where each ai is n/2 ints or less1319MutableBigInteger aUpper = new MutableBigInteger(this);1320aUpper.safeRightShift(32*(n/2)); // aUpper = [a1,a2,a3]1321keepLower(n/2); // this = a413221323// step 3: q1=aUpper/b, r1=aUpper%b1324MutableBigInteger q1 = new MutableBigInteger();1325MutableBigInteger r1 = aUpper.divide3n2n(b, q1);13261327// step 4: quotient=[r1,this]/b, r2=[r1,this]%b1328addDisjoint(r1, n/2); // this = [r1,this]1329MutableBigInteger r2 = divide3n2n(b, quotient);13301331// step 5: let quotient=[q1,quotient] and return r21332quotient.addDisjoint(q1, n/2);1333return r2;1334}13351336/**1337* This method implements algorithm 2 from pg. 5 of the Burnikel-Ziegler paper.1338* It divides a 3n-digit number by a 2n-digit number.<br/>1339* The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.<br/>1340* <br/>1341* {@code this} must be a nonnegative number such that {@code 2*this.bitLength() <= 3*b.bitLength()}1342* @param quotient output parameter for {@code this/b}1343* @return {@code this%b}1344*/1345private MutableBigInteger divide3n2n(MutableBigInteger b, MutableBigInteger quotient) {1346int n = b.intLen / 2; // half the length of b in ints13471348// step 1: view this as [a1,a2,a3] where each ai is n ints or less; let a12=[a1,a2]1349MutableBigInteger a12 = new MutableBigInteger(this);1350a12.safeRightShift(32*n);13511352// step 2: view b as [b1,b2] where each bi is n ints or less1353MutableBigInteger b1 = new MutableBigInteger(b);1354b1.safeRightShift(n * 32);1355BigInteger b2 = b.getLower(n);13561357MutableBigInteger r;1358MutableBigInteger d;1359if (compareShifted(b, n) < 0) {1360// step 3a: if a1<b1, let quotient=a12/b1 and r=a12%b11361r = a12.divide2n1n(b1, quotient);13621363// step 4: d=quotient*b21364d = new MutableBigInteger(quotient.toBigInteger().multiply(b2));1365} else {1366// step 3b: if a1>=b1, let quotient=beta^n-1 and r=a12-b1*2^n+b11367quotient.ones(n);1368a12.add(b1);1369b1.leftShift(32*n);1370a12.subtract(b1);1371r = a12;13721373// step 4: d=quotient*b2=(b2 << 32*n) - b21374d = new MutableBigInteger(b2);1375d.leftShift(32 * n);1376d.subtract(new MutableBigInteger(b2));1377}13781379// step 5: r = r*beta^n + a3 - d (paper says a4)1380// However, don't subtract d until after the while loop so r doesn't become negative1381r.leftShift(32 * n);1382r.addLower(this, n);13831384// step 6: add b until r>=d1385while (r.compare(d) < 0) {1386r.add(b);1387quotient.subtract(MutableBigInteger.ONE);1388}1389r.subtract(d);13901391return r;1392}13931394/**1395* Returns a {@code MutableBigInteger} containing {@code blockLength} ints from1396* {@code this} number, starting at {@code index*blockLength}.<br/>1397* Used by Burnikel-Ziegler division.1398* @param index the block index1399* @param numBlocks the total number of blocks in {@code this} number1400* @param blockLength length of one block in units of 32 bits1401* @return1402*/1403private MutableBigInteger getBlock(int index, int numBlocks, int blockLength) {1404int blockStart = index * blockLength;1405if (blockStart >= intLen) {1406return new MutableBigInteger();1407}14081409int blockEnd;1410if (index == numBlocks-1) {1411blockEnd = intLen;1412} else {1413blockEnd = (index+1) * blockLength;1414}1415if (blockEnd > intLen) {1416return new MutableBigInteger();1417}14181419int[] newVal = Arrays.copyOfRange(value, offset+intLen-blockEnd, offset+intLen-blockStart);1420return new MutableBigInteger(newVal);1421}14221423/** @see BigInteger#bitLength() */1424long bitLength() {1425if (intLen == 0)1426return 0;1427return intLen*32L - Integer.numberOfLeadingZeros(value[offset]);1428}14291430/**1431* Internally used to calculate the quotient of this div v and places the1432* quotient in the provided MutableBigInteger object and the remainder is1433* returned.1434*1435* @return the remainder of the division will be returned.1436*/1437long divide(long v, MutableBigInteger quotient) {1438if (v == 0)1439throw new ArithmeticException("BigInteger divide by zero");14401441// Dividend is zero1442if (intLen == 0) {1443quotient.intLen = quotient.offset = 0;1444return 0;1445}1446if (v < 0)1447v = -v;14481449int d = (int)(v >>> 32);1450quotient.clear();1451// Special case on word divisor1452if (d == 0)1453return divideOneWord((int)v, quotient) & LONG_MASK;1454else {1455return divideLongMagnitude(v, quotient).toLong();1456}1457}14581459private static void copyAndShift(int[] src, int srcFrom, int srcLen, int[] dst, int dstFrom, int shift) {1460int n2 = 32 - shift;1461int c=src[srcFrom];1462for (int i=0; i < srcLen-1; i++) {1463int b = c;1464c = src[++srcFrom];1465dst[dstFrom+i] = (b << shift) | (c >>> n2);1466}1467dst[dstFrom+srcLen-1] = c << shift;1468}14691470/**1471* Divide this MutableBigInteger by the divisor.1472* The quotient will be placed into the provided quotient object &1473* the remainder object is returned.1474*/1475private MutableBigInteger divideMagnitude(MutableBigInteger div,1476MutableBigInteger quotient,1477boolean needRemainder ) {1478// assert div.intLen > 11479// D1 normalize the divisor1480int shift = Integer.numberOfLeadingZeros(div.value[div.offset]);1481// Copy divisor value to protect divisor1482final int dlen = div.intLen;1483int[] divisor;1484MutableBigInteger rem; // Remainder starts as dividend with space for a leading zero1485if (shift > 0) {1486divisor = new int[dlen];1487copyAndShift(div.value,div.offset,dlen,divisor,0,shift);1488if (Integer.numberOfLeadingZeros(value[offset]) >= shift) {1489int[] remarr = new int[intLen + 1];1490rem = new MutableBigInteger(remarr);1491rem.intLen = intLen;1492rem.offset = 1;1493copyAndShift(value,offset,intLen,remarr,1,shift);1494} else {1495int[] remarr = new int[intLen + 2];1496rem = new MutableBigInteger(remarr);1497rem.intLen = intLen+1;1498rem.offset = 1;1499int rFrom = offset;1500int c=0;1501int n2 = 32 - shift;1502for (int i=1; i < intLen+1; i++,rFrom++) {1503int b = c;1504c = value[rFrom];1505remarr[i] = (b << shift) | (c >>> n2);1506}1507remarr[intLen+1] = c << shift;1508}1509} else {1510divisor = Arrays.copyOfRange(div.value, div.offset, div.offset + div.intLen);1511rem = new MutableBigInteger(new int[intLen + 1]);1512System.arraycopy(value, offset, rem.value, 1, intLen);1513rem.intLen = intLen;1514rem.offset = 1;1515}15161517int nlen = rem.intLen;15181519// Set the quotient size1520final int limit = nlen - dlen + 1;1521if (quotient.value.length < limit) {1522quotient.value = new int[limit];1523quotient.offset = 0;1524}1525quotient.intLen = limit;1526int[] q = quotient.value;152715281529// Must insert leading 0 in rem if its length did not change1530if (rem.intLen == nlen) {1531rem.offset = 0;1532rem.value[0] = 0;1533rem.intLen++;1534}15351536int dh = divisor[0];1537long dhLong = dh & LONG_MASK;1538int dl = divisor[1];15391540// D2 Initialize j1541for (int j=0; j < limit-1; j++) {1542// D3 Calculate qhat1543// estimate qhat1544int qhat = 0;1545int qrem = 0;1546boolean skipCorrection = false;1547int nh = rem.value[j+rem.offset];1548int nh2 = nh + 0x80000000;1549int nm = rem.value[j+1+rem.offset];15501551if (nh == dh) {1552qhat = ~0;1553qrem = nh + nm;1554skipCorrection = qrem + 0x80000000 < nh2;1555} else {1556long nChunk = (((long)nh) << 32) | (nm & LONG_MASK);1557if (nChunk >= 0) {1558qhat = (int) (nChunk / dhLong);1559qrem = (int) (nChunk - (qhat * dhLong));1560} else {1561long tmp = divWord(nChunk, dh);1562qhat = (int) (tmp & LONG_MASK);1563qrem = (int) (tmp >>> 32);1564}1565}15661567if (qhat == 0)1568continue;15691570if (!skipCorrection) { // Correct qhat1571long nl = rem.value[j+2+rem.offset] & LONG_MASK;1572long rs = ((qrem & LONG_MASK) << 32) | nl;1573long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);15741575if (unsignedLongCompare(estProduct, rs)) {1576qhat--;1577qrem = (int)((qrem & LONG_MASK) + dhLong);1578if ((qrem & LONG_MASK) >= dhLong) {1579estProduct -= (dl & LONG_MASK);1580rs = ((qrem & LONG_MASK) << 32) | nl;1581if (unsignedLongCompare(estProduct, rs))1582qhat--;1583}1584}1585}15861587// D4 Multiply and subtract1588rem.value[j+rem.offset] = 0;1589int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset);15901591// D5 Test remainder1592if (borrow + 0x80000000 > nh2) {1593// D6 Add back1594divadd(divisor, rem.value, j+1+rem.offset);1595qhat--;1596}15971598// Store the quotient digit1599q[j] = qhat;1600} // D7 loop on j1601// D3 Calculate qhat1602// estimate qhat1603int qhat = 0;1604int qrem = 0;1605boolean skipCorrection = false;1606int nh = rem.value[limit - 1 + rem.offset];1607int nh2 = nh + 0x80000000;1608int nm = rem.value[limit + rem.offset];16091610if (nh == dh) {1611qhat = ~0;1612qrem = nh + nm;1613skipCorrection = qrem + 0x80000000 < nh2;1614} else {1615long nChunk = (((long) nh) << 32) | (nm & LONG_MASK);1616if (nChunk >= 0) {1617qhat = (int) (nChunk / dhLong);1618qrem = (int) (nChunk - (qhat * dhLong));1619} else {1620long tmp = divWord(nChunk, dh);1621qhat = (int) (tmp & LONG_MASK);1622qrem = (int) (tmp >>> 32);1623}1624}1625if (qhat != 0) {1626if (!skipCorrection) { // Correct qhat1627long nl = rem.value[limit + 1 + rem.offset] & LONG_MASK;1628long rs = ((qrem & LONG_MASK) << 32) | nl;1629long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);16301631if (unsignedLongCompare(estProduct, rs)) {1632qhat--;1633qrem = (int) ((qrem & LONG_MASK) + dhLong);1634if ((qrem & LONG_MASK) >= dhLong) {1635estProduct -= (dl & LONG_MASK);1636rs = ((qrem & LONG_MASK) << 32) | nl;1637if (unsignedLongCompare(estProduct, rs))1638qhat--;1639}1640}1641}164216431644// D4 Multiply and subtract1645int borrow;1646rem.value[limit - 1 + rem.offset] = 0;1647if(needRemainder)1648borrow = mulsub(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset);1649else1650borrow = mulsubBorrow(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset);16511652// D5 Test remainder1653if (borrow + 0x80000000 > nh2) {1654// D6 Add back1655if(needRemainder)1656divadd(divisor, rem.value, limit - 1 + 1 + rem.offset);1657qhat--;1658}16591660// Store the quotient digit1661q[(limit - 1)] = qhat;1662}166316641665if (needRemainder) {1666// D8 Unnormalize1667if (shift > 0)1668rem.rightShift(shift);1669rem.normalize();1670}1671quotient.normalize();1672return needRemainder ? rem : null;1673}16741675/**1676* Divide this MutableBigInteger by the divisor represented by positive long1677* value. The quotient will be placed into the provided quotient object &1678* the remainder object is returned.1679*/1680private MutableBigInteger divideLongMagnitude(long ldivisor, MutableBigInteger quotient) {1681// Remainder starts as dividend with space for a leading zero1682MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]);1683System.arraycopy(value, offset, rem.value, 1, intLen);1684rem.intLen = intLen;1685rem.offset = 1;16861687int nlen = rem.intLen;16881689int limit = nlen - 2 + 1;1690if (quotient.value.length < limit) {1691quotient.value = new int[limit];1692quotient.offset = 0;1693}1694quotient.intLen = limit;1695int[] q = quotient.value;16961697// D1 normalize the divisor1698int shift = Long.numberOfLeadingZeros(ldivisor);1699if (shift > 0) {1700ldivisor<<=shift;1701rem.leftShift(shift);1702}17031704// Must insert leading 0 in rem if its length did not change1705if (rem.intLen == nlen) {1706rem.offset = 0;1707rem.value[0] = 0;1708rem.intLen++;1709}17101711int dh = (int)(ldivisor >>> 32);1712long dhLong = dh & LONG_MASK;1713int dl = (int)(ldivisor & LONG_MASK);17141715// D2 Initialize j1716for (int j = 0; j < limit; j++) {1717// D3 Calculate qhat1718// estimate qhat1719int qhat = 0;1720int qrem = 0;1721boolean skipCorrection = false;1722int nh = rem.value[j + rem.offset];1723int nh2 = nh + 0x80000000;1724int nm = rem.value[j + 1 + rem.offset];17251726if (nh == dh) {1727qhat = ~0;1728qrem = nh + nm;1729skipCorrection = qrem + 0x80000000 < nh2;1730} else {1731long nChunk = (((long) nh) << 32) | (nm & LONG_MASK);1732if (nChunk >= 0) {1733qhat = (int) (nChunk / dhLong);1734qrem = (int) (nChunk - (qhat * dhLong));1735} else {1736long tmp = divWord(nChunk, dh);1737qhat =(int)(tmp & LONG_MASK);1738qrem = (int)(tmp>>>32);1739}1740}17411742if (qhat == 0)1743continue;17441745if (!skipCorrection) { // Correct qhat1746long nl = rem.value[j + 2 + rem.offset] & LONG_MASK;1747long rs = ((qrem & LONG_MASK) << 32) | nl;1748long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);17491750if (unsignedLongCompare(estProduct, rs)) {1751qhat--;1752qrem = (int) ((qrem & LONG_MASK) + dhLong);1753if ((qrem & LONG_MASK) >= dhLong) {1754estProduct -= (dl & LONG_MASK);1755rs = ((qrem & LONG_MASK) << 32) | nl;1756if (unsignedLongCompare(estProduct, rs))1757qhat--;1758}1759}1760}17611762// D4 Multiply and subtract1763rem.value[j + rem.offset] = 0;1764int borrow = mulsubLong(rem.value, dh, dl, qhat, j + rem.offset);17651766// D5 Test remainder1767if (borrow + 0x80000000 > nh2) {1768// D6 Add back1769divaddLong(dh,dl, rem.value, j + 1 + rem.offset);1770qhat--;1771}17721773// Store the quotient digit1774q[j] = qhat;1775} // D7 loop on j17761777// D8 Unnormalize1778if (shift > 0)1779rem.rightShift(shift);17801781quotient.normalize();1782rem.normalize();1783return rem;1784}17851786/**1787* A primitive used for division by long.1788* Specialized version of the method divadd.1789* dh is a high part of the divisor, dl is a low part1790*/1791private int divaddLong(int dh, int dl, int[] result, int offset) {1792long carry = 0;17931794long sum = (dl & LONG_MASK) + (result[1+offset] & LONG_MASK);1795result[1+offset] = (int)sum;17961797sum = (dh & LONG_MASK) + (result[offset] & LONG_MASK) + carry;1798result[offset] = (int)sum;1799carry = sum >>> 32;1800return (int)carry;1801}18021803/**1804* This method is used for division by long.1805* Specialized version of the method sulsub.1806* dh is a high part of the divisor, dl is a low part1807*/1808private int mulsubLong(int[] q, int dh, int dl, int x, int offset) {1809long xLong = x & LONG_MASK;1810offset += 2;1811long product = (dl & LONG_MASK) * xLong;1812long difference = q[offset] - product;1813q[offset--] = (int)difference;1814long carry = (product >>> 32)1815+ (((difference & LONG_MASK) >1816(((~(int)product) & LONG_MASK))) ? 1:0);1817product = (dh & LONG_MASK) * xLong + carry;1818difference = q[offset] - product;1819q[offset--] = (int)difference;1820carry = (product >>> 32)1821+ (((difference & LONG_MASK) >1822(((~(int)product) & LONG_MASK))) ? 1:0);1823return (int)carry;1824}18251826/**1827* Compare two longs as if they were unsigned.1828* Returns true iff one is bigger than two.1829*/1830private boolean unsignedLongCompare(long one, long two) {1831return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);1832}18331834/**1835* This method divides a long quantity by an int to estimate1836* qhat for two multi precision numbers. It is used when1837* the signed value of n is less than zero.1838* Returns long value where high 32 bits contain remainder value and1839* low 32 bits contain quotient value.1840*/1841static long divWord(long n, int d) {1842long dLong = d & LONG_MASK;1843long r;1844long q;1845if (dLong == 1) {1846q = (int)n;1847r = 0;1848return (r << 32) | (q & LONG_MASK);1849}18501851// Approximate the quotient and remainder1852q = (n >>> 1) / (dLong >>> 1);1853r = n - q*dLong;18541855// Correct the approximation1856while (r < 0) {1857r += dLong;1858q--;1859}1860while (r >= dLong) {1861r -= dLong;1862q++;1863}1864// n - q*dlong == r && 0 <= r <dLong, hence we're done.1865return (r << 32) | (q & LONG_MASK);1866}18671868/**1869* Calculate GCD of this and b. This and b are changed by the computation.1870*/1871MutableBigInteger hybridGCD(MutableBigInteger b) {1872// Use Euclid's algorithm until the numbers are approximately the1873// same length, then use the binary GCD algorithm to find the GCD.1874MutableBigInteger a = this;1875MutableBigInteger q = new MutableBigInteger();18761877while (b.intLen != 0) {1878if (Math.abs(a.intLen - b.intLen) < 2)1879return a.binaryGCD(b);18801881MutableBigInteger r = a.divide(b, q);1882a = b;1883b = r;1884}1885return a;1886}18871888/**1889* Calculate GCD of this and v.1890* Assumes that this and v are not zero.1891*/1892private MutableBigInteger binaryGCD(MutableBigInteger v) {1893// Algorithm B from Knuth section 4.5.21894MutableBigInteger u = this;1895MutableBigInteger r = new MutableBigInteger();18961897// step B11898int s1 = u.getLowestSetBit();1899int s2 = v.getLowestSetBit();1900int k = (s1 < s2) ? s1 : s2;1901if (k != 0) {1902u.rightShift(k);1903v.rightShift(k);1904}19051906// step B21907boolean uOdd = (k == s1);1908MutableBigInteger t = uOdd ? v: u;1909int tsign = uOdd ? -1 : 1;19101911int lb;1912while ((lb = t.getLowestSetBit()) >= 0) {1913// steps B3 and B41914t.rightShift(lb);1915// step B51916if (tsign > 0)1917u = t;1918else1919v = t;19201921// Special case one word numbers1922if (u.intLen < 2 && v.intLen < 2) {1923int x = u.value[u.offset];1924int y = v.value[v.offset];1925x = binaryGcd(x, y);1926r.value[0] = x;1927r.intLen = 1;1928r.offset = 0;1929if (k > 0)1930r.leftShift(k);1931return r;1932}19331934// step B61935if ((tsign = u.difference(v)) == 0)1936break;1937t = (tsign >= 0) ? u : v;1938}19391940if (k > 0)1941u.leftShift(k);1942return u;1943}19441945/**1946* Calculate GCD of a and b interpreted as unsigned integers.1947*/1948static int binaryGcd(int a, int b) {1949if (b == 0)1950return a;1951if (a == 0)1952return b;19531954// Right shift a & b till their last bits equal to 1.1955int aZeros = Integer.numberOfTrailingZeros(a);1956int bZeros = Integer.numberOfTrailingZeros(b);1957a >>>= aZeros;1958b >>>= bZeros;19591960int t = (aZeros < bZeros ? aZeros : bZeros);19611962while (a != b) {1963if ((a+0x80000000) > (b+0x80000000)) { // a > b as unsigned1964a -= b;1965a >>>= Integer.numberOfTrailingZeros(a);1966} else {1967b -= a;1968b >>>= Integer.numberOfTrailingZeros(b);1969}1970}1971return a<<t;1972}19731974/**1975* Returns the modInverse of this mod p. This and p are not affected by1976* the operation.1977*/1978MutableBigInteger mutableModInverse(MutableBigInteger p) {1979// Modulus is odd, use Schroeppel's algorithm1980if (p.isOdd())1981return modInverse(p);19821983// Base and modulus are even, throw exception1984if (isEven())1985throw new ArithmeticException("BigInteger not invertible.");19861987// Get even part of modulus expressed as a power of 21988int powersOf2 = p.getLowestSetBit();19891990// Construct odd part of modulus1991MutableBigInteger oddMod = new MutableBigInteger(p);1992oddMod.rightShift(powersOf2);19931994if (oddMod.isOne())1995return modInverseMP2(powersOf2);19961997// Calculate 1/a mod oddMod1998MutableBigInteger oddPart = modInverse(oddMod);19992000// Calculate 1/a mod evenMod2001MutableBigInteger evenPart = modInverseMP2(powersOf2);20022003// Combine the results using Chinese Remainder Theorem2004MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2);2005MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2);20062007MutableBigInteger temp1 = new MutableBigInteger();2008MutableBigInteger temp2 = new MutableBigInteger();2009MutableBigInteger result = new MutableBigInteger();20102011oddPart.leftShift(powersOf2);2012oddPart.multiply(y1, result);20132014evenPart.multiply(oddMod, temp1);2015temp1.multiply(y2, temp2);20162017result.add(temp2);2018return result.divide(p, temp1);2019}20202021/*2022* Calculate the multiplicative inverse of this mod 2^k.2023*/2024MutableBigInteger modInverseMP2(int k) {2025if (isEven())2026throw new ArithmeticException("Non-invertible. (GCD != 1)");20272028if (k > 64)2029return euclidModInverse(k);20302031int t = inverseMod32(value[offset+intLen-1]);20322033if (k < 33) {2034t = (k == 32 ? t : t & ((1 << k) - 1));2035return new MutableBigInteger(t);2036}20372038long pLong = (value[offset+intLen-1] & LONG_MASK);2039if (intLen > 1)2040pLong |= ((long)value[offset+intLen-2] << 32);2041long tLong = t & LONG_MASK;2042tLong = tLong * (2 - pLong * tLong); // 1 more Newton iter step2043tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1));20442045MutableBigInteger result = new MutableBigInteger(new int[2]);2046result.value[0] = (int)(tLong >>> 32);2047result.value[1] = (int)tLong;2048result.intLen = 2;2049result.normalize();2050return result;2051}20522053/**2054* Returns the multiplicative inverse of val mod 2^32. Assumes val is odd.2055*/2056static int inverseMod32(int val) {2057// Newton's iteration!2058int t = val;2059t *= 2 - val*t;2060t *= 2 - val*t;2061t *= 2 - val*t;2062t *= 2 - val*t;2063return t;2064}20652066/**2067* Returns the multiplicative inverse of val mod 2^64. Assumes val is odd.2068*/2069static long inverseMod64(long val) {2070// Newton's iteration!2071long t = val;2072t *= 2 - val*t;2073t *= 2 - val*t;2074t *= 2 - val*t;2075t *= 2 - val*t;2076t *= 2 - val*t;2077assert(t * val == 1);2078return t;2079}20802081/**2082* Calculate the multiplicative inverse of 2^k mod mod, where mod is odd.2083*/2084static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) {2085// Copy the mod to protect original2086return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k);2087}20882089/**2090* Calculate the multiplicative inverse of this modulo mod, where the mod2091* argument is odd. This and mod are not changed by the calculation.2092*2093* This method implements an algorithm due to Richard Schroeppel, that uses2094* the same intermediate representation as Montgomery Reduction2095* ("Montgomery Form"). The algorithm is described in an unpublished2096* manuscript entitled "Fast Modular Reciprocals."2097*/2098private MutableBigInteger modInverse(MutableBigInteger mod) {2099MutableBigInteger p = new MutableBigInteger(mod);2100MutableBigInteger f = new MutableBigInteger(this);2101MutableBigInteger g = new MutableBigInteger(p);2102SignedMutableBigInteger c = new SignedMutableBigInteger(1);2103SignedMutableBigInteger d = new SignedMutableBigInteger();2104MutableBigInteger temp = null;2105SignedMutableBigInteger sTemp = null;21062107int k = 0;2108// Right shift f k times until odd, left shift d k times2109if (f.isEven()) {2110int trailingZeros = f.getLowestSetBit();2111f.rightShift(trailingZeros);2112d.leftShift(trailingZeros);2113k = trailingZeros;2114}21152116// The Almost Inverse Algorithm2117while (!f.isOne()) {2118// If gcd(f, g) != 1, number is not invertible modulo mod2119if (f.isZero())2120throw new ArithmeticException("BigInteger not invertible.");21212122// If f < g exchange f, g and c, d2123if (f.compare(g) < 0) {2124temp = f; f = g; g = temp;2125sTemp = d; d = c; c = sTemp;2126}21272128// If f == g (mod 4)2129if (((f.value[f.offset + f.intLen - 1] ^2130g.value[g.offset + g.intLen - 1]) & 3) == 0) {2131f.subtract(g);2132c.signedSubtract(d);2133} else { // If f != g (mod 4)2134f.add(g);2135c.signedAdd(d);2136}21372138// Right shift f k times until odd, left shift d k times2139int trailingZeros = f.getLowestSetBit();2140f.rightShift(trailingZeros);2141d.leftShift(trailingZeros);2142k += trailingZeros;2143}21442145if (c.compare(p) >= 0) { // c has a larger magnitude than p2146MutableBigInteger remainder = c.divide(p,2147new MutableBigInteger());2148// The previous line ignores the sign so we copy the data back2149// into c which will restore the sign as needed (and converts2150// it back to a SignedMutableBigInteger)2151c.copyValue(remainder);2152}21532154if (c.sign < 0) {2155c.signedAdd(p);2156}21572158return fixup(c, p, k);2159}21602161/**2162* The Fixup Algorithm2163* Calculates X such that X = C * 2^(-k) (mod P)2164* Assumes C<P and P is odd.2165*/2166static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p,2167int k) {2168MutableBigInteger temp = new MutableBigInteger();2169// Set r to the multiplicative inverse of p mod 2^322170int r = -inverseMod32(p.value[p.offset+p.intLen-1]);21712172for (int i=0, numWords = k >> 5; i < numWords; i++) {2173// V = R * c (mod 2^j)2174int v = r * c.value[c.offset + c.intLen-1];2175// c = c + (v * p)2176p.mul(v, temp);2177c.add(temp);2178// c = c / 2^j2179c.intLen--;2180}2181int numBits = k & 0x1f;2182if (numBits != 0) {2183// V = R * c (mod 2^j)2184int v = r * c.value[c.offset + c.intLen-1];2185v &= ((1<<numBits) - 1);2186// c = c + (v * p)2187p.mul(v, temp);2188c.add(temp);2189// c = c / 2^j2190c.rightShift(numBits);2191}21922193// In theory, c may be greater than p at this point (Very rare!)2194if (c.compare(p) >= 0)2195c = c.divide(p, new MutableBigInteger());21962197return c;2198}21992200/**2201* Uses the extended Euclidean algorithm to compute the modInverse of base2202* mod a modulus that is a power of 2. The modulus is 2^k.2203*/2204MutableBigInteger euclidModInverse(int k) {2205MutableBigInteger b = new MutableBigInteger(1);2206b.leftShift(k);2207MutableBigInteger mod = new MutableBigInteger(b);22082209MutableBigInteger a = new MutableBigInteger(this);2210MutableBigInteger q = new MutableBigInteger();2211MutableBigInteger r = b.divide(a, q);22122213MutableBigInteger swapper = b;2214// swap b & r2215b = r;2216r = swapper;22172218MutableBigInteger t1 = new MutableBigInteger(q);2219MutableBigInteger t0 = new MutableBigInteger(1);2220MutableBigInteger temp = new MutableBigInteger();22212222while (!b.isOne()) {2223r = a.divide(b, q);22242225if (r.intLen == 0)2226throw new ArithmeticException("BigInteger not invertible.");22272228swapper = r;2229a = swapper;22302231if (q.intLen == 1)2232t1.mul(q.value[q.offset], temp);2233else2234q.multiply(t1, temp);2235swapper = q;2236q = temp;2237temp = swapper;2238t0.add(q);22392240if (a.isOne())2241return t0;22422243r = b.divide(a, q);22442245if (r.intLen == 0)2246throw new ArithmeticException("BigInteger not invertible.");22472248swapper = b;2249b = r;22502251if (q.intLen == 1)2252t0.mul(q.value[q.offset], temp);2253else2254q.multiply(t0, temp);2255swapper = q; q = temp; temp = swapper;22562257t1.add(q);2258}2259mod.subtract(t1);2260return mod;2261}2262}226322642265