Path: blob/master/src/java.base/share/classes/java/math/MutableBigInteger.java
41152 views
/*1* Copyright (c) 1999, 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*/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*/148private void ones(int n) {149if (n > value.length)150value = new int[n];151Arrays.fill(value, -1);152offset = 0;153intLen = n;154}155156/**157* Internal helper method to return the magnitude array. The caller is not158* supposed to modify the returned array.159*/160private int[] getMagnitudeArray() {161if (offset > 0 || value.length != intLen) {162// Shrink value to be the total magnitude163int[] tmp = Arrays.copyOfRange(value, offset, offset + intLen);164Arrays.fill(value, 0);165offset = 0;166intLen = tmp.length;167value = tmp;168}169return value;170}171172/**173* Convert this MutableBigInteger to a long value. The caller has to make174* sure this MutableBigInteger can be fit into long.175*/176private long toLong() {177assert (intLen <= 2) : "this MutableBigInteger exceeds the range of long";178if (intLen == 0)179return 0;180long d = value[offset] & LONG_MASK;181return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d;182}183184/**185* Convert this MutableBigInteger to a BigInteger object.186*/187BigInteger toBigInteger(int sign) {188if (intLen == 0 || sign == 0)189return BigInteger.ZERO;190return new BigInteger(getMagnitudeArray(), sign);191}192193/**194* Converts this number to a nonnegative {@code BigInteger}.195*/196BigInteger toBigInteger() {197normalize();198return toBigInteger(isZero() ? 0 : 1);199}200201/**202* Convert this MutableBigInteger to BigDecimal object with the specified sign203* and scale.204*/205BigDecimal toBigDecimal(int sign, int scale) {206if (intLen == 0 || sign == 0)207return BigDecimal.zeroValueOf(scale);208int[] mag = getMagnitudeArray();209int len = mag.length;210int d = mag[0];211// If this MutableBigInteger can't be fit into long, we need to212// make a BigInteger object for the resultant BigDecimal object.213if (len > 2 || (d < 0 && len == 2))214return new BigDecimal(new BigInteger(mag, sign), INFLATED, scale, 0);215long v = (len == 2) ?216((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) :217d & LONG_MASK;218return BigDecimal.valueOf(sign == -1 ? -v : v, scale);219}220221/**222* This is for internal use in converting from a MutableBigInteger223* object into a long value given a specified sign.224* returns INFLATED if value is not fit into long225*/226long toCompactValue(int sign) {227if (intLen == 0 || sign == 0)228return 0L;229int[] mag = getMagnitudeArray();230int len = mag.length;231int d = mag[0];232// If this MutableBigInteger can not be fitted into long, we need to233// make a BigInteger object for the resultant BigDecimal object.234if (len > 2 || (d < 0 && len == 2))235return INFLATED;236long v = (len == 2) ?237((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) :238d & LONG_MASK;239return sign == -1 ? -v : v;240}241242/**243* Clear out a MutableBigInteger for reuse.244*/245void clear() {246offset = intLen = 0;247for (int index=0, n=value.length; index < n; index++)248value[index] = 0;249}250251/**252* Set a MutableBigInteger to zero, removing its offset.253*/254void reset() {255offset = intLen = 0;256}257258/**259* Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1260* as this MutableBigInteger is numerically less than, equal to, or261* greater than {@code b}.262*/263final int compare(MutableBigInteger b) {264int blen = b.intLen;265if (intLen < blen)266return -1;267if (intLen > blen)268return 1;269270// Add Integer.MIN_VALUE to make the comparison act as unsigned integer271// comparison.272int[] bval = b.value;273for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) {274int b1 = value[i] + 0x80000000;275int b2 = bval[j] + 0x80000000;276if (b1 < b2)277return -1;278if (b1 > b2)279return 1;280}281return 0;282}283284/**285* Returns a value equal to what {@code b.leftShift(32*ints); return compare(b);}286* would return, but doesn't change the value of {@code b}.287*/288private int compareShifted(MutableBigInteger b, int ints) {289int blen = b.intLen;290int alen = intLen - ints;291if (alen < blen)292return -1;293if (alen > blen)294return 1;295296// Add Integer.MIN_VALUE to make the comparison act as unsigned integer297// comparison.298int[] bval = b.value;299for (int i = offset, j = b.offset; i < alen + offset; i++, j++) {300int b1 = value[i] + 0x80000000;301int b2 = bval[j] + 0x80000000;302if (b1 < b2)303return -1;304if (b1 > b2)305return 1;306}307return 0;308}309310/**311* Compare this against half of a MutableBigInteger object (Needed for312* remainder tests).313* Assumes no leading unnecessary zeros, which holds for results314* from divide().315*/316final int compareHalf(MutableBigInteger b) {317int blen = b.intLen;318int len = intLen;319if (len <= 0)320return blen <= 0 ? 0 : -1;321if (len > blen)322return 1;323if (len < blen - 1)324return -1;325int[] bval = b.value;326int bstart = 0;327int carry = 0;328// Only 2 cases left:len == blen or len == blen - 1329if (len != blen) { // len == blen - 1330if (bval[bstart] == 1) {331++bstart;332carry = 0x80000000;333} else334return -1;335}336// compare values with right-shifted values of b,337// carrying shifted-out bits across words338int[] val = value;339for (int i = offset, j = bstart; i < len + offset;) {340int bv = bval[j++];341long hb = ((bv >>> 1) + carry) & LONG_MASK;342long v = val[i++] & LONG_MASK;343if (v != hb)344return v < hb ? -1 : 1;345carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0346}347return carry == 0 ? 0 : -1;348}349350/**351* Return the index of the lowest set bit in this MutableBigInteger. If the352* magnitude of this MutableBigInteger is zero, -1 is returned.353*/354private final int getLowestSetBit() {355if (intLen == 0)356return -1;357int j, b;358for (j=intLen-1; (j > 0) && (value[j+offset] == 0); j--)359;360b = value[j+offset];361if (b == 0)362return -1;363return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b);364}365366/**367* Return the int in use in this MutableBigInteger at the specified368* index. This method is not used because it is not inlined on all369* platforms.370*/371private final int getInt(int index) {372return value[offset+index];373}374375/**376* Return a long which is equal to the unsigned value of the int in377* use in this MutableBigInteger at the specified index. This method is378* not used because it is not inlined on all platforms.379*/380private final long getLong(int index) {381return value[offset+index] & LONG_MASK;382}383384/**385* Ensure that the MutableBigInteger is in normal form, specifically386* making sure that there are no leading zeros, and that if the387* magnitude is zero, then intLen is zero.388*/389final void normalize() {390if (intLen == 0) {391offset = 0;392return;393}394395int index = offset;396if (value[index] != 0)397return;398399int indexBound = index+intLen;400do {401index++;402} while(index < indexBound && value[index] == 0);403404int numZeros = index - offset;405intLen -= numZeros;406offset = (intLen == 0 ? 0 : offset+numZeros);407}408409/**410* If this MutableBigInteger cannot hold len words, increase the size411* of the value array to len words.412*/413private final void ensureCapacity(int len) {414if (value.length < len) {415value = new int[len];416offset = 0;417intLen = len;418}419}420421/**422* Convert this MutableBigInteger into an int array with no leading423* zeros, of a length that is equal to this MutableBigInteger's intLen.424*/425int[] toIntArray() {426int[] result = new int[intLen];427for(int i=0; i < intLen; i++)428result[i] = value[offset+i];429return result;430}431432/**433* Sets the int at index+offset in this MutableBigInteger to val.434* This does not get inlined on all platforms so it is not used435* as often as originally intended.436*/437void setInt(int index, int val) {438value[offset + index] = val;439}440441/**442* Sets this MutableBigInteger's value array to the specified array.443* The intLen is set to the specified length.444*/445void setValue(int[] val, int length) {446value = val;447intLen = length;448offset = 0;449}450451/**452* Sets this MutableBigInteger's value array to a copy of the specified453* array. The intLen is set to the length of the new array.454*/455void copyValue(MutableBigInteger src) {456int len = src.intLen;457if (value.length < len)458value = new int[len];459System.arraycopy(src.value, src.offset, value, 0, len);460intLen = len;461offset = 0;462}463464/**465* Sets this MutableBigInteger's value array to a copy of the specified466* array. The intLen is set to the length of the specified array.467*/468void copyValue(int[] val) {469int len = val.length;470if (value.length < len)471value = new int[len];472System.arraycopy(val, 0, value, 0, len);473intLen = len;474offset = 0;475}476477/**478* Returns true iff this MutableBigInteger has a value of one.479*/480boolean isOne() {481return (intLen == 1) && (value[offset] == 1);482}483484/**485* Returns true iff this MutableBigInteger has a value of zero.486*/487boolean isZero() {488return (intLen == 0);489}490491/**492* Returns true iff this MutableBigInteger is even.493*/494boolean isEven() {495return (intLen == 0) || ((value[offset + intLen - 1] & 1) == 0);496}497498/**499* Returns true iff this MutableBigInteger is odd.500*/501boolean isOdd() {502return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1);503}504505/**506* Returns true iff this MutableBigInteger is in normal form. A507* MutableBigInteger is in normal form if it has no leading zeros508* after the offset, and intLen + offset <= value.length.509*/510boolean isNormal() {511if (intLen + offset > value.length)512return false;513if (intLen == 0)514return true;515return (value[offset] != 0);516}517518/**519* Returns a String representation of this MutableBigInteger in radix 10.520*/521public String toString() {522BigInteger b = toBigInteger(1);523return b.toString();524}525526/**527* Like {@link #rightShift(int)} but {@code n} can be greater than the length of the number.528*/529void safeRightShift(int n) {530if (n/32 >= intLen) {531reset();532} else {533rightShift(n);534}535}536537/**538* Right shift this MutableBigInteger n bits. The MutableBigInteger is left539* in normal form.540*/541void rightShift(int n) {542if (intLen == 0)543return;544int nInts = n >>> 5;545int nBits = n & 0x1F;546this.intLen -= nInts;547if (nBits == 0)548return;549int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);550if (nBits >= bitsInHighWord) {551this.primitiveLeftShift(32 - nBits);552this.intLen--;553} else {554primitiveRightShift(nBits);555}556}557558/**559* Like {@link #leftShift(int)} but {@code n} can be zero.560*/561void safeLeftShift(int n) {562if (n > 0) {563leftShift(n);564}565}566567/**568* Left shift this MutableBigInteger n bits.569*/570void leftShift(int n) {571/*572* If there is enough storage space in this MutableBigInteger already573* the available space will be used. Space to the right of the used574* ints in the value array is faster to utilize, so the extra space575* will be taken from the right if possible.576*/577if (intLen == 0)578return;579int nInts = n >>> 5;580int nBits = n&0x1F;581int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);582583// If shift can be done without moving words, do so584if (n <= (32-bitsInHighWord)) {585primitiveLeftShift(nBits);586return;587}588589int newLen = intLen + nInts +1;590if (nBits <= (32-bitsInHighWord))591newLen--;592if (value.length < newLen) {593// The array must grow594int[] result = new int[newLen];595for (int i=0; i < intLen; i++)596result[i] = value[offset+i];597setValue(result, newLen);598} else if (value.length - offset >= newLen) {599// Use space on right600for(int i=0; i < newLen - intLen; i++)601value[offset+intLen+i] = 0;602} else {603// Must use space on left604for (int i=0; i < intLen; i++)605value[i] = value[offset+i];606for (int i=intLen; i < newLen; i++)607value[i] = 0;608offset = 0;609}610intLen = newLen;611if (nBits == 0)612return;613if (nBits <= (32-bitsInHighWord))614primitiveLeftShift(nBits);615else616primitiveRightShift(32 -nBits);617}618619/**620* A primitive used for division. This method adds in one multiple of the621* divisor a back to the dividend result at a specified offset. It is used622* when qhat was estimated too large, and must be adjusted.623*/624private int divadd(int[] a, int[] result, int offset) {625long carry = 0;626627for (int j=a.length-1; j >= 0; j--) {628long sum = (a[j] & LONG_MASK) +629(result[j+offset] & LONG_MASK) + carry;630result[j+offset] = (int)sum;631carry = sum >>> 32;632}633return (int)carry;634}635636/**637* This method is used for division. It multiplies an n word input a by one638* word input x, and subtracts the n word product from q. This is needed639* when subtracting qhat*divisor from dividend.640*/641private int mulsub(int[] q, int[] a, int x, int len, int offset) {642long xLong = x & LONG_MASK;643long carry = 0;644offset += len;645646for (int j=len-1; j >= 0; j--) {647long product = (a[j] & LONG_MASK) * xLong + carry;648long difference = q[offset] - product;649q[offset--] = (int)difference;650carry = (product >>> 32)651+ (((difference & LONG_MASK) >652(((~(int)product) & LONG_MASK))) ? 1:0);653}654return (int)carry;655}656657/**658* The method is the same as mulsun, except the fact that q array is not659* updated, the only result of the method is borrow flag.660*/661private int mulsubBorrow(int[] q, int[] a, int x, int len, int offset) {662long xLong = x & LONG_MASK;663long carry = 0;664offset += len;665for (int j=len-1; j >= 0; j--) {666long product = (a[j] & LONG_MASK) * xLong + carry;667long difference = q[offset--] - product;668carry = (product >>> 32)669+ (((difference & LONG_MASK) >670(((~(int)product) & LONG_MASK))) ? 1:0);671}672return (int)carry;673}674675/**676* Right shift this MutableBigInteger n bits, where n is677* less than 32.678* Assumes that intLen > 0, n > 0 for speed679*/680private final void primitiveRightShift(int n) {681int[] val = value;682int n2 = 32 - n;683for (int i=offset+intLen-1, c=val[i]; i > offset; i--) {684int b = c;685c = val[i-1];686val[i] = (c << n2) | (b >>> n);687}688val[offset] >>>= n;689}690691/**692* Left shift this MutableBigInteger n bits, where n is693* less than 32.694* Assumes that intLen > 0, n > 0 for speed695*/696private final void primitiveLeftShift(int n) {697int[] val = value;698int n2 = 32 - n;699for (int i=offset, c=val[i], m=i+intLen-1; i < m; i++) {700int b = c;701c = val[i+1];702val[i] = (b << n) | (c >>> n2);703}704val[offset+intLen-1] <<= n;705}706707/**708* Returns a {@code BigInteger} equal to the {@code n}709* low ints of this number.710*/711private BigInteger getLower(int n) {712if (isZero()) {713return BigInteger.ZERO;714} else if (intLen < n) {715return toBigInteger(1);716} else {717// strip zeros718int len = n;719while (len > 0 && value[offset+intLen-len] == 0)720len--;721int sign = len > 0 ? 1 : 0;722return new BigInteger(Arrays.copyOfRange(value, offset+intLen-len, offset+intLen), sign);723}724}725726/**727* Discards all ints whose index is greater than {@code n}.728*/729private void keepLower(int n) {730if (intLen >= n) {731offset += intLen - n;732intLen = n;733}734}735736/**737* Adds the contents of two MutableBigInteger objects.The result738* is placed within this MutableBigInteger.739* The contents of the addend are not changed.740*/741void add(MutableBigInteger addend) {742int x = intLen;743int y = addend.intLen;744int resultLen = (intLen > addend.intLen ? intLen : addend.intLen);745int[] result = (value.length < resultLen ? new int[resultLen] : value);746747int rstart = result.length-1;748long sum;749long carry = 0;750751// Add common parts of both numbers752while(x > 0 && y > 0) {753x--; y--;754sum = (value[x+offset] & LONG_MASK) +755(addend.value[y+addend.offset] & LONG_MASK) + carry;756result[rstart--] = (int)sum;757carry = sum >>> 32;758}759760// Add remainder of the longer number761while(x > 0) {762x--;763if (carry == 0 && result == value && rstart == (x + offset))764return;765sum = (value[x+offset] & LONG_MASK) + carry;766result[rstart--] = (int)sum;767carry = sum >>> 32;768}769while(y > 0) {770y--;771sum = (addend.value[y+addend.offset] & LONG_MASK) + carry;772result[rstart--] = (int)sum;773carry = sum >>> 32;774}775776if (carry > 0) { // Result must grow in length777resultLen++;778if (result.length < resultLen) {779int temp[] = new int[resultLen];780// Result one word longer from carry-out; copy low-order781// bits into new result.782System.arraycopy(result, 0, temp, 1, result.length);783temp[0] = 1;784result = temp;785} else {786result[rstart--] = 1;787}788}789790value = result;791intLen = resultLen;792offset = result.length - resultLen;793}794795/**796* Adds the value of {@code addend} shifted {@code n} ints to the left.797* Has the same effect as {@code addend.leftShift(32*ints); add(addend);}798* but doesn't change the value of {@code addend}.799*/800void addShifted(MutableBigInteger addend, int n) {801if (addend.isZero()) {802return;803}804805int x = intLen;806int y = addend.intLen + n;807int resultLen = (intLen > y ? intLen : y);808int[] result = (value.length < resultLen ? new int[resultLen] : value);809810int rstart = result.length-1;811long sum;812long carry = 0;813814// Add common parts of both numbers815while (x > 0 && y > 0) {816x--; y--;817int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0;818sum = (value[x+offset] & LONG_MASK) +819(bval & LONG_MASK) + carry;820result[rstart--] = (int)sum;821carry = sum >>> 32;822}823824// Add remainder of the longer number825while (x > 0) {826x--;827if (carry == 0 && result == value && rstart == (x + offset)) {828return;829}830sum = (value[x+offset] & LONG_MASK) + carry;831result[rstart--] = (int)sum;832carry = sum >>> 32;833}834while (y > 0) {835y--;836int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0;837sum = (bval & LONG_MASK) + carry;838result[rstart--] = (int)sum;839carry = sum >>> 32;840}841842if (carry > 0) { // Result must grow in length843resultLen++;844if (result.length < resultLen) {845int temp[] = new int[resultLen];846// Result one word longer from carry-out; copy low-order847// bits into new result.848System.arraycopy(result, 0, temp, 1, result.length);849temp[0] = 1;850result = temp;851} else {852result[rstart--] = 1;853}854}855856value = result;857intLen = resultLen;858offset = result.length - resultLen;859}860861/**862* Like {@link #addShifted(MutableBigInteger, int)} but {@code this.intLen} must863* not be greater than {@code n}. In other words, concatenates {@code this}864* and {@code addend}.865*/866void addDisjoint(MutableBigInteger addend, int n) {867if (addend.isZero())868return;869870int x = intLen;871int y = addend.intLen + n;872int resultLen = (intLen > y ? intLen : y);873int[] result;874if (value.length < resultLen)875result = new int[resultLen];876else {877result = value;878Arrays.fill(value, offset+intLen, value.length, 0);879}880881int rstart = result.length-1;882883// copy from this if needed884System.arraycopy(value, offset, result, rstart+1-x, x);885y -= x;886rstart -= x;887888int len = Math.min(y, addend.value.length-addend.offset);889System.arraycopy(addend.value, addend.offset, result, rstart+1-y, len);890891// zero the gap892for (int i=rstart+1-y+len; i < rstart+1; i++)893result[i] = 0;894895value = result;896intLen = resultLen;897offset = result.length - resultLen;898}899900/**901* Adds the low {@code n} ints of {@code addend}.902*/903void addLower(MutableBigInteger addend, int n) {904MutableBigInteger a = new MutableBigInteger(addend);905if (a.offset + a.intLen >= n) {906a.offset = a.offset + a.intLen - n;907a.intLen = n;908}909a.normalize();910add(a);911}912913/**914* Subtracts the smaller of this and b from the larger and places the915* result into this MutableBigInteger.916*/917int subtract(MutableBigInteger b) {918MutableBigInteger a = this;919920int[] result = value;921int sign = a.compare(b);922923if (sign == 0) {924reset();925return 0;926}927if (sign < 0) {928MutableBigInteger tmp = a;929a = b;930b = tmp;931}932933int resultLen = a.intLen;934if (result.length < resultLen)935result = new int[resultLen];936937long diff = 0;938int x = a.intLen;939int y = b.intLen;940int rstart = result.length - 1;941942// Subtract common parts of both numbers943while (y > 0) {944x--; y--;945946diff = (a.value[x+a.offset] & LONG_MASK) -947(b.value[y+b.offset] & LONG_MASK) - ((int)-(diff>>32));948result[rstart--] = (int)diff;949}950// Subtract remainder of longer number951while (x > 0) {952x--;953diff = (a.value[x+a.offset] & LONG_MASK) - ((int)-(diff>>32));954result[rstart--] = (int)diff;955}956957value = result;958intLen = resultLen;959offset = value.length - resultLen;960normalize();961return sign;962}963964/**965* Subtracts the smaller of a and b from the larger and places the result966* into the larger. Returns 1 if the answer is in a, -1 if in b, 0 if no967* operation was performed.968*/969private int difference(MutableBigInteger b) {970MutableBigInteger a = this;971int sign = a.compare(b);972if (sign == 0)973return 0;974if (sign < 0) {975MutableBigInteger tmp = a;976a = b;977b = tmp;978}979980long diff = 0;981int x = a.intLen;982int y = b.intLen;983984// Subtract common parts of both numbers985while (y > 0) {986x--; y--;987diff = (a.value[a.offset+ x] & LONG_MASK) -988(b.value[b.offset+ y] & LONG_MASK) - ((int)-(diff>>32));989a.value[a.offset+x] = (int)diff;990}991// Subtract remainder of longer number992while (x > 0) {993x--;994diff = (a.value[a.offset+ x] & LONG_MASK) - ((int)-(diff>>32));995a.value[a.offset+x] = (int)diff;996}997998a.normalize();999return sign;1000}10011002/**1003* Multiply the contents of two MutableBigInteger objects. The result is1004* placed into MutableBigInteger z. The contents of y are not changed.1005*/1006void multiply(MutableBigInteger y, MutableBigInteger z) {1007int xLen = intLen;1008int yLen = y.intLen;1009int newLen = xLen + yLen;10101011// Put z into an appropriate state to receive product1012if (z.value.length < newLen)1013z.value = new int[newLen];1014z.offset = 0;1015z.intLen = newLen;10161017// The first iteration is hoisted out of the loop to avoid extra add1018long carry = 0;1019for (int j=yLen-1, k=yLen+xLen-1; j >= 0; j--, k--) {1020long product = (y.value[j+y.offset] & LONG_MASK) *1021(value[xLen-1+offset] & LONG_MASK) + carry;1022z.value[k] = (int)product;1023carry = product >>> 32;1024}1025z.value[xLen-1] = (int)carry;10261027// Perform the multiplication word by word1028for (int i = xLen-2; i >= 0; i--) {1029carry = 0;1030for (int j=yLen-1, k=yLen+i; j >= 0; j--, k--) {1031long product = (y.value[j+y.offset] & LONG_MASK) *1032(value[i+offset] & LONG_MASK) +1033(z.value[k] & LONG_MASK) + carry;1034z.value[k] = (int)product;1035carry = product >>> 32;1036}1037z.value[i] = (int)carry;1038}10391040// Remove leading zeros from product1041z.normalize();1042}10431044/**1045* Multiply the contents of this MutableBigInteger by the word y. The1046* result is placed into z.1047*/1048void mul(int y, MutableBigInteger z) {1049if (y == 1) {1050z.copyValue(this);1051return;1052}10531054if (y == 0) {1055z.clear();1056return;1057}10581059// Perform the multiplication word by word1060long ylong = y & LONG_MASK;1061int[] zval = (z.value.length < intLen+1 ? new int[intLen + 1]1062: z.value);1063long carry = 0;1064for (int i = intLen-1; i >= 0; i--) {1065long product = ylong * (value[i+offset] & LONG_MASK) + carry;1066zval[i+1] = (int)product;1067carry = product >>> 32;1068}10691070if (carry == 0) {1071z.offset = 1;1072z.intLen = intLen;1073} else {1074z.offset = 0;1075z.intLen = intLen + 1;1076zval[0] = (int)carry;1077}1078z.value = zval;1079}10801081/**1082* This method is used for division of an n word dividend by a one word1083* divisor. The quotient is placed into quotient. The one word divisor is1084* specified by divisor.1085*1086* @return the remainder of the division is returned.1087*1088*/1089int divideOneWord(int divisor, MutableBigInteger quotient) {1090long divisorLong = divisor & LONG_MASK;10911092// Special case of one word dividend1093if (intLen == 1) {1094long dividendValue = value[offset] & LONG_MASK;1095int q = (int) (dividendValue / divisorLong);1096int r = (int) (dividendValue - q * divisorLong);1097quotient.value[0] = q;1098quotient.intLen = (q == 0) ? 0 : 1;1099quotient.offset = 0;1100return r;1101}11021103if (quotient.value.length < intLen)1104quotient.value = new int[intLen];1105quotient.offset = 0;1106quotient.intLen = intLen;11071108// Normalize the divisor1109int shift = Integer.numberOfLeadingZeros(divisor);11101111int rem = value[offset];1112long remLong = rem & LONG_MASK;1113if (remLong < divisorLong) {1114quotient.value[0] = 0;1115} else {1116quotient.value[0] = (int)(remLong / divisorLong);1117rem = (int) (remLong - (quotient.value[0] * divisorLong));1118remLong = rem & LONG_MASK;1119}1120int xlen = intLen;1121while (--xlen > 0) {1122long dividendEstimate = (remLong << 32) |1123(value[offset + intLen - xlen] & LONG_MASK);1124int q;1125if (dividendEstimate >= 0) {1126q = (int) (dividendEstimate / divisorLong);1127rem = (int) (dividendEstimate - q * divisorLong);1128} else {1129long tmp = divWord(dividendEstimate, divisor);1130q = (int) (tmp & LONG_MASK);1131rem = (int) (tmp >>> 32);1132}1133quotient.value[intLen - xlen] = q;1134remLong = rem & LONG_MASK;1135}11361137quotient.normalize();1138// Unnormalize1139if (shift > 0)1140return rem % divisor;1141else1142return rem;1143}11441145/**1146* Calculates the quotient of this div b and places the quotient in the1147* provided MutableBigInteger objects and the remainder object is returned.1148*1149*/1150MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) {1151return divide(b,quotient,true);1152}11531154MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder) {1155if (b.intLen < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD ||1156intLen - b.intLen < BigInteger.BURNIKEL_ZIEGLER_OFFSET) {1157return divideKnuth(b, quotient, needRemainder);1158} else {1159return divideAndRemainderBurnikelZiegler(b, quotient);1160}1161}11621163/**1164* @see #divideKnuth(MutableBigInteger, MutableBigInteger, boolean)1165*/1166MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient) {1167return divideKnuth(b,quotient,true);1168}11691170/**1171* Calculates the quotient of this div b and places the quotient in the1172* provided MutableBigInteger objects and the remainder object is returned.1173*1174* Uses Algorithm D from Knuth TAOCP Vol. 2, 3rd edition, section 4.3.1.1175* Many optimizations to that algorithm have been adapted from the Colin1176* Plumb C library.1177* It special cases one word divisors for speed. The content of b is not1178* changed.1179*1180*/1181MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder) {1182if (b.intLen == 0)1183throw new ArithmeticException("BigInteger divide by zero");11841185// Dividend is zero1186if (intLen == 0) {1187quotient.intLen = quotient.offset = 0;1188return needRemainder ? new MutableBigInteger() : null;1189}11901191int cmp = compare(b);1192// Dividend less than divisor1193if (cmp < 0) {1194quotient.intLen = quotient.offset = 0;1195return needRemainder ? new MutableBigInteger(this) : null;1196}1197// Dividend equal to divisor1198if (cmp == 0) {1199quotient.value[0] = quotient.intLen = 1;1200quotient.offset = 0;1201return needRemainder ? new MutableBigInteger() : null;1202}12031204quotient.clear();1205// Special case one word divisor1206if (b.intLen == 1) {1207int r = divideOneWord(b.value[b.offset], quotient);1208if(needRemainder) {1209if (r == 0)1210return new MutableBigInteger();1211return new MutableBigInteger(r);1212} else {1213return null;1214}1215}12161217// Cancel common powers of two if we're above the KNUTH_POW2_* thresholds1218if (intLen >= KNUTH_POW2_THRESH_LEN) {1219int trailingZeroBits = Math.min(getLowestSetBit(), b.getLowestSetBit());1220if (trailingZeroBits >= KNUTH_POW2_THRESH_ZEROS*32) {1221MutableBigInteger a = new MutableBigInteger(this);1222b = new MutableBigInteger(b);1223a.rightShift(trailingZeroBits);1224b.rightShift(trailingZeroBits);1225MutableBigInteger r = a.divideKnuth(b, quotient);1226r.leftShift(trailingZeroBits);1227return r;1228}1229}12301231return divideMagnitude(b, quotient, needRemainder);1232}12331234/**1235* Computes {@code this/b} and {@code this%b} using the1236* <a href="http://cr.yp.to/bib/1998/burnikel.ps"> Burnikel-Ziegler algorithm</a>.1237* This method implements algorithm 3 from pg. 9 of the Burnikel-Ziegler paper.1238* The parameter beta was chosen to b 2<sup>32</sup> so almost all shifts are1239* multiples of 32 bits.<br/>1240* {@code this} and {@code b} must be nonnegative.1241* @param b the divisor1242* @param quotient output parameter for {@code this/b}1243* @return the remainder1244*/1245MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) {1246int r = intLen;1247int s = b.intLen;12481249// Clear the quotient1250quotient.offset = quotient.intLen = 0;12511252if (r < s) {1253return this;1254} else {1255// Unlike Knuth division, we don't check for common powers of two here because1256// BZ already runs faster if both numbers contain powers of two and cancelling them has no1257// additional benefit.12581259// step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s}1260int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD));12611262int j = (s+m-1) / m; // step 2a: j = ceil(s/m)1263int n = j * m; // step 2b: block length in 32-bit units1264long n32 = 32L * n; // block length in bits1265int sigma = (int) Math.max(0, n32 - b.bitLength()); // step 3: sigma = max{T | (2^T)*B < beta^n}1266MutableBigInteger bShifted = new MutableBigInteger(b);1267bShifted.safeLeftShift(sigma); // step 4a: shift b so its length is a multiple of n1268MutableBigInteger aShifted = new MutableBigInteger (this);1269aShifted.safeLeftShift(sigma); // step 4b: shift a by the same amount12701271// step 5: t is the number of blocks needed to accommodate a plus one additional bit1272int t = (int) ((aShifted.bitLength()+n32) / n32);1273if (t < 2) {1274t = 2;1275}12761277// step 6: conceptually split a into blocks a[t-1], ..., a[0]1278MutableBigInteger a1 = aShifted.getBlock(t-1, t, n); // the most significant block of a12791280// step 7: z[t-2] = [a[t-1], a[t-2]]1281MutableBigInteger z = aShifted.getBlock(t-2, t, n); // the second to most significant block1282z.addDisjoint(a1, n); // z[t-2]12831284// do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers1285MutableBigInteger qi = new MutableBigInteger();1286MutableBigInteger ri;1287for (int i=t-2; i > 0; i--) {1288// step 8a: compute (qi,ri) such that z=b*qi+ri1289ri = z.divide2n1n(bShifted, qi);12901291// step 8b: z = [ri, a[i-1]]1292z = aShifted.getBlock(i-1, t, n); // a[i-1]1293z.addDisjoint(ri, n);1294quotient.addShifted(qi, i*n); // update q (part of step 9)1295}1296// final iteration of step 8: do the loop one more time for i=0 but leave z unchanged1297ri = z.divide2n1n(bShifted, qi);1298quotient.add(qi);12991300ri.rightShift(sigma); // step 9: a and b were shifted, so shift back1301return ri;1302}1303}13041305/**1306* This method implements algorithm 1 from pg. 4 of the Burnikel-Ziegler paper.1307* It divides a 2n-digit number by a n-digit number.<br/>1308* The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.1309* <br/>1310* {@code this} must be a nonnegative number such that {@code this.bitLength() <= 2*b.bitLength()}1311* @param b a positive number such that {@code b.bitLength()} is even1312* @param quotient output parameter for {@code this/b}1313* @return {@code this%b}1314*/1315private MutableBigInteger divide2n1n(MutableBigInteger b, MutableBigInteger quotient) {1316int n = b.intLen;13171318// step 1: base case1319if (n%2 != 0 || n < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD) {1320return divideKnuth(b, quotient);1321}13221323// step 2: view this as [a1,a2,a3,a4] where each ai is n/2 ints or less1324MutableBigInteger aUpper = new MutableBigInteger(this);1325aUpper.safeRightShift(32*(n/2)); // aUpper = [a1,a2,a3]1326keepLower(n/2); // this = a413271328// step 3: q1=aUpper/b, r1=aUpper%b1329MutableBigInteger q1 = new MutableBigInteger();1330MutableBigInteger r1 = aUpper.divide3n2n(b, q1);13311332// step 4: quotient=[r1,this]/b, r2=[r1,this]%b1333addDisjoint(r1, n/2); // this = [r1,this]1334MutableBigInteger r2 = divide3n2n(b, quotient);13351336// step 5: let quotient=[q1,quotient] and return r21337quotient.addDisjoint(q1, n/2);1338return r2;1339}13401341/**1342* This method implements algorithm 2 from pg. 5 of the Burnikel-Ziegler paper.1343* It divides a 3n-digit number by a 2n-digit number.<br/>1344* The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.<br/>1345* <br/>1346* {@code this} must be a nonnegative number such that {@code 2*this.bitLength() <= 3*b.bitLength()}1347* @param quotient output parameter for {@code this/b}1348* @return {@code this%b}1349*/1350private MutableBigInteger divide3n2n(MutableBigInteger b, MutableBigInteger quotient) {1351int n = b.intLen / 2; // half the length of b in ints13521353// step 1: view this as [a1,a2,a3] where each ai is n ints or less; let a12=[a1,a2]1354MutableBigInteger a12 = new MutableBigInteger(this);1355a12.safeRightShift(32*n);13561357// step 2: view b as [b1,b2] where each bi is n ints or less1358MutableBigInteger b1 = new MutableBigInteger(b);1359b1.safeRightShift(n * 32);1360BigInteger b2 = b.getLower(n);13611362MutableBigInteger r;1363MutableBigInteger d;1364if (compareShifted(b, n) < 0) {1365// step 3a: if a1<b1, let quotient=a12/b1 and r=a12%b11366r = a12.divide2n1n(b1, quotient);13671368// step 4: d=quotient*b21369d = new MutableBigInteger(quotient.toBigInteger().multiply(b2));1370} else {1371// step 3b: if a1>=b1, let quotient=beta^n-1 and r=a12-b1*2^n+b11372quotient.ones(n);1373a12.add(b1);1374b1.leftShift(32*n);1375a12.subtract(b1);1376r = a12;13771378// step 4: d=quotient*b2=(b2 << 32*n) - b21379d = new MutableBigInteger(b2);1380d.leftShift(32 * n);1381d.subtract(new MutableBigInteger(b2));1382}13831384// step 5: r = r*beta^n + a3 - d (paper says a4)1385// However, don't subtract d until after the while loop so r doesn't become negative1386r.leftShift(32 * n);1387r.addLower(this, n);13881389// step 6: add b until r>=d1390while (r.compare(d) < 0) {1391r.add(b);1392quotient.subtract(MutableBigInteger.ONE);1393}1394r.subtract(d);13951396return r;1397}13981399/**1400* Returns a {@code MutableBigInteger} containing {@code blockLength} ints from1401* {@code this} number, starting at {@code index*blockLength}.<br/>1402* Used by Burnikel-Ziegler division.1403* @param index the block index1404* @param numBlocks the total number of blocks in {@code this} number1405* @param blockLength length of one block in units of 32 bits1406* @return1407*/1408private MutableBigInteger getBlock(int index, int numBlocks, int blockLength) {1409int blockStart = index * blockLength;1410if (blockStart >= intLen) {1411return new MutableBigInteger();1412}14131414int blockEnd;1415if (index == numBlocks-1) {1416blockEnd = intLen;1417} else {1418blockEnd = (index+1) * blockLength;1419}1420if (blockEnd > intLen) {1421return new MutableBigInteger();1422}14231424int[] newVal = Arrays.copyOfRange(value, offset+intLen-blockEnd, offset+intLen-blockStart);1425return new MutableBigInteger(newVal);1426}14271428/** @see BigInteger#bitLength() */1429long bitLength() {1430if (intLen == 0)1431return 0;1432return intLen*32L - Integer.numberOfLeadingZeros(value[offset]);1433}14341435/**1436* Internally used to calculate the quotient of this div v and places the1437* quotient in the provided MutableBigInteger object and the remainder is1438* returned.1439*1440* @return the remainder of the division will be returned.1441*/1442long divide(long v, MutableBigInteger quotient) {1443if (v == 0)1444throw new ArithmeticException("BigInteger divide by zero");14451446// Dividend is zero1447if (intLen == 0) {1448quotient.intLen = quotient.offset = 0;1449return 0;1450}1451if (v < 0)1452v = -v;14531454int d = (int)(v >>> 32);1455quotient.clear();1456// Special case on word divisor1457if (d == 0)1458return divideOneWord((int)v, quotient) & LONG_MASK;1459else {1460return divideLongMagnitude(v, quotient).toLong();1461}1462}14631464private static void copyAndShift(int[] src, int srcFrom, int srcLen, int[] dst, int dstFrom, int shift) {1465int n2 = 32 - shift;1466int c=src[srcFrom];1467for (int i=0; i < srcLen-1; i++) {1468int b = c;1469c = src[++srcFrom];1470dst[dstFrom+i] = (b << shift) | (c >>> n2);1471}1472dst[dstFrom+srcLen-1] = c << shift;1473}14741475/**1476* Divide this MutableBigInteger by the divisor.1477* The quotient will be placed into the provided quotient object &1478* the remainder object is returned.1479*/1480private MutableBigInteger divideMagnitude(MutableBigInteger div,1481MutableBigInteger quotient,1482boolean needRemainder ) {1483// assert div.intLen > 11484// D1 normalize the divisor1485int shift = Integer.numberOfLeadingZeros(div.value[div.offset]);1486// Copy divisor value to protect divisor1487final int dlen = div.intLen;1488int[] divisor;1489MutableBigInteger rem; // Remainder starts as dividend with space for a leading zero1490if (shift > 0) {1491divisor = new int[dlen];1492copyAndShift(div.value,div.offset,dlen,divisor,0,shift);1493if (Integer.numberOfLeadingZeros(value[offset]) >= shift) {1494int[] remarr = new int[intLen + 1];1495rem = new MutableBigInteger(remarr);1496rem.intLen = intLen;1497rem.offset = 1;1498copyAndShift(value,offset,intLen,remarr,1,shift);1499} else {1500int[] remarr = new int[intLen + 2];1501rem = new MutableBigInteger(remarr);1502rem.intLen = intLen+1;1503rem.offset = 1;1504int rFrom = offset;1505int c=0;1506int n2 = 32 - shift;1507for (int i=1; i < intLen+1; i++,rFrom++) {1508int b = c;1509c = value[rFrom];1510remarr[i] = (b << shift) | (c >>> n2);1511}1512remarr[intLen+1] = c << shift;1513}1514} else {1515divisor = Arrays.copyOfRange(div.value, div.offset, div.offset + div.intLen);1516rem = new MutableBigInteger(new int[intLen + 1]);1517System.arraycopy(value, offset, rem.value, 1, intLen);1518rem.intLen = intLen;1519rem.offset = 1;1520}15211522int nlen = rem.intLen;15231524// Set the quotient size1525final int limit = nlen - dlen + 1;1526if (quotient.value.length < limit) {1527quotient.value = new int[limit];1528quotient.offset = 0;1529}1530quotient.intLen = limit;1531int[] q = quotient.value;153215331534// Must insert leading 0 in rem if its length did not change1535if (rem.intLen == nlen) {1536rem.offset = 0;1537rem.value[0] = 0;1538rem.intLen++;1539}15401541int dh = divisor[0];1542long dhLong = dh & LONG_MASK;1543int dl = divisor[1];15441545// D2 Initialize j1546for (int j=0; j < limit-1; j++) {1547// D3 Calculate qhat1548// estimate qhat1549int qhat = 0;1550int qrem = 0;1551boolean skipCorrection = false;1552int nh = rem.value[j+rem.offset];1553int nh2 = nh + 0x80000000;1554int nm = rem.value[j+1+rem.offset];15551556if (nh == dh) {1557qhat = ~0;1558qrem = nh + nm;1559skipCorrection = qrem + 0x80000000 < nh2;1560} else {1561long nChunk = (((long)nh) << 32) | (nm & LONG_MASK);1562if (nChunk >= 0) {1563qhat = (int) (nChunk / dhLong);1564qrem = (int) (nChunk - (qhat * dhLong));1565} else {1566long tmp = divWord(nChunk, dh);1567qhat = (int) (tmp & LONG_MASK);1568qrem = (int) (tmp >>> 32);1569}1570}15711572if (qhat == 0)1573continue;15741575if (!skipCorrection) { // Correct qhat1576long nl = rem.value[j+2+rem.offset] & LONG_MASK;1577long rs = ((qrem & LONG_MASK) << 32) | nl;1578long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);15791580if (unsignedLongCompare(estProduct, rs)) {1581qhat--;1582qrem = (int)((qrem & LONG_MASK) + dhLong);1583if ((qrem & LONG_MASK) >= dhLong) {1584estProduct -= (dl & LONG_MASK);1585rs = ((qrem & LONG_MASK) << 32) | nl;1586if (unsignedLongCompare(estProduct, rs))1587qhat--;1588}1589}1590}15911592// D4 Multiply and subtract1593rem.value[j+rem.offset] = 0;1594int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset);15951596// D5 Test remainder1597if (borrow + 0x80000000 > nh2) {1598// D6 Add back1599divadd(divisor, rem.value, j+1+rem.offset);1600qhat--;1601}16021603// Store the quotient digit1604q[j] = qhat;1605} // D7 loop on j1606// D3 Calculate qhat1607// estimate qhat1608int qhat = 0;1609int qrem = 0;1610boolean skipCorrection = false;1611int nh = rem.value[limit - 1 + rem.offset];1612int nh2 = nh + 0x80000000;1613int nm = rem.value[limit + rem.offset];16141615if (nh == dh) {1616qhat = ~0;1617qrem = nh + nm;1618skipCorrection = qrem + 0x80000000 < nh2;1619} else {1620long nChunk = (((long) nh) << 32) | (nm & LONG_MASK);1621if (nChunk >= 0) {1622qhat = (int) (nChunk / dhLong);1623qrem = (int) (nChunk - (qhat * dhLong));1624} else {1625long tmp = divWord(nChunk, dh);1626qhat = (int) (tmp & LONG_MASK);1627qrem = (int) (tmp >>> 32);1628}1629}1630if (qhat != 0) {1631if (!skipCorrection) { // Correct qhat1632long nl = rem.value[limit + 1 + rem.offset] & LONG_MASK;1633long rs = ((qrem & LONG_MASK) << 32) | nl;1634long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);16351636if (unsignedLongCompare(estProduct, rs)) {1637qhat--;1638qrem = (int) ((qrem & LONG_MASK) + dhLong);1639if ((qrem & LONG_MASK) >= dhLong) {1640estProduct -= (dl & LONG_MASK);1641rs = ((qrem & LONG_MASK) << 32) | nl;1642if (unsignedLongCompare(estProduct, rs))1643qhat--;1644}1645}1646}164716481649// D4 Multiply and subtract1650int borrow;1651rem.value[limit - 1 + rem.offset] = 0;1652if(needRemainder)1653borrow = mulsub(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset);1654else1655borrow = mulsubBorrow(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset);16561657// D5 Test remainder1658if (borrow + 0x80000000 > nh2) {1659// D6 Add back1660if(needRemainder)1661divadd(divisor, rem.value, limit - 1 + 1 + rem.offset);1662qhat--;1663}16641665// Store the quotient digit1666q[(limit - 1)] = qhat;1667}166816691670if (needRemainder) {1671// D8 Unnormalize1672if (shift > 0)1673rem.rightShift(shift);1674rem.normalize();1675}1676quotient.normalize();1677return needRemainder ? rem : null;1678}16791680/**1681* Divide this MutableBigInteger by the divisor represented by positive long1682* value. The quotient will be placed into the provided quotient object &1683* the remainder object is returned.1684*/1685private MutableBigInteger divideLongMagnitude(long ldivisor, MutableBigInteger quotient) {1686// Remainder starts as dividend with space for a leading zero1687MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]);1688System.arraycopy(value, offset, rem.value, 1, intLen);1689rem.intLen = intLen;1690rem.offset = 1;16911692int nlen = rem.intLen;16931694int limit = nlen - 2 + 1;1695if (quotient.value.length < limit) {1696quotient.value = new int[limit];1697quotient.offset = 0;1698}1699quotient.intLen = limit;1700int[] q = quotient.value;17011702// D1 normalize the divisor1703int shift = Long.numberOfLeadingZeros(ldivisor);1704if (shift > 0) {1705ldivisor<<=shift;1706rem.leftShift(shift);1707}17081709// Must insert leading 0 in rem if its length did not change1710if (rem.intLen == nlen) {1711rem.offset = 0;1712rem.value[0] = 0;1713rem.intLen++;1714}17151716int dh = (int)(ldivisor >>> 32);1717long dhLong = dh & LONG_MASK;1718int dl = (int)(ldivisor & LONG_MASK);17191720// D2 Initialize j1721for (int j = 0; j < limit; j++) {1722// D3 Calculate qhat1723// estimate qhat1724int qhat = 0;1725int qrem = 0;1726boolean skipCorrection = false;1727int nh = rem.value[j + rem.offset];1728int nh2 = nh + 0x80000000;1729int nm = rem.value[j + 1 + rem.offset];17301731if (nh == dh) {1732qhat = ~0;1733qrem = nh + nm;1734skipCorrection = qrem + 0x80000000 < nh2;1735} else {1736long nChunk = (((long) nh) << 32) | (nm & LONG_MASK);1737if (nChunk >= 0) {1738qhat = (int) (nChunk / dhLong);1739qrem = (int) (nChunk - (qhat * dhLong));1740} else {1741long tmp = divWord(nChunk, dh);1742qhat =(int)(tmp & LONG_MASK);1743qrem = (int)(tmp>>>32);1744}1745}17461747if (qhat == 0)1748continue;17491750if (!skipCorrection) { // Correct qhat1751long nl = rem.value[j + 2 + rem.offset] & LONG_MASK;1752long rs = ((qrem & LONG_MASK) << 32) | nl;1753long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);17541755if (unsignedLongCompare(estProduct, rs)) {1756qhat--;1757qrem = (int) ((qrem & LONG_MASK) + dhLong);1758if ((qrem & LONG_MASK) >= dhLong) {1759estProduct -= (dl & LONG_MASK);1760rs = ((qrem & LONG_MASK) << 32) | nl;1761if (unsignedLongCompare(estProduct, rs))1762qhat--;1763}1764}1765}17661767// D4 Multiply and subtract1768rem.value[j + rem.offset] = 0;1769int borrow = mulsubLong(rem.value, dh, dl, qhat, j + rem.offset);17701771// D5 Test remainder1772if (borrow + 0x80000000 > nh2) {1773// D6 Add back1774divaddLong(dh,dl, rem.value, j + 1 + rem.offset);1775qhat--;1776}17771778// Store the quotient digit1779q[j] = qhat;1780} // D7 loop on j17811782// D8 Unnormalize1783if (shift > 0)1784rem.rightShift(shift);17851786quotient.normalize();1787rem.normalize();1788return rem;1789}17901791/**1792* A primitive used for division by long.1793* Specialized version of the method divadd.1794* dh is a high part of the divisor, dl is a low part1795*/1796private int divaddLong(int dh, int dl, int[] result, int offset) {1797long carry = 0;17981799long sum = (dl & LONG_MASK) + (result[1+offset] & LONG_MASK);1800result[1+offset] = (int)sum;18011802sum = (dh & LONG_MASK) + (result[offset] & LONG_MASK) + carry;1803result[offset] = (int)sum;1804carry = sum >>> 32;1805return (int)carry;1806}18071808/**1809* This method is used for division by long.1810* Specialized version of the method sulsub.1811* dh is a high part of the divisor, dl is a low part1812*/1813private int mulsubLong(int[] q, int dh, int dl, int x, int offset) {1814long xLong = x & LONG_MASK;1815offset += 2;1816long product = (dl & LONG_MASK) * xLong;1817long difference = q[offset] - product;1818q[offset--] = (int)difference;1819long carry = (product >>> 32)1820+ (((difference & LONG_MASK) >1821(((~(int)product) & LONG_MASK))) ? 1:0);1822product = (dh & LONG_MASK) * xLong + carry;1823difference = q[offset] - product;1824q[offset--] = (int)difference;1825carry = (product >>> 32)1826+ (((difference & LONG_MASK) >1827(((~(int)product) & LONG_MASK))) ? 1:0);1828return (int)carry;1829}18301831/**1832* Compare two longs as if they were unsigned.1833* Returns true iff one is bigger than two.1834*/1835private boolean unsignedLongCompare(long one, long two) {1836return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);1837}18381839/**1840* This method divides a long quantity by an int to estimate1841* qhat for two multi precision numbers. It is used when1842* the signed value of n is less than zero.1843* Returns long value where high 32 bits contain remainder value and1844* low 32 bits contain quotient value.1845*/1846static long divWord(long n, int d) {1847long dLong = d & LONG_MASK;1848long r;1849long q;1850if (dLong == 1) {1851q = (int)n;1852r = 0;1853return (r << 32) | (q & LONG_MASK);1854}18551856// Approximate the quotient and remainder1857q = (n >>> 1) / (dLong >>> 1);1858r = n - q*dLong;18591860// Correct the approximation1861while (r < 0) {1862r += dLong;1863q--;1864}1865while (r >= dLong) {1866r -= dLong;1867q++;1868}1869// n - q*dlong == r && 0 <= r <dLong, hence we're done.1870return (r << 32) | (q & LONG_MASK);1871}18721873/**1874* Calculate the integer square root {@code floor(sqrt(this))} where1875* {@code sqrt(.)} denotes the mathematical square root. The contents of1876* {@code this} are <b>not</b> changed. The value of {@code this} is assumed1877* to be non-negative.1878*1879* @implNote The implementation is based on the material in Henry S. Warren,1880* Jr., <i>Hacker's Delight (2nd ed.)</i> (Addison Wesley, 2013), 279-282.1881*1882* @throws ArithmeticException if the value returned by {@code bitLength()}1883* overflows the range of {@code int}.1884* @return the integer square root of {@code this}1885* @since 91886*/1887MutableBigInteger sqrt() {1888// Special cases.1889if (this.isZero()) {1890return new MutableBigInteger(0);1891} else if (this.value.length == 11892&& (this.value[0] & LONG_MASK) < 4) { // result is unity1893return ONE;1894}18951896if (bitLength() <= 63) {1897// Initial estimate is the square root of the positive long value.1898long v = new BigInteger(this.value, 1).longValueExact();1899long xk = (long)Math.floor(Math.sqrt(v));19001901// Refine the estimate.1902do {1903long xk1 = (xk + v/xk)/2;19041905// Terminate when non-decreasing.1906if (xk1 >= xk) {1907return new MutableBigInteger(new int[] {1908(int)(xk >>> 32), (int)(xk & LONG_MASK)1909});1910}19111912xk = xk1;1913} while (true);1914} else {1915// Set up the initial estimate of the iteration.19161917// Obtain the bitLength > 63.1918int bitLength = (int) this.bitLength();1919if (bitLength != this.bitLength()) {1920throw new ArithmeticException("bitLength() integer overflow");1921}19221923// Determine an even valued right shift into positive long range.1924int shift = bitLength - 63;1925if (shift % 2 == 1) {1926shift++;1927}19281929// Shift the value into positive long range.1930MutableBigInteger xk = new MutableBigInteger(this);1931xk.rightShift(shift);1932xk.normalize();19331934// Use the square root of the shifted value as an approximation.1935double d = new BigInteger(xk.value, 1).doubleValue();1936BigInteger bi = BigInteger.valueOf((long)Math.ceil(Math.sqrt(d)));1937xk = new MutableBigInteger(bi.mag);19381939// Shift the approximate square root back into the original range.1940xk.leftShift(shift / 2);19411942// Refine the estimate.1943MutableBigInteger xk1 = new MutableBigInteger();1944do {1945// xk1 = (xk + n/xk)/21946this.divide(xk, xk1, false);1947xk1.add(xk);1948xk1.rightShift(1);19491950// Terminate when non-decreasing.1951if (xk1.compare(xk) >= 0) {1952return xk;1953}19541955// xk = xk11956xk.copyValue(xk1);19571958xk1.reset();1959} while (true);1960}1961}19621963/**1964* Calculate GCD of this and b. This and b are changed by the computation.1965*/1966MutableBigInteger hybridGCD(MutableBigInteger b) {1967// Use Euclid's algorithm until the numbers are approximately the1968// same length, then use the binary GCD algorithm to find the GCD.1969MutableBigInteger a = this;1970MutableBigInteger q = new MutableBigInteger();19711972while (b.intLen != 0) {1973if (Math.abs(a.intLen - b.intLen) < 2)1974return a.binaryGCD(b);19751976MutableBigInteger r = a.divide(b, q);1977a = b;1978b = r;1979}1980return a;1981}19821983/**1984* Calculate GCD of this and v.1985* Assumes that this and v are not zero.1986*/1987private MutableBigInteger binaryGCD(MutableBigInteger v) {1988// Algorithm B from Knuth TAOCP Vol. 2, 3rd edition, section 4.5.21989MutableBigInteger u = this;1990MutableBigInteger r = new MutableBigInteger();19911992// step B11993int s1 = u.getLowestSetBit();1994int s2 = v.getLowestSetBit();1995int k = (s1 < s2) ? s1 : s2;1996if (k != 0) {1997u.rightShift(k);1998v.rightShift(k);1999}20002001// step B22002boolean uOdd = (k == s1);2003MutableBigInteger t = uOdd ? v: u;2004int tsign = uOdd ? -1 : 1;20052006int lb;2007while ((lb = t.getLowestSetBit()) >= 0) {2008// steps B3 and B42009t.rightShift(lb);2010// step B52011if (tsign > 0)2012u = t;2013else2014v = t;20152016// Special case one word numbers2017if (u.intLen < 2 && v.intLen < 2) {2018int x = u.value[u.offset];2019int y = v.value[v.offset];2020x = binaryGcd(x, y);2021r.value[0] = x;2022r.intLen = 1;2023r.offset = 0;2024if (k > 0)2025r.leftShift(k);2026return r;2027}20282029// step B62030if ((tsign = u.difference(v)) == 0)2031break;2032t = (tsign >= 0) ? u : v;2033}20342035if (k > 0)2036u.leftShift(k);2037return u;2038}20392040/**2041* Calculate GCD of a and b interpreted as unsigned integers.2042*/2043static int binaryGcd(int a, int b) {2044if (b == 0)2045return a;2046if (a == 0)2047return b;20482049// Right shift a & b till their last bits equal to 1.2050int aZeros = Integer.numberOfTrailingZeros(a);2051int bZeros = Integer.numberOfTrailingZeros(b);2052a >>>= aZeros;2053b >>>= bZeros;20542055int t = (aZeros < bZeros ? aZeros : bZeros);20562057while (a != b) {2058if ((a+0x80000000) > (b+0x80000000)) { // a > b as unsigned2059a -= b;2060a >>>= Integer.numberOfTrailingZeros(a);2061} else {2062b -= a;2063b >>>= Integer.numberOfTrailingZeros(b);2064}2065}2066return a<<t;2067}20682069/**2070* Returns the modInverse of this mod p. This and p are not affected by2071* the operation.2072*/2073MutableBigInteger mutableModInverse(MutableBigInteger p) {2074// Modulus is odd, use Schroeppel's algorithm2075if (p.isOdd())2076return modInverse(p);20772078// Base and modulus are even, throw exception2079if (isEven())2080throw new ArithmeticException("BigInteger not invertible.");20812082// Get even part of modulus expressed as a power of 22083int powersOf2 = p.getLowestSetBit();20842085// Construct odd part of modulus2086MutableBigInteger oddMod = new MutableBigInteger(p);2087oddMod.rightShift(powersOf2);20882089if (oddMod.isOne())2090return modInverseMP2(powersOf2);20912092// Calculate 1/a mod oddMod2093MutableBigInteger oddPart = modInverse(oddMod);20942095// Calculate 1/a mod evenMod2096MutableBigInteger evenPart = modInverseMP2(powersOf2);20972098// Combine the results using Chinese Remainder Theorem2099MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2);2100MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2);21012102MutableBigInteger temp1 = new MutableBigInteger();2103MutableBigInteger temp2 = new MutableBigInteger();2104MutableBigInteger result = new MutableBigInteger();21052106oddPart.leftShift(powersOf2);2107oddPart.multiply(y1, result);21082109evenPart.multiply(oddMod, temp1);2110temp1.multiply(y2, temp2);21112112result.add(temp2);2113return result.divide(p, temp1);2114}21152116/*2117* Calculate the multiplicative inverse of this mod 2^k.2118*/2119MutableBigInteger modInverseMP2(int k) {2120if (isEven())2121throw new ArithmeticException("Non-invertible. (GCD != 1)");21222123if (k > 64)2124return euclidModInverse(k);21252126int t = inverseMod32(value[offset+intLen-1]);21272128if (k < 33) {2129t = (k == 32 ? t : t & ((1 << k) - 1));2130return new MutableBigInteger(t);2131}21322133long pLong = (value[offset+intLen-1] & LONG_MASK);2134if (intLen > 1)2135pLong |= ((long)value[offset+intLen-2] << 32);2136long tLong = t & LONG_MASK;2137tLong = tLong * (2 - pLong * tLong); // 1 more Newton iter step2138tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1));21392140MutableBigInteger result = new MutableBigInteger(new int[2]);2141result.value[0] = (int)(tLong >>> 32);2142result.value[1] = (int)tLong;2143result.intLen = 2;2144result.normalize();2145return result;2146}21472148/**2149* Returns the multiplicative inverse of val mod 2^32. Assumes val is odd.2150*/2151static int inverseMod32(int val) {2152// Newton's iteration!2153int t = val;2154t *= 2 - val*t;2155t *= 2 - val*t;2156t *= 2 - val*t;2157t *= 2 - val*t;2158return t;2159}21602161/**2162* Returns the multiplicative inverse of val mod 2^64. Assumes val is odd.2163*/2164static long inverseMod64(long val) {2165// Newton's iteration!2166long t = val;2167t *= 2 - val*t;2168t *= 2 - val*t;2169t *= 2 - val*t;2170t *= 2 - val*t;2171t *= 2 - val*t;2172assert(t * val == 1);2173return t;2174}21752176/**2177* Calculate the multiplicative inverse of 2^k mod mod, where mod is odd.2178*/2179static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) {2180// Copy the mod to protect original2181return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k);2182}21832184/**2185* Calculate the multiplicative inverse of this modulo mod, where the mod2186* argument is odd. This and mod are not changed by the calculation.2187*2188* This method implements an algorithm due to Richard Schroeppel, that uses2189* the same intermediate representation as Montgomery Reduction2190* ("Montgomery Form"). The algorithm is described in an unpublished2191* manuscript entitled "Fast Modular Reciprocals."2192*/2193private MutableBigInteger modInverse(MutableBigInteger mod) {2194MutableBigInteger p = new MutableBigInteger(mod);2195MutableBigInteger f = new MutableBigInteger(this);2196MutableBigInteger g = new MutableBigInteger(p);2197SignedMutableBigInteger c = new SignedMutableBigInteger(1);2198SignedMutableBigInteger d = new SignedMutableBigInteger();2199MutableBigInteger temp = null;2200SignedMutableBigInteger sTemp = null;22012202int k = 0;2203// Right shift f k times until odd, left shift d k times2204if (f.isEven()) {2205int trailingZeros = f.getLowestSetBit();2206f.rightShift(trailingZeros);2207d.leftShift(trailingZeros);2208k = trailingZeros;2209}22102211// The Almost Inverse Algorithm2212while (!f.isOne()) {2213// If gcd(f, g) != 1, number is not invertible modulo mod2214if (f.isZero())2215throw new ArithmeticException("BigInteger not invertible.");22162217// If f < g exchange f, g and c, d2218if (f.compare(g) < 0) {2219temp = f; f = g; g = temp;2220sTemp = d; d = c; c = sTemp;2221}22222223// If f == g (mod 4)2224if (((f.value[f.offset + f.intLen - 1] ^2225g.value[g.offset + g.intLen - 1]) & 3) == 0) {2226f.subtract(g);2227c.signedSubtract(d);2228} else { // If f != g (mod 4)2229f.add(g);2230c.signedAdd(d);2231}22322233// Right shift f k times until odd, left shift d k times2234int trailingZeros = f.getLowestSetBit();2235f.rightShift(trailingZeros);2236d.leftShift(trailingZeros);2237k += trailingZeros;2238}22392240if (c.compare(p) >= 0) { // c has a larger magnitude than p2241MutableBigInteger remainder = c.divide(p,2242new MutableBigInteger());2243// The previous line ignores the sign so we copy the data back2244// into c which will restore the sign as needed (and converts2245// it back to a SignedMutableBigInteger)2246c.copyValue(remainder);2247}22482249if (c.sign < 0) {2250c.signedAdd(p);2251}22522253return fixup(c, p, k);2254}22552256/**2257* The Fixup Algorithm2258* Calculates X such that X = C * 2^(-k) (mod P)2259* Assumes C<P and P is odd.2260*/2261static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p,2262int k) {2263MutableBigInteger temp = new MutableBigInteger();2264// Set r to the multiplicative inverse of p mod 2^322265int r = -inverseMod32(p.value[p.offset+p.intLen-1]);22662267for (int i=0, numWords = k >> 5; i < numWords; i++) {2268// V = R * c (mod 2^j)2269int v = r * c.value[c.offset + c.intLen-1];2270// c = c + (v * p)2271p.mul(v, temp);2272c.add(temp);2273// c = c / 2^j2274c.intLen--;2275}2276int numBits = k & 0x1f;2277if (numBits != 0) {2278// V = R * c (mod 2^j)2279int v = r * c.value[c.offset + c.intLen-1];2280v &= ((1<<numBits) - 1);2281// c = c + (v * p)2282p.mul(v, temp);2283c.add(temp);2284// c = c / 2^j2285c.rightShift(numBits);2286}22872288// In theory, c may be greater than p at this point (Very rare!)2289if (c.compare(p) >= 0)2290c = c.divide(p, new MutableBigInteger());22912292return c;2293}22942295/**2296* Uses the extended Euclidean algorithm to compute the modInverse of base2297* mod a modulus that is a power of 2. The modulus is 2^k.2298*/2299MutableBigInteger euclidModInverse(int k) {2300MutableBigInteger b = new MutableBigInteger(1);2301b.leftShift(k);2302MutableBigInteger mod = new MutableBigInteger(b);23032304MutableBigInteger a = new MutableBigInteger(this);2305MutableBigInteger q = new MutableBigInteger();2306MutableBigInteger r = b.divide(a, q);23072308MutableBigInteger swapper = b;2309// swap b & r2310b = r;2311r = swapper;23122313MutableBigInteger t1 = new MutableBigInteger(q);2314MutableBigInteger t0 = new MutableBigInteger(1);2315MutableBigInteger temp = new MutableBigInteger();23162317while (!b.isOne()) {2318r = a.divide(b, q);23192320if (r.intLen == 0)2321throw new ArithmeticException("BigInteger not invertible.");23222323swapper = r;2324a = swapper;23252326if (q.intLen == 1)2327t1.mul(q.value[q.offset], temp);2328else2329q.multiply(t1, temp);2330swapper = q;2331q = temp;2332temp = swapper;2333t0.add(q);23342335if (a.isOne())2336return t0;23372338r = b.divide(a, q);23392340if (r.intLen == 0)2341throw new ArithmeticException("BigInteger not invertible.");23422343swapper = b;2344b = r;23452346if (q.intLen == 1)2347t0.mul(q.value[q.offset], temp);2348else2349q.multiply(t0, temp);2350swapper = q; q = temp; temp = swapper;23512352t1.add(q);2353}2354mod.subtract(t1);2355return mod;2356}2357}235823592360