0N/A/*
2362N/A * Copyright (c) 1999, 2007, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.math;
0N/A
0N/A/**
0N/A * A class used to represent multiprecision integers that makes efficient
0N/A * use of allocated space by allowing a number to occupy only part of
0N/A * an array so that the arrays do not have to be reallocated as often.
0N/A * When performing an operation with many iterations the array used to
0N/A * hold a number is only reallocated when necessary and does not have to
0N/A * be the same size as the number it represents. A mutable number allows
0N/A * calculations to occur on the same number without having to create
0N/A * a new number for every step of the calculation as occurs with
0N/A * BigIntegers.
0N/A *
0N/A * @see BigInteger
0N/A * @author Michael McCloskey
0N/A * @since 1.3
0N/A */
0N/A
1246N/Aimport java.util.Arrays;
1246N/A
1246N/Aimport static java.math.BigInteger.LONG_MASK;
1246N/Aimport static java.math.BigDecimal.INFLATED;
1246N/A
0N/Aclass MutableBigInteger {
0N/A /**
0N/A * Holds the magnitude of this MutableBigInteger in big endian order.
0N/A * The magnitude may start at an offset into the value array, and it may
0N/A * end before the length of the value array.
0N/A */
0N/A int[] value;
0N/A
0N/A /**
0N/A * The number of ints of the value array that are currently used
0N/A * to hold the magnitude of this MutableBigInteger. The magnitude starts
0N/A * at an offset and offset + intLen may be less than value.length.
0N/A */
0N/A int intLen;
0N/A
0N/A /**
0N/A * The offset into the value array where the magnitude of this
0N/A * MutableBigInteger begins.
0N/A */
0N/A int offset = 0;
0N/A
1246N/A // Constants
0N/A /**
1246N/A * MutableBigInteger with one element value array with the value 1. Used by
1246N/A * BigDecimal divideAndRound to increment the quotient. Use this constant
1246N/A * only when the method is not going to modify this object.
0N/A */
1246N/A static final MutableBigInteger ONE = new MutableBigInteger(1);
0N/A
0N/A // Constructors
0N/A
0N/A /**
0N/A * The default constructor. An empty MutableBigInteger is created with
0N/A * a one word capacity.
0N/A */
0N/A MutableBigInteger() {
0N/A value = new int[1];
0N/A intLen = 0;
0N/A }
0N/A
0N/A /**
0N/A * Construct a new MutableBigInteger with a magnitude specified by
0N/A * the int val.
0N/A */
0N/A MutableBigInteger(int val) {
0N/A value = new int[1];
0N/A intLen = 1;
0N/A value[0] = val;
0N/A }
0N/A
0N/A /**
0N/A * Construct a new MutableBigInteger with the specified value array
0N/A * up to the length of the array supplied.
0N/A */
0N/A MutableBigInteger(int[] val) {
0N/A value = val;
0N/A intLen = val.length;
0N/A }
0N/A
0N/A /**
0N/A * Construct a new MutableBigInteger with a magnitude equal to the
0N/A * specified BigInteger.
0N/A */
0N/A MutableBigInteger(BigInteger b) {
1246N/A intLen = b.mag.length;
1246N/A value = Arrays.copyOf(b.mag, intLen);
0N/A }
0N/A
0N/A /**
0N/A * Construct a new MutableBigInteger with a magnitude equal to the
0N/A * specified MutableBigInteger.
0N/A */
0N/A MutableBigInteger(MutableBigInteger val) {
0N/A intLen = val.intLen;
1246N/A value = Arrays.copyOfRange(val.value, val.offset, val.offset + intLen);
1246N/A }
1246N/A
1246N/A /**
1246N/A * Internal helper method to return the magnitude array. The caller is not
1246N/A * supposed to modify the returned array.
1246N/A */
1246N/A private int[] getMagnitudeArray() {
1246N/A if (offset > 0 || value.length != intLen)
1246N/A return Arrays.copyOfRange(value, offset, offset + intLen);
1246N/A return value;
1246N/A }
1246N/A
1246N/A /**
1246N/A * Convert this MutableBigInteger to a long value. The caller has to make
1246N/A * sure this MutableBigInteger can be fit into long.
1246N/A */
1246N/A private long toLong() {
1246N/A assert (intLen <= 2) : "this MutableBigInteger exceeds the range of long";
1246N/A if (intLen == 0)
1246N/A return 0;
1246N/A long d = value[offset] & LONG_MASK;
1246N/A return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d;
1246N/A }
0N/A
1246N/A /**
1246N/A * Convert this MutableBigInteger to a BigInteger object.
1246N/A */
1246N/A BigInteger toBigInteger(int sign) {
1246N/A if (intLen == 0 || sign == 0)
1246N/A return BigInteger.ZERO;
1246N/A return new BigInteger(getMagnitudeArray(), sign);
1246N/A }
1246N/A
1246N/A /**
1246N/A * Convert this MutableBigInteger to BigDecimal object with the specified sign
1246N/A * and scale.
1246N/A */
1246N/A BigDecimal toBigDecimal(int sign, int scale) {
1246N/A if (intLen == 0 || sign == 0)
1246N/A return BigDecimal.valueOf(0, scale);
1246N/A int[] mag = getMagnitudeArray();
1246N/A int len = mag.length;
1246N/A int d = mag[0];
1246N/A // If this MutableBigInteger can't be fit into long, we need to
1246N/A // make a BigInteger object for the resultant BigDecimal object.
1246N/A if (len > 2 || (d < 0 && len == 2))
1246N/A return new BigDecimal(new BigInteger(mag, sign), INFLATED, scale, 0);
1246N/A long v = (len == 2) ?
1246N/A ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) :
1246N/A d & LONG_MASK;
1246N/A return new BigDecimal(null, sign == -1 ? -v : v, scale, 0);
0N/A }
0N/A
0N/A /**
0N/A * Clear out a MutableBigInteger for reuse.
0N/A */
0N/A void clear() {
0N/A offset = intLen = 0;
0N/A for (int index=0, n=value.length; index < n; index++)
0N/A value[index] = 0;
0N/A }
0N/A
0N/A /**
0N/A * Set a MutableBigInteger to zero, removing its offset.
0N/A */
0N/A void reset() {
0N/A offset = intLen = 0;
0N/A }
0N/A
0N/A /**
0N/A * Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1
0N/A * as this MutableBigInteger is numerically less than, equal to, or
1246N/A * greater than <tt>b</tt>.
0N/A */
0N/A final int compare(MutableBigInteger b) {
1246N/A int blen = b.intLen;
1246N/A if (intLen < blen)
0N/A return -1;
1246N/A if (intLen > blen)
1246N/A return 1;
0N/A
1246N/A // Add Integer.MIN_VALUE to make the comparison act as unsigned integer
1246N/A // comparison.
1246N/A int[] bval = b.value;
1246N/A for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) {
1246N/A int b1 = value[i] + 0x80000000;
1246N/A int b2 = bval[j] + 0x80000000;
0N/A if (b1 < b2)
0N/A return -1;
0N/A if (b1 > b2)
0N/A return 1;
0N/A }
0N/A return 0;
0N/A }
0N/A
0N/A /**
1246N/A * Compare this against half of a MutableBigInteger object (Needed for
1246N/A * remainder tests).
1246N/A * Assumes no leading unnecessary zeros, which holds for results
1246N/A * from divide().
1246N/A */
1246N/A final int compareHalf(MutableBigInteger b) {
1246N/A int blen = b.intLen;
1246N/A int len = intLen;
1246N/A if (len <= 0)
1246N/A return blen <=0 ? 0 : -1;
1246N/A if (len > blen)
1246N/A return 1;
1246N/A if (len < blen - 1)
1246N/A return -1;
1246N/A int[] bval = b.value;
1246N/A int bstart = 0;
1246N/A int carry = 0;
1246N/A // Only 2 cases left:len == blen or len == blen - 1
1246N/A if (len != blen) { // len == blen - 1
1246N/A if (bval[bstart] == 1) {
1246N/A ++bstart;
1246N/A carry = 0x80000000;
1246N/A } else
1246N/A return -1;
1246N/A }
1246N/A // compare values with right-shifted values of b,
1246N/A // carrying shifted-out bits across words
1246N/A int[] val = value;
1246N/A for (int i = offset, j = bstart; i < len + offset;) {
1246N/A int bv = bval[j++];
1246N/A long hb = ((bv >>> 1) + carry) & LONG_MASK;
1246N/A long v = val[i++] & LONG_MASK;
1246N/A if (v != hb)
1246N/A return v < hb ? -1 : 1;
1246N/A carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0
1246N/A }
1246N/A return carry == 0? 0 : -1;
1246N/A }
1246N/A
1246N/A /**
0N/A * Return the index of the lowest set bit in this MutableBigInteger. If the
0N/A * magnitude of this MutableBigInteger is zero, -1 is returned.
0N/A */
0N/A private final int getLowestSetBit() {
0N/A if (intLen == 0)
0N/A return -1;
0N/A int j, b;
0N/A for (j=intLen-1; (j>0) && (value[j+offset]==0); j--)
0N/A ;
0N/A b = value[j+offset];
0N/A if (b==0)
0N/A return -1;
1246N/A return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b);
0N/A }
0N/A
0N/A /**
0N/A * Return the int in use in this MutableBigInteger at the specified
0N/A * index. This method is not used because it is not inlined on all
0N/A * platforms.
0N/A */
0N/A private final int getInt(int index) {
0N/A return value[offset+index];
0N/A }
0N/A
0N/A /**
0N/A * Return a long which is equal to the unsigned value of the int in
0N/A * use in this MutableBigInteger at the specified index. This method is
0N/A * not used because it is not inlined on all platforms.
0N/A */
0N/A private final long getLong(int index) {
0N/A return value[offset+index] & LONG_MASK;
0N/A }
0N/A
0N/A /**
0N/A * Ensure that the MutableBigInteger is in normal form, specifically
0N/A * making sure that there are no leading zeros, and that if the
0N/A * magnitude is zero, then intLen is zero.
0N/A */
0N/A final void normalize() {
0N/A if (intLen == 0) {
0N/A offset = 0;
0N/A return;
0N/A }
0N/A
0N/A int index = offset;
0N/A if (value[index] != 0)
0N/A return;
0N/A
0N/A int indexBound = index+intLen;
0N/A do {
0N/A index++;
0N/A } while(index < indexBound && value[index]==0);
0N/A
0N/A int numZeros = index - offset;
0N/A intLen -= numZeros;
0N/A offset = (intLen==0 ? 0 : offset+numZeros);
0N/A }
0N/A
0N/A /**
0N/A * If this MutableBigInteger cannot hold len words, increase the size
0N/A * of the value array to len words.
0N/A */
0N/A private final void ensureCapacity(int len) {
0N/A if (value.length < len) {
0N/A value = new int[len];
0N/A offset = 0;
0N/A intLen = len;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Convert this MutableBigInteger into an int array with no leading
0N/A * zeros, of a length that is equal to this MutableBigInteger's intLen.
0N/A */
0N/A int[] toIntArray() {
0N/A int[] result = new int[intLen];
0N/A for(int i=0; i<intLen; i++)
0N/A result[i] = value[offset+i];
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Sets the int at index+offset in this MutableBigInteger to val.
0N/A * This does not get inlined on all platforms so it is not used
0N/A * as often as originally intended.
0N/A */
0N/A void setInt(int index, int val) {
0N/A value[offset + index] = val;
0N/A }
0N/A
0N/A /**
0N/A * Sets this MutableBigInteger's value array to the specified array.
0N/A * The intLen is set to the specified length.
0N/A */
0N/A void setValue(int[] val, int length) {
0N/A value = val;
0N/A intLen = length;
0N/A offset = 0;
0N/A }
0N/A
0N/A /**
0N/A * Sets this MutableBigInteger's value array to a copy of the specified
0N/A * array. The intLen is set to the length of the new array.
0N/A */
1246N/A void copyValue(MutableBigInteger src) {
1246N/A int len = src.intLen;
0N/A if (value.length < len)
0N/A value = new int[len];
1246N/A System.arraycopy(src.value, src.offset, value, 0, len);
0N/A intLen = len;
0N/A offset = 0;
0N/A }
0N/A
0N/A /**
0N/A * Sets this MutableBigInteger's value array to a copy of the specified
0N/A * array. The intLen is set to the length of the specified array.
0N/A */
0N/A void copyValue(int[] val) {
0N/A int len = val.length;
0N/A if (value.length < len)
0N/A value = new int[len];
1246N/A System.arraycopy(val, 0, value, 0, len);
0N/A intLen = len;
0N/A offset = 0;
0N/A }
0N/A
0N/A /**
0N/A * Returns true iff this MutableBigInteger has a value of one.
0N/A */
0N/A boolean isOne() {
0N/A return (intLen == 1) && (value[offset] == 1);
0N/A }
0N/A
0N/A /**
0N/A * Returns true iff this MutableBigInteger has a value of zero.
0N/A */
0N/A boolean isZero() {
0N/A return (intLen == 0);
0N/A }
0N/A
0N/A /**
0N/A * Returns true iff this MutableBigInteger is even.
0N/A */
0N/A boolean isEven() {
0N/A return (intLen == 0) || ((value[offset + intLen - 1] & 1) == 0);
0N/A }
0N/A
0N/A /**
0N/A * Returns true iff this MutableBigInteger is odd.
0N/A */
0N/A boolean isOdd() {
1246N/A return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1);
0N/A }
0N/A
0N/A /**
0N/A * Returns true iff this MutableBigInteger is in normal form. A
0N/A * MutableBigInteger is in normal form if it has no leading zeros
0N/A * after the offset, and intLen + offset <= value.length.
0N/A */
0N/A boolean isNormal() {
0N/A if (intLen + offset > value.length)
0N/A return false;
0N/A if (intLen ==0)
0N/A return true;
0N/A return (value[offset] != 0);
0N/A }
0N/A
0N/A /**
0N/A * Returns a String representation of this MutableBigInteger in radix 10.
0N/A */
0N/A public String toString() {
1246N/A BigInteger b = toBigInteger(1);
0N/A return b.toString();
0N/A }
0N/A
0N/A /**
0N/A * Right shift this MutableBigInteger n bits. The MutableBigInteger is left
0N/A * in normal form.
0N/A */
0N/A void rightShift(int n) {
0N/A if (intLen == 0)
0N/A return;
0N/A int nInts = n >>> 5;
0N/A int nBits = n & 0x1F;
0N/A this.intLen -= nInts;
0N/A if (nBits == 0)
0N/A return;
1246N/A int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
0N/A if (nBits >= bitsInHighWord) {
0N/A this.primitiveLeftShift(32 - nBits);
0N/A this.intLen--;
0N/A } else {
0N/A primitiveRightShift(nBits);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Left shift this MutableBigInteger n bits.
0N/A */
0N/A void leftShift(int n) {
0N/A /*
0N/A * If there is enough storage space in this MutableBigInteger already
0N/A * the available space will be used. Space to the right of the used
0N/A * ints in the value array is faster to utilize, so the extra space
0N/A * will be taken from the right if possible.
0N/A */
0N/A if (intLen == 0)
0N/A return;
0N/A int nInts = n >>> 5;
0N/A int nBits = n&0x1F;
1246N/A int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
0N/A
0N/A // If shift can be done without moving words, do so
0N/A if (n <= (32-bitsInHighWord)) {
0N/A primitiveLeftShift(nBits);
0N/A return;
0N/A }
0N/A
0N/A int newLen = intLen + nInts +1;
0N/A if (nBits <= (32-bitsInHighWord))
0N/A newLen--;
0N/A if (value.length < newLen) {
0N/A // The array must grow
0N/A int[] result = new int[newLen];
0N/A for (int i=0; i<intLen; i++)
0N/A result[i] = value[offset+i];
0N/A setValue(result, newLen);
0N/A } else if (value.length - offset >= newLen) {
0N/A // Use space on right
0N/A for(int i=0; i<newLen - intLen; i++)
0N/A value[offset+intLen+i] = 0;
0N/A } else {
0N/A // Must use space on left
0N/A for (int i=0; i<intLen; i++)
0N/A value[i] = value[offset+i];
0N/A for (int i=intLen; i<newLen; i++)
0N/A value[i] = 0;
0N/A offset = 0;
0N/A }
0N/A intLen = newLen;
0N/A if (nBits == 0)
0N/A return;
0N/A if (nBits <= (32-bitsInHighWord))
0N/A primitiveLeftShift(nBits);
0N/A else
0N/A primitiveRightShift(32 -nBits);
0N/A }
0N/A
0N/A /**
0N/A * A primitive used for division. This method adds in one multiple of the
0N/A * divisor a back to the dividend result at a specified offset. It is used
0N/A * when qhat was estimated too large, and must be adjusted.
0N/A */
0N/A private int divadd(int[] a, int[] result, int offset) {
0N/A long carry = 0;
0N/A
0N/A for (int j=a.length-1; j >= 0; j--) {
0N/A long sum = (a[j] & LONG_MASK) +
0N/A (result[j+offset] & LONG_MASK) + carry;
0N/A result[j+offset] = (int)sum;
0N/A carry = sum >>> 32;
0N/A }
0N/A return (int)carry;
0N/A }
0N/A
0N/A /**
0N/A * This method is used for division. It multiplies an n word input a by one
0N/A * word input x, and subtracts the n word product from q. This is needed
0N/A * when subtracting qhat*divisor from dividend.
0N/A */
0N/A private int mulsub(int[] q, int[] a, int x, int len, int offset) {
0N/A long xLong = x & LONG_MASK;
0N/A long carry = 0;
0N/A offset += len;
0N/A
0N/A for (int j=len-1; j >= 0; j--) {
0N/A long product = (a[j] & LONG_MASK) * xLong + carry;
0N/A long difference = q[offset] - product;
0N/A q[offset--] = (int)difference;
0N/A carry = (product >>> 32)
0N/A + (((difference & LONG_MASK) >
0N/A (((~(int)product) & LONG_MASK))) ? 1:0);
0N/A }
0N/A return (int)carry;
0N/A }
0N/A
0N/A /**
0N/A * Right shift this MutableBigInteger n bits, where n is
0N/A * less than 32.
0N/A * Assumes that intLen > 0, n > 0 for speed
0N/A */
0N/A private final void primitiveRightShift(int n) {
0N/A int[] val = value;
0N/A int n2 = 32 - n;
0N/A for (int i=offset+intLen-1, c=val[i]; i>offset; i--) {
0N/A int b = c;
0N/A c = val[i-1];
0N/A val[i] = (c << n2) | (b >>> n);
0N/A }
0N/A val[offset] >>>= n;
0N/A }
0N/A
0N/A /**
0N/A * Left shift this MutableBigInteger n bits, where n is
0N/A * less than 32.
0N/A * Assumes that intLen > 0, n > 0 for speed
0N/A */
0N/A private final void primitiveLeftShift(int n) {
0N/A int[] val = value;
0N/A int n2 = 32 - n;
0N/A for (int i=offset, c=val[i], m=i+intLen-1; i<m; i++) {
0N/A int b = c;
0N/A c = val[i+1];
0N/A val[i] = (b << n) | (c >>> n2);
0N/A }
0N/A val[offset+intLen-1] <<= n;
0N/A }
0N/A
0N/A /**
0N/A * Adds the contents of two MutableBigInteger objects.The result
0N/A * is placed within this MutableBigInteger.
0N/A * The contents of the addend are not changed.
0N/A */
0N/A void add(MutableBigInteger addend) {
0N/A int x = intLen;
0N/A int y = addend.intLen;
0N/A int resultLen = (intLen > addend.intLen ? intLen : addend.intLen);
0N/A int[] result = (value.length < resultLen ? new int[resultLen] : value);
0N/A
0N/A int rstart = result.length-1;
1246N/A long sum;
1246N/A long carry = 0;
0N/A
0N/A // Add common parts of both numbers
0N/A while(x>0 && y>0) {
0N/A x--; y--;
0N/A sum = (value[x+offset] & LONG_MASK) +
1246N/A (addend.value[y+addend.offset] & LONG_MASK) + carry;
0N/A result[rstart--] = (int)sum;
1246N/A carry = sum >>> 32;
0N/A }
0N/A
0N/A // Add remainder of the longer number
0N/A while(x>0) {
0N/A x--;
1246N/A if (carry == 0 && result == value && rstart == (x + offset))
1246N/A return;
1246N/A sum = (value[x+offset] & LONG_MASK) + carry;
0N/A result[rstart--] = (int)sum;
1246N/A carry = sum >>> 32;
0N/A }
0N/A while(y>0) {
0N/A y--;
1246N/A sum = (addend.value[y+addend.offset] & LONG_MASK) + carry;
0N/A result[rstart--] = (int)sum;
1246N/A carry = sum >>> 32;
0N/A }
0N/A
1246N/A if (carry > 0) { // Result must grow in length
0N/A resultLen++;
0N/A if (result.length < resultLen) {
0N/A int temp[] = new int[resultLen];
1246N/A // Result one word longer from carry-out; copy low-order
1246N/A // bits into new result.
1246N/A System.arraycopy(result, 0, temp, 1, result.length);
0N/A temp[0] = 1;
0N/A result = temp;
0N/A } else {
0N/A result[rstart--] = 1;
0N/A }
0N/A }
0N/A
0N/A value = result;
0N/A intLen = resultLen;
0N/A offset = result.length - resultLen;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Subtracts the smaller of this and b from the larger and places the
0N/A * result into this MutableBigInteger.
0N/A */
0N/A int subtract(MutableBigInteger b) {
0N/A MutableBigInteger a = this;
0N/A
0N/A int[] result = value;
0N/A int sign = a.compare(b);
0N/A
0N/A if (sign == 0) {
0N/A reset();
0N/A return 0;
0N/A }
0N/A if (sign < 0) {
0N/A MutableBigInteger tmp = a;
0N/A a = b;
0N/A b = tmp;
0N/A }
0N/A
0N/A int resultLen = a.intLen;
0N/A if (result.length < resultLen)
0N/A result = new int[resultLen];
0N/A
0N/A long diff = 0;
0N/A int x = a.intLen;
0N/A int y = b.intLen;
0N/A int rstart = result.length - 1;
0N/A
0N/A // Subtract common parts of both numbers
0N/A while (y>0) {
0N/A x--; y--;
0N/A
0N/A diff = (a.value[x+a.offset] & LONG_MASK) -
0N/A (b.value[y+b.offset] & LONG_MASK) - ((int)-(diff>>32));
0N/A result[rstart--] = (int)diff;
0N/A }
0N/A // Subtract remainder of longer number
0N/A while (x>0) {
0N/A x--;
0N/A diff = (a.value[x+a.offset] & LONG_MASK) - ((int)-(diff>>32));
0N/A result[rstart--] = (int)diff;
0N/A }
0N/A
0N/A value = result;
0N/A intLen = resultLen;
0N/A offset = value.length - resultLen;
0N/A normalize();
0N/A return sign;
0N/A }
0N/A
0N/A /**
0N/A * Subtracts the smaller of a and b from the larger and places the result
0N/A * into the larger. Returns 1 if the answer is in a, -1 if in b, 0 if no
0N/A * operation was performed.
0N/A */
0N/A private int difference(MutableBigInteger b) {
0N/A MutableBigInteger a = this;
0N/A int sign = a.compare(b);
0N/A if (sign ==0)
0N/A return 0;
0N/A if (sign < 0) {
0N/A MutableBigInteger tmp = a;
0N/A a = b;
0N/A b = tmp;
0N/A }
0N/A
0N/A long diff = 0;
0N/A int x = a.intLen;
0N/A int y = b.intLen;
0N/A
0N/A // Subtract common parts of both numbers
0N/A while (y>0) {
0N/A x--; y--;
0N/A diff = (a.value[a.offset+ x] & LONG_MASK) -
0N/A (b.value[b.offset+ y] & LONG_MASK) - ((int)-(diff>>32));
0N/A a.value[a.offset+x] = (int)diff;
0N/A }
0N/A // Subtract remainder of longer number
0N/A while (x>0) {
0N/A x--;
0N/A diff = (a.value[a.offset+ x] & LONG_MASK) - ((int)-(diff>>32));
0N/A a.value[a.offset+x] = (int)diff;
0N/A }
0N/A
0N/A a.normalize();
0N/A return sign;
0N/A }
0N/A
0N/A /**
0N/A * Multiply the contents of two MutableBigInteger objects. The result is
0N/A * placed into MutableBigInteger z. The contents of y are not changed.
0N/A */
0N/A void multiply(MutableBigInteger y, MutableBigInteger z) {
0N/A int xLen = intLen;
0N/A int yLen = y.intLen;
0N/A int newLen = xLen + yLen;
0N/A
0N/A // Put z into an appropriate state to receive product
0N/A if (z.value.length < newLen)
0N/A z.value = new int[newLen];
0N/A z.offset = 0;
0N/A z.intLen = newLen;
0N/A
0N/A // The first iteration is hoisted out of the loop to avoid extra add
0N/A long carry = 0;
0N/A for (int j=yLen-1, k=yLen+xLen-1; j >= 0; j--, k--) {
0N/A long product = (y.value[j+y.offset] & LONG_MASK) *
0N/A (value[xLen-1+offset] & LONG_MASK) + carry;
0N/A z.value[k] = (int)product;
0N/A carry = product >>> 32;
0N/A }
0N/A z.value[xLen-1] = (int)carry;
0N/A
0N/A // Perform the multiplication word by word
0N/A for (int i = xLen-2; i >= 0; i--) {
0N/A carry = 0;
0N/A for (int j=yLen-1, k=yLen+i; j >= 0; j--, k--) {
0N/A long product = (y.value[j+y.offset] & LONG_MASK) *
0N/A (value[i+offset] & LONG_MASK) +
0N/A (z.value[k] & LONG_MASK) + carry;
0N/A z.value[k] = (int)product;
0N/A carry = product >>> 32;
0N/A }
0N/A z.value[i] = (int)carry;
0N/A }
0N/A
0N/A // Remove leading zeros from product
0N/A z.normalize();
0N/A }
0N/A
0N/A /**
0N/A * Multiply the contents of this MutableBigInteger by the word y. The
0N/A * result is placed into z.
0N/A */
0N/A void mul(int y, MutableBigInteger z) {
0N/A if (y == 1) {
0N/A z.copyValue(this);
0N/A return;
0N/A }
0N/A
0N/A if (y == 0) {
0N/A z.clear();
0N/A return;
0N/A }
0N/A
0N/A // Perform the multiplication word by word
0N/A long ylong = y & LONG_MASK;
0N/A int[] zval = (z.value.length<intLen+1 ? new int[intLen + 1]
0N/A : z.value);
0N/A long carry = 0;
0N/A for (int i = intLen-1; i >= 0; i--) {
0N/A long product = ylong * (value[i+offset] & LONG_MASK) + carry;
0N/A zval[i+1] = (int)product;
0N/A carry = product >>> 32;
0N/A }
0N/A
0N/A if (carry == 0) {
0N/A z.offset = 1;
0N/A z.intLen = intLen;
0N/A } else {
0N/A z.offset = 0;
0N/A z.intLen = intLen + 1;
0N/A zval[0] = (int)carry;
0N/A }
0N/A z.value = zval;
0N/A }
0N/A
1246N/A /**
0N/A * This method is used for division of an n word dividend by a one word
0N/A * divisor. The quotient is placed into quotient. The one word divisor is
1246N/A * specified by divisor.
1246N/A *
1246N/A * @return the remainder of the division is returned.
0N/A *
0N/A */
1246N/A int divideOneWord(int divisor, MutableBigInteger quotient) {
1246N/A long divisorLong = divisor & LONG_MASK;
0N/A
0N/A // Special case of one word dividend
0N/A if (intLen == 1) {
1246N/A long dividendValue = value[offset] & LONG_MASK;
1246N/A int q = (int) (dividendValue / divisorLong);
1246N/A int r = (int) (dividendValue - q * divisorLong);
1246N/A quotient.value[0] = q;
1246N/A quotient.intLen = (q == 0) ? 0 : 1;
0N/A quotient.offset = 0;
1246N/A return r;
0N/A }
0N/A
0N/A if (quotient.value.length < intLen)
0N/A quotient.value = new int[intLen];
0N/A quotient.offset = 0;
0N/A quotient.intLen = intLen;
0N/A
0N/A // Normalize the divisor
1246N/A int shift = Integer.numberOfLeadingZeros(divisor);
0N/A
0N/A int rem = value[offset];
0N/A long remLong = rem & LONG_MASK;
1246N/A if (remLong < divisorLong) {
0N/A quotient.value[0] = 0;
0N/A } else {
1246N/A quotient.value[0] = (int)(remLong / divisorLong);
1246N/A rem = (int) (remLong - (quotient.value[0] * divisorLong));
0N/A remLong = rem & LONG_MASK;
0N/A }
0N/A
0N/A int xlen = intLen;
0N/A int[] qWord = new int[2];
0N/A while (--xlen > 0) {
0N/A long dividendEstimate = (remLong<<32) |
0N/A (value[offset + intLen - xlen] & LONG_MASK);
0N/A if (dividendEstimate >= 0) {
1246N/A qWord[0] = (int) (dividendEstimate / divisorLong);
1246N/A qWord[1] = (int) (dividendEstimate - qWord[0] * divisorLong);
0N/A } else {
0N/A divWord(qWord, dividendEstimate, divisor);
0N/A }
0N/A quotient.value[intLen - xlen] = qWord[0];
0N/A rem = qWord[1];
0N/A remLong = rem & LONG_MASK;
0N/A }
0N/A
1246N/A quotient.normalize();
0N/A // Unnormalize
0N/A if (shift > 0)
1246N/A return rem % divisor;
0N/A else
1246N/A return rem;
0N/A }
0N/A
0N/A /**
1246N/A * Calculates the quotient of this div b and places the quotient in the
1246N/A * provided MutableBigInteger objects and the remainder object is returned.
0N/A *
0N/A * Uses Algorithm D in Knuth section 4.3.1.
0N/A * Many optimizations to that algorithm have been adapted from the Colin
0N/A * Plumb C library.
1246N/A * It special cases one word divisors for speed. The content of b is not
1246N/A * changed.
0N/A *
0N/A */
1246N/A MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) {
0N/A if (b.intLen == 0)
0N/A throw new ArithmeticException("BigInteger divide by zero");
0N/A
0N/A // Dividend is zero
0N/A if (intLen == 0) {
1246N/A quotient.intLen = quotient.offset;
1246N/A return new MutableBigInteger();
0N/A }
0N/A
0N/A int cmp = compare(b);
0N/A // Dividend less than divisor
0N/A if (cmp < 0) {
0N/A quotient.intLen = quotient.offset = 0;
1246N/A return new MutableBigInteger(this);
0N/A }
0N/A // Dividend equal to divisor
0N/A if (cmp == 0) {
0N/A quotient.value[0] = quotient.intLen = 1;
1246N/A quotient.offset = 0;
1246N/A return new MutableBigInteger();
0N/A }
0N/A
0N/A quotient.clear();
0N/A // Special case one word divisor
0N/A if (b.intLen == 1) {
1246N/A int r = divideOneWord(b.value[b.offset], quotient);
1246N/A if (r == 0)
1246N/A return new MutableBigInteger();
1246N/A return new MutableBigInteger(r);
0N/A }
0N/A
0N/A // Copy divisor value to protect divisor
1246N/A int[] div = Arrays.copyOfRange(b.value, b.offset, b.offset + b.intLen);
1246N/A return divideMagnitude(div, quotient);
1246N/A }
1246N/A
1246N/A /**
1246N/A * Internally used to calculate the quotient of this div v and places the
1246N/A * quotient in the provided MutableBigInteger object and the remainder is
1246N/A * returned.
1246N/A *
1246N/A * @return the remainder of the division will be returned.
1246N/A */
1246N/A long divide(long v, MutableBigInteger quotient) {
1246N/A if (v == 0)
1246N/A throw new ArithmeticException("BigInteger divide by zero");
1246N/A
1246N/A // Dividend is zero
1246N/A if (intLen == 0) {
1246N/A quotient.intLen = quotient.offset = 0;
1246N/A return 0;
1246N/A }
1246N/A if (v < 0)
1246N/A v = -v;
1246N/A
1246N/A int d = (int)(v >>> 32);
1246N/A quotient.clear();
1246N/A // Special case on word divisor
1246N/A if (d == 0)
1246N/A return divideOneWord((int)v, quotient) & LONG_MASK;
1246N/A else {
1246N/A int[] div = new int[]{ d, (int)(v & LONG_MASK) };
1246N/A return divideMagnitude(div, quotient).toLong();
1246N/A }
1246N/A }
1246N/A
1246N/A /**
1246N/A * Divide this MutableBigInteger by the divisor represented by its magnitude
1246N/A * array. The quotient will be placed into the provided quotient object &
1246N/A * the remainder object is returned.
1246N/A */
1246N/A private MutableBigInteger divideMagnitude(int[] divisor,
1246N/A MutableBigInteger quotient) {
0N/A
0N/A // Remainder starts as dividend with space for a leading zero
1246N/A MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]);
1246N/A System.arraycopy(value, offset, rem.value, 1, intLen);
0N/A rem.intLen = intLen;
0N/A rem.offset = 1;
0N/A
0N/A int nlen = rem.intLen;
0N/A
0N/A // Set the quotient size
1246N/A int dlen = divisor.length;
0N/A int limit = nlen - dlen + 1;
0N/A if (quotient.value.length < limit) {
0N/A quotient.value = new int[limit];
0N/A quotient.offset = 0;
0N/A }
0N/A quotient.intLen = limit;
0N/A int[] q = quotient.value;
0N/A
0N/A // D1 normalize the divisor
1246N/A int shift = Integer.numberOfLeadingZeros(divisor[0]);
0N/A if (shift > 0) {
0N/A // First shift will not grow array
1246N/A BigInteger.primitiveLeftShift(divisor, dlen, shift);
0N/A // But this one might
0N/A rem.leftShift(shift);
0N/A }
0N/A
0N/A // Must insert leading 0 in rem if its length did not change
0N/A if (rem.intLen == nlen) {
0N/A rem.offset = 0;
0N/A rem.value[0] = 0;
0N/A rem.intLen++;
0N/A }
0N/A
1246N/A int dh = divisor[0];
0N/A long dhLong = dh & LONG_MASK;
1246N/A int dl = divisor[1];
0N/A int[] qWord = new int[2];
0N/A
0N/A // D2 Initialize j
0N/A for(int j=0; j<limit; j++) {
0N/A // D3 Calculate qhat
0N/A // estimate qhat
0N/A int qhat = 0;
0N/A int qrem = 0;
0N/A boolean skipCorrection = false;
0N/A int nh = rem.value[j+rem.offset];
0N/A int nh2 = nh + 0x80000000;
0N/A int nm = rem.value[j+1+rem.offset];
0N/A
0N/A if (nh == dh) {
0N/A qhat = ~0;
0N/A qrem = nh + nm;
0N/A skipCorrection = qrem + 0x80000000 < nh2;
0N/A } else {
0N/A long nChunk = (((long)nh) << 32) | (nm & LONG_MASK);
0N/A if (nChunk >= 0) {
0N/A qhat = (int) (nChunk / dhLong);
0N/A qrem = (int) (nChunk - (qhat * dhLong));
0N/A } else {
0N/A divWord(qWord, nChunk, dh);
0N/A qhat = qWord[0];
0N/A qrem = qWord[1];
0N/A }
0N/A }
0N/A
0N/A if (qhat == 0)
0N/A continue;
0N/A
0N/A if (!skipCorrection) { // Correct qhat
0N/A long nl = rem.value[j+2+rem.offset] & LONG_MASK;
0N/A long rs = ((qrem & LONG_MASK) << 32) | nl;
0N/A long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
0N/A
0N/A if (unsignedLongCompare(estProduct, rs)) {
0N/A qhat--;
0N/A qrem = (int)((qrem & LONG_MASK) + dhLong);
0N/A if ((qrem & LONG_MASK) >= dhLong) {
1246N/A estProduct -= (dl & LONG_MASK);
0N/A rs = ((qrem & LONG_MASK) << 32) | nl;
0N/A if (unsignedLongCompare(estProduct, rs))
0N/A qhat--;
0N/A }
0N/A }
0N/A }
0N/A
0N/A // D4 Multiply and subtract
0N/A rem.value[j+rem.offset] = 0;
1246N/A int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset);
0N/A
0N/A // D5 Test remainder
0N/A if (borrow + 0x80000000 > nh2) {
0N/A // D6 Add back
1246N/A divadd(divisor, rem.value, j+1+rem.offset);
0N/A qhat--;
0N/A }
0N/A
0N/A // Store the quotient digit
0N/A q[j] = qhat;
0N/A } // D7 loop on j
0N/A
0N/A // D8 Unnormalize
0N/A if (shift > 0)
0N/A rem.rightShift(shift);
0N/A
1246N/A quotient.normalize();
0N/A rem.normalize();
1246N/A return rem;
0N/A }
0N/A
0N/A /**
0N/A * Compare two longs as if they were unsigned.
0N/A * Returns true iff one is bigger than two.
0N/A */
0N/A private boolean unsignedLongCompare(long one, long two) {
0N/A return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);
0N/A }
0N/A
0N/A /**
0N/A * This method divides a long quantity by an int to estimate
0N/A * qhat for two multi precision numbers. It is used when
0N/A * the signed value of n is less than zero.
0N/A */
0N/A private void divWord(int[] result, long n, int d) {
0N/A long dLong = d & LONG_MASK;
0N/A
0N/A if (dLong == 1) {
0N/A result[0] = (int)n;
0N/A result[1] = 0;
0N/A return;
0N/A }
0N/A
0N/A // Approximate the quotient and remainder
0N/A long q = (n >>> 1) / (dLong >>> 1);
0N/A long r = n - q*dLong;
0N/A
0N/A // Correct the approximation
0N/A while (r < 0) {
0N/A r += dLong;
0N/A q--;
0N/A }
0N/A while (r >= dLong) {
0N/A r -= dLong;
0N/A q++;
0N/A }
0N/A
0N/A // n - q*dlong == r && 0 <= r <dLong, hence we're done.
0N/A result[0] = (int)q;
0N/A result[1] = (int)r;
0N/A }
0N/A
0N/A /**
0N/A * Calculate GCD of this and b. This and b are changed by the computation.
0N/A */
0N/A MutableBigInteger hybridGCD(MutableBigInteger b) {
0N/A // Use Euclid's algorithm until the numbers are approximately the
0N/A // same length, then use the binary GCD algorithm to find the GCD.
0N/A MutableBigInteger a = this;
1246N/A MutableBigInteger q = new MutableBigInteger();
0N/A
0N/A while (b.intLen != 0) {
0N/A if (Math.abs(a.intLen - b.intLen) < 2)
0N/A return a.binaryGCD(b);
0N/A
1246N/A MutableBigInteger r = a.divide(b, q);
1246N/A a = b;
1246N/A b = r;
0N/A }
0N/A return a;
0N/A }
0N/A
0N/A /**
0N/A * Calculate GCD of this and v.
0N/A * Assumes that this and v are not zero.
0N/A */
0N/A private MutableBigInteger binaryGCD(MutableBigInteger v) {
0N/A // Algorithm B from Knuth section 4.5.2
0N/A MutableBigInteger u = this;
0N/A MutableBigInteger r = new MutableBigInteger();
0N/A
0N/A // step B1
0N/A int s1 = u.getLowestSetBit();
0N/A int s2 = v.getLowestSetBit();
0N/A int k = (s1 < s2) ? s1 : s2;
0N/A if (k != 0) {
0N/A u.rightShift(k);
0N/A v.rightShift(k);
0N/A }
0N/A
0N/A // step B2
0N/A boolean uOdd = (k==s1);
0N/A MutableBigInteger t = uOdd ? v: u;
0N/A int tsign = uOdd ? -1 : 1;
0N/A
0N/A int lb;
0N/A while ((lb = t.getLowestSetBit()) >= 0) {
0N/A // steps B3 and B4
0N/A t.rightShift(lb);
0N/A // step B5
0N/A if (tsign > 0)
0N/A u = t;
0N/A else
0N/A v = t;
0N/A
0N/A // Special case one word numbers
0N/A if (u.intLen < 2 && v.intLen < 2) {
0N/A int x = u.value[u.offset];
0N/A int y = v.value[v.offset];
0N/A x = binaryGcd(x, y);
0N/A r.value[0] = x;
0N/A r.intLen = 1;
0N/A r.offset = 0;
0N/A if (k > 0)
0N/A r.leftShift(k);
0N/A return r;
0N/A }
0N/A
0N/A // step B6
0N/A if ((tsign = u.difference(v)) == 0)
0N/A break;
0N/A t = (tsign >= 0) ? u : v;
0N/A }
0N/A
0N/A if (k > 0)
0N/A u.leftShift(k);
0N/A return u;
0N/A }
0N/A
0N/A /**
0N/A * Calculate GCD of a and b interpreted as unsigned integers.
0N/A */
0N/A static int binaryGcd(int a, int b) {
0N/A if (b==0)
0N/A return a;
0N/A if (a==0)
0N/A return b;
0N/A
1246N/A // Right shift a & b till their last bits equal to 1.
1246N/A int aZeros = Integer.numberOfTrailingZeros(a);
1246N/A int bZeros = Integer.numberOfTrailingZeros(b);
1246N/A a >>>= aZeros;
1246N/A b >>>= bZeros;
0N/A
0N/A int t = (aZeros < bZeros ? aZeros : bZeros);
0N/A
0N/A while (a != b) {
0N/A if ((a+0x80000000) > (b+0x80000000)) { // a > b as unsigned
0N/A a -= b;
1246N/A a >>>= Integer.numberOfTrailingZeros(a);
0N/A } else {
0N/A b -= a;
1246N/A b >>>= Integer.numberOfTrailingZeros(b);
0N/A }
0N/A }
0N/A return a<<t;
0N/A }
0N/A
0N/A /**
0N/A * Returns the modInverse of this mod p. This and p are not affected by
0N/A * the operation.
0N/A */
0N/A MutableBigInteger mutableModInverse(MutableBigInteger p) {
0N/A // Modulus is odd, use Schroeppel's algorithm
0N/A if (p.isOdd())
0N/A return modInverse(p);
0N/A
0N/A // Base and modulus are even, throw exception
0N/A if (isEven())
0N/A throw new ArithmeticException("BigInteger not invertible.");
0N/A
0N/A // Get even part of modulus expressed as a power of 2
0N/A int powersOf2 = p.getLowestSetBit();
0N/A
0N/A // Construct odd part of modulus
0N/A MutableBigInteger oddMod = new MutableBigInteger(p);
0N/A oddMod.rightShift(powersOf2);
0N/A
0N/A if (oddMod.isOne())
0N/A return modInverseMP2(powersOf2);
0N/A
0N/A // Calculate 1/a mod oddMod
0N/A MutableBigInteger oddPart = modInverse(oddMod);
0N/A
0N/A // Calculate 1/a mod evenMod
0N/A MutableBigInteger evenPart = modInverseMP2(powersOf2);
0N/A
0N/A // Combine the results using Chinese Remainder Theorem
0N/A MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2);
0N/A MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2);
0N/A
0N/A MutableBigInteger temp1 = new MutableBigInteger();
0N/A MutableBigInteger temp2 = new MutableBigInteger();
0N/A MutableBigInteger result = new MutableBigInteger();
0N/A
0N/A oddPart.leftShift(powersOf2);
0N/A oddPart.multiply(y1, result);
0N/A
0N/A evenPart.multiply(oddMod, temp1);
0N/A temp1.multiply(y2, temp2);
0N/A
0N/A result.add(temp2);
1246N/A return result.divide(p, temp1);
0N/A }
0N/A
0N/A /*
0N/A * Calculate the multiplicative inverse of this mod 2^k.
0N/A */
0N/A MutableBigInteger modInverseMP2(int k) {
0N/A if (isEven())
0N/A throw new ArithmeticException("Non-invertible. (GCD != 1)");
0N/A
0N/A if (k > 64)
0N/A return euclidModInverse(k);
0N/A
0N/A int t = inverseMod32(value[offset+intLen-1]);
0N/A
0N/A if (k < 33) {
0N/A t = (k == 32 ? t : t & ((1 << k) - 1));
0N/A return new MutableBigInteger(t);
0N/A }
0N/A
0N/A long pLong = (value[offset+intLen-1] & LONG_MASK);
0N/A if (intLen > 1)
0N/A pLong |= ((long)value[offset+intLen-2] << 32);
0N/A long tLong = t & LONG_MASK;
0N/A tLong = tLong * (2 - pLong * tLong); // 1 more Newton iter step
0N/A tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1));
0N/A
0N/A MutableBigInteger result = new MutableBigInteger(new int[2]);
0N/A result.value[0] = (int)(tLong >>> 32);
0N/A result.value[1] = (int)tLong;
0N/A result.intLen = 2;
0N/A result.normalize();
0N/A return result;
0N/A }
0N/A
0N/A /*
0N/A * Returns the multiplicative inverse of val mod 2^32. Assumes val is odd.
0N/A */
0N/A static int inverseMod32(int val) {
0N/A // Newton's iteration!
0N/A int t = val;
0N/A t *= 2 - val*t;
0N/A t *= 2 - val*t;
0N/A t *= 2 - val*t;
0N/A t *= 2 - val*t;
0N/A return t;
0N/A }
0N/A
0N/A /*
0N/A * Calculate the multiplicative inverse of 2^k mod mod, where mod is odd.
0N/A */
0N/A static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) {
0N/A // Copy the mod to protect original
0N/A return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k);
0N/A }
0N/A
0N/A /**
0N/A * Calculate the multiplicative inverse of this mod mod, where mod is odd.
0N/A * This and mod are not changed by the calculation.
0N/A *
0N/A * This method implements an algorithm due to Richard Schroeppel, that uses
0N/A * the same intermediate representation as Montgomery Reduction
0N/A * ("Montgomery Form"). The algorithm is described in an unpublished
0N/A * manuscript entitled "Fast Modular Reciprocals."
0N/A */
0N/A private MutableBigInteger modInverse(MutableBigInteger mod) {
0N/A MutableBigInteger p = new MutableBigInteger(mod);
0N/A MutableBigInteger f = new MutableBigInteger(this);
0N/A MutableBigInteger g = new MutableBigInteger(p);
0N/A SignedMutableBigInteger c = new SignedMutableBigInteger(1);
0N/A SignedMutableBigInteger d = new SignedMutableBigInteger();
0N/A MutableBigInteger temp = null;
0N/A SignedMutableBigInteger sTemp = null;
0N/A
0N/A int k = 0;
0N/A // Right shift f k times until odd, left shift d k times
0N/A if (f.isEven()) {
0N/A int trailingZeros = f.getLowestSetBit();
0N/A f.rightShift(trailingZeros);
0N/A d.leftShift(trailingZeros);
0N/A k = trailingZeros;
0N/A }
0N/A
0N/A // The Almost Inverse Algorithm
0N/A while(!f.isOne()) {
0N/A // If gcd(f, g) != 1, number is not invertible modulo mod
0N/A if (f.isZero())
0N/A throw new ArithmeticException("BigInteger not invertible.");
0N/A
0N/A // If f < g exchange f, g and c, d
0N/A if (f.compare(g) < 0) {
0N/A temp = f; f = g; g = temp;
0N/A sTemp = d; d = c; c = sTemp;
0N/A }
0N/A
0N/A // If f == g (mod 4)
0N/A if (((f.value[f.offset + f.intLen - 1] ^
0N/A g.value[g.offset + g.intLen - 1]) & 3) == 0) {
0N/A f.subtract(g);
0N/A c.signedSubtract(d);
0N/A } else { // If f != g (mod 4)
0N/A f.add(g);
0N/A c.signedAdd(d);
0N/A }
0N/A
0N/A // Right shift f k times until odd, left shift d k times
0N/A int trailingZeros = f.getLowestSetBit();
0N/A f.rightShift(trailingZeros);
0N/A d.leftShift(trailingZeros);
0N/A k += trailingZeros;
0N/A }
0N/A
0N/A while (c.sign < 0)
0N/A c.signedAdd(p);
0N/A
0N/A return fixup(c, p, k);
0N/A }
0N/A
0N/A /*
0N/A * The Fixup Algorithm
0N/A * Calculates X such that X = C * 2^(-k) (mod P)
0N/A * Assumes C<P and P is odd.
0N/A */
0N/A static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p,
0N/A int k) {
0N/A MutableBigInteger temp = new MutableBigInteger();
0N/A // Set r to the multiplicative inverse of p mod 2^32
0N/A int r = -inverseMod32(p.value[p.offset+p.intLen-1]);
0N/A
0N/A for(int i=0, numWords = k >> 5; i<numWords; i++) {
0N/A // V = R * c (mod 2^j)
0N/A int v = r * c.value[c.offset + c.intLen-1];
0N/A // c = c + (v * p)
0N/A p.mul(v, temp);
0N/A c.add(temp);
0N/A // c = c / 2^j
0N/A c.intLen--;
0N/A }
0N/A int numBits = k & 0x1f;
0N/A if (numBits != 0) {
0N/A // V = R * c (mod 2^j)
0N/A int v = r * c.value[c.offset + c.intLen-1];
0N/A v &= ((1<<numBits) - 1);
0N/A // c = c + (v * p)
0N/A p.mul(v, temp);
0N/A c.add(temp);
0N/A // c = c / 2^j
0N/A c.rightShift(numBits);
0N/A }
0N/A
0N/A // In theory, c may be greater than p at this point (Very rare!)
0N/A while (c.compare(p) >= 0)
0N/A c.subtract(p);
0N/A
0N/A return c;
0N/A }
0N/A
0N/A /**
0N/A * Uses the extended Euclidean algorithm to compute the modInverse of base
0N/A * mod a modulus that is a power of 2. The modulus is 2^k.
0N/A */
0N/A MutableBigInteger euclidModInverse(int k) {
0N/A MutableBigInteger b = new MutableBigInteger(1);
0N/A b.leftShift(k);
0N/A MutableBigInteger mod = new MutableBigInteger(b);
0N/A
0N/A MutableBigInteger a = new MutableBigInteger(this);
0N/A MutableBigInteger q = new MutableBigInteger();
1246N/A MutableBigInteger r = b.divide(a, q);
0N/A
1246N/A MutableBigInteger swapper = b;
1246N/A // swap b & r
1246N/A b = r;
1246N/A r = swapper;
0N/A
0N/A MutableBigInteger t1 = new MutableBigInteger(q);
0N/A MutableBigInteger t0 = new MutableBigInteger(1);
0N/A MutableBigInteger temp = new MutableBigInteger();
0N/A
0N/A while (!b.isOne()) {
1246N/A r = a.divide(b, q);
0N/A
0N/A if (r.intLen == 0)
0N/A throw new ArithmeticException("BigInteger not invertible.");
0N/A
1246N/A swapper = r;
1246N/A a = swapper;
0N/A
0N/A if (q.intLen == 1)
0N/A t1.mul(q.value[q.offset], temp);
0N/A else
0N/A q.multiply(t1, temp);
1246N/A swapper = q;
1246N/A q = temp;
1246N/A temp = swapper;
0N/A t0.add(q);
0N/A
0N/A if (a.isOne())
0N/A return t0;
0N/A
1246N/A r = b.divide(a, q);
0N/A
0N/A if (r.intLen == 0)
0N/A throw new ArithmeticException("BigInteger not invertible.");
0N/A
1246N/A swapper = b;
1246N/A b = r;
0N/A
0N/A if (q.intLen == 1)
0N/A t0.mul(q.value[q.offset], temp);
0N/A else
0N/A q.multiply(t0, temp);
0N/A swapper = q; q = temp; temp = swapper;
0N/A
0N/A t1.add(q);
0N/A }
0N/A mod.subtract(t1);
0N/A return mod;
0N/A }
0N/A
0N/A}