jdk/src/share/classes/java/math/MutableBigInteger.java
changeset 2922 dd6d609861f0
parent 2 90ce3da70b43
child 5506 202f599c92aa
equal deleted inserted replaced
2921:d9d491a5a169 2922:dd6d609861f0
    39  * @see     BigInteger
    39  * @see     BigInteger
    40  * @author  Michael McCloskey
    40  * @author  Michael McCloskey
    41  * @since   1.3
    41  * @since   1.3
    42  */
    42  */
    43 
    43 
       
    44 import java.util.Arrays;
       
    45 
       
    46 import static java.math.BigInteger.LONG_MASK;
       
    47 import static java.math.BigDecimal.INFLATED;
       
    48 
    44 class MutableBigInteger {
    49 class MutableBigInteger {
    45     /**
    50     /**
    46      * Holds the magnitude of this MutableBigInteger in big endian order.
    51      * Holds the magnitude of this MutableBigInteger in big endian order.
    47      * The magnitude may start at an offset into the value array, and it may
    52      * The magnitude may start at an offset into the value array, and it may
    48      * end before the length of the value array.
    53      * end before the length of the value array.
    60      * The offset into the value array where the magnitude of this
    65      * The offset into the value array where the magnitude of this
    61      * MutableBigInteger begins.
    66      * MutableBigInteger begins.
    62      */
    67      */
    63     int offset = 0;
    68     int offset = 0;
    64 
    69 
    65     /**
    70     // Constants
    66      * This mask is used to obtain the value of an int as if it were unsigned.
    71     /**
    67      */
    72      * MutableBigInteger with one element value array with the value 1. Used by
    68     private final static long LONG_MASK = 0xffffffffL;
    73      * BigDecimal divideAndRound to increment the quotient. Use this constant
       
    74      * only when the method is not going to modify this object.
       
    75      */
       
    76     static final MutableBigInteger ONE = new MutableBigInteger(1);
    69 
    77 
    70     // Constructors
    78     // Constructors
    71 
    79 
    72     /**
    80     /**
    73      * The default constructor. An empty MutableBigInteger is created with
    81      * The default constructor. An empty MutableBigInteger is created with
    88         value[0] = val;
    96         value[0] = val;
    89     }
    97     }
    90 
    98 
    91     /**
    99     /**
    92      * Construct a new MutableBigInteger with the specified value array
   100      * Construct a new MutableBigInteger with the specified value array
    93      * up to the specified length.
       
    94      */
       
    95     MutableBigInteger(int[] val, int len) {
       
    96         value = val;
       
    97         intLen = len;
       
    98     }
       
    99 
       
   100     /**
       
   101      * Construct a new MutableBigInteger with the specified value array
       
   102      * up to the length of the array supplied.
   101      * up to the length of the array supplied.
   103      */
   102      */
   104     MutableBigInteger(int[] val) {
   103     MutableBigInteger(int[] val) {
   105         value = val;
   104         value = val;
   106         intLen = val.length;
   105         intLen = val.length;
   109     /**
   108     /**
   110      * Construct a new MutableBigInteger with a magnitude equal to the
   109      * Construct a new MutableBigInteger with a magnitude equal to the
   111      * specified BigInteger.
   110      * specified BigInteger.
   112      */
   111      */
   113     MutableBigInteger(BigInteger b) {
   112     MutableBigInteger(BigInteger b) {
   114         value = b.mag.clone();
   113         intLen = b.mag.length;
   115         intLen = value.length;
   114         value = Arrays.copyOf(b.mag, intLen);
   116     }
   115     }
   117 
   116 
   118     /**
   117     /**
   119      * Construct a new MutableBigInteger with a magnitude equal to the
   118      * Construct a new MutableBigInteger with a magnitude equal to the
   120      * specified MutableBigInteger.
   119      * specified MutableBigInteger.
   121      */
   120      */
   122     MutableBigInteger(MutableBigInteger val) {
   121     MutableBigInteger(MutableBigInteger val) {
   123         intLen = val.intLen;
   122         intLen = val.intLen;
   124         value = new int[intLen];
   123         value = Arrays.copyOfRange(val.value, val.offset, val.offset + intLen);
   125 
   124     }
   126         for(int i=0; i<intLen; i++)
   125 
   127             value[i] = val.value[val.offset+i];
   126     /**
       
   127      * Internal helper method to return the magnitude array. The caller is not
       
   128      * supposed to modify the returned array.
       
   129      */
       
   130     private int[] getMagnitudeArray() {
       
   131         if (offset > 0 || value.length != intLen)
       
   132             return Arrays.copyOfRange(value, offset, offset + intLen);
       
   133         return value;
       
   134     }
       
   135 
       
   136     /**
       
   137      * Convert this MutableBigInteger to a long value. The caller has to make
       
   138      * sure this MutableBigInteger can be fit into long.
       
   139      */
       
   140     private long toLong() {
       
   141         assert (intLen <= 2) : "this MutableBigInteger exceeds the range of long";
       
   142         if (intLen == 0)
       
   143             return 0;
       
   144         long d = value[offset] & LONG_MASK;
       
   145         return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d;
       
   146     }
       
   147 
       
   148     /**
       
   149      * Convert this MutableBigInteger to a BigInteger object.
       
   150      */
       
   151     BigInteger toBigInteger(int sign) {
       
   152         if (intLen == 0 || sign == 0)
       
   153             return BigInteger.ZERO;
       
   154         return new BigInteger(getMagnitudeArray(), sign);
       
   155     }
       
   156 
       
   157     /**
       
   158      * Convert this MutableBigInteger to BigDecimal object with the specified sign
       
   159      * and scale.
       
   160      */
       
   161     BigDecimal toBigDecimal(int sign, int scale) {
       
   162         if (intLen == 0 || sign == 0)
       
   163             return BigDecimal.valueOf(0, scale);
       
   164         int[] mag = getMagnitudeArray();
       
   165         int len = mag.length;
       
   166         int d = mag[0];
       
   167         // If this MutableBigInteger can't be fit into long, we need to
       
   168         // make a BigInteger object for the resultant BigDecimal object.
       
   169         if (len > 2 || (d < 0 && len == 2))
       
   170             return new BigDecimal(new BigInteger(mag, sign), INFLATED, scale, 0);
       
   171         long v = (len == 2) ?
       
   172             ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) :
       
   173             d & LONG_MASK;
       
   174         return new BigDecimal(null, sign == -1 ? -v : v, scale, 0);
   128     }
   175     }
   129 
   176 
   130     /**
   177     /**
   131      * Clear out a MutableBigInteger for reuse.
   178      * Clear out a MutableBigInteger for reuse.
   132      */
   179      */
   144     }
   191     }
   145 
   192 
   146     /**
   193     /**
   147      * Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1
   194      * Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1
   148      * as this MutableBigInteger is numerically less than, equal to, or
   195      * as this MutableBigInteger is numerically less than, equal to, or
   149      * greater than {@code b}.
   196      * greater than <tt>b</tt>.
   150      */
   197      */
   151     final int compare(MutableBigInteger b) {
   198     final int compare(MutableBigInteger b) {
   152         if (intLen < b.intLen)
   199         int blen = b.intLen;
       
   200         if (intLen < blen)
   153             return -1;
   201             return -1;
   154         if (intLen > b.intLen)
   202         if (intLen > blen)
   155             return 1;
   203            return 1;
   156 
   204 
   157         for (int i=0; i<intLen; i++) {
   205         // Add Integer.MIN_VALUE to make the comparison act as unsigned integer
   158             int b1 = value[offset+i]     + 0x80000000;
   206         // comparison.
   159             int b2 = b.value[b.offset+i] + 0x80000000;
   207         int[] bval = b.value;
       
   208         for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) {
       
   209             int b1 = value[i] + 0x80000000;
       
   210             int b2 = bval[j]  + 0x80000000;
   160             if (b1 < b2)
   211             if (b1 < b2)
   161                 return -1;
   212                 return -1;
   162             if (b1 > b2)
   213             if (b1 > b2)
   163                 return 1;
   214                 return 1;
   164         }
   215         }
   165         return 0;
   216         return 0;
       
   217     }
       
   218 
       
   219     /**
       
   220      * Compare this against half of a MutableBigInteger object (Needed for
       
   221      * remainder tests).
       
   222      * Assumes no leading unnecessary zeros, which holds for results
       
   223      * from divide().
       
   224      */
       
   225     final int compareHalf(MutableBigInteger b) {
       
   226         int blen = b.intLen;
       
   227         int len = intLen;
       
   228         if (len <= 0)
       
   229             return blen <=0 ? 0 : -1;
       
   230         if (len > blen)
       
   231             return 1;
       
   232         if (len < blen - 1)
       
   233             return -1;
       
   234         int[] bval = b.value;
       
   235         int bstart = 0;
       
   236         int carry = 0;
       
   237         // Only 2 cases left:len == blen or len == blen - 1
       
   238         if (len != blen) { // len == blen - 1
       
   239             if (bval[bstart] == 1) {
       
   240                 ++bstart;
       
   241                 carry = 0x80000000;
       
   242             } else
       
   243                 return -1;
       
   244         }
       
   245         // compare values with right-shifted values of b,
       
   246         // carrying shifted-out bits across words
       
   247         int[] val = value;
       
   248         for (int i = offset, j = bstart; i < len + offset;) {
       
   249             int bv = bval[j++];
       
   250             long hb = ((bv >>> 1) + carry) & LONG_MASK;
       
   251             long v = val[i++] & LONG_MASK;
       
   252             if (v != hb)
       
   253                 return v < hb ? -1 : 1;
       
   254             carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0
       
   255         }
       
   256         return carry == 0? 0 : -1;
   166     }
   257     }
   167 
   258 
   168     /**
   259     /**
   169      * Return the index of the lowest set bit in this MutableBigInteger. If the
   260      * Return the index of the lowest set bit in this MutableBigInteger. If the
   170      * magnitude of this MutableBigInteger is zero, -1 is returned.
   261      * magnitude of this MutableBigInteger is zero, -1 is returned.
   176         for (j=intLen-1; (j>0) && (value[j+offset]==0); j--)
   267         for (j=intLen-1; (j>0) && (value[j+offset]==0); j--)
   177             ;
   268             ;
   178         b = value[j+offset];
   269         b = value[j+offset];
   179         if (b==0)
   270         if (b==0)
   180             return -1;
   271             return -1;
   181         return ((intLen-1-j)<<5) + BigInteger.trailingZeroCnt(b);
   272         return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b);
   182     }
   273     }
   183 
   274 
   184     /**
   275     /**
   185      * Return the int in use in this MutableBigInteger at the specified
   276      * Return the int in use in this MutableBigInteger at the specified
   186      * index. This method is not used because it is not inlined on all
   277      * index. This method is not used because it is not inlined on all
   268 
   359 
   269     /**
   360     /**
   270      * Sets this MutableBigInteger's value array to a copy of the specified
   361      * Sets this MutableBigInteger's value array to a copy of the specified
   271      * array. The intLen is set to the length of the new array.
   362      * array. The intLen is set to the length of the new array.
   272      */
   363      */
   273     void copyValue(MutableBigInteger val) {
   364     void copyValue(MutableBigInteger src) {
   274         int len = val.intLen;
   365         int len = src.intLen;
   275         if (value.length < len)
   366         if (value.length < len)
   276             value = new int[len];
   367             value = new int[len];
   277 
   368         System.arraycopy(src.value, src.offset, value, 0, len);
   278         for(int i=0; i<len; i++)
       
   279             value[i] = val.value[val.offset+i];
       
   280         intLen = len;
   369         intLen = len;
   281         offset = 0;
   370         offset = 0;
   282     }
   371     }
   283 
   372 
   284     /**
   373     /**
   287      */
   376      */
   288     void copyValue(int[] val) {
   377     void copyValue(int[] val) {
   289         int len = val.length;
   378         int len = val.length;
   290         if (value.length < len)
   379         if (value.length < len)
   291             value = new int[len];
   380             value = new int[len];
   292         for(int i=0; i<len; i++)
   381         System.arraycopy(val, 0, value, 0, len);
   293             value[i] = val[i];
       
   294         intLen = len;
   382         intLen = len;
   295         offset = 0;
   383         offset = 0;
   296     }
   384     }
   297 
   385 
   298     /**
   386     /**
   318 
   406 
   319     /**
   407     /**
   320      * Returns true iff this MutableBigInteger is odd.
   408      * Returns true iff this MutableBigInteger is odd.
   321      */
   409      */
   322     boolean isOdd() {
   410     boolean isOdd() {
   323         return ((value[offset + intLen - 1] & 1) == 1);
   411         return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1);
   324     }
   412     }
   325 
   413 
   326     /**
   414     /**
   327      * Returns true iff this MutableBigInteger is in normal form. A
   415      * Returns true iff this MutableBigInteger is in normal form. A
   328      * MutableBigInteger is in normal form if it has no leading zeros
   416      * MutableBigInteger is in normal form if it has no leading zeros
   338 
   426 
   339     /**
   427     /**
   340      * Returns a String representation of this MutableBigInteger in radix 10.
   428      * Returns a String representation of this MutableBigInteger in radix 10.
   341      */
   429      */
   342     public String toString() {
   430     public String toString() {
   343         BigInteger b = new BigInteger(this, 1);
   431         BigInteger b = toBigInteger(1);
   344         return b.toString();
   432         return b.toString();
   345     }
   433     }
   346 
   434 
   347     /**
   435     /**
   348      * Right shift this MutableBigInteger n bits. The MutableBigInteger is left
   436      * Right shift this MutableBigInteger n bits. The MutableBigInteger is left
   354         int nInts = n >>> 5;
   442         int nInts = n >>> 5;
   355         int nBits = n & 0x1F;
   443         int nBits = n & 0x1F;
   356         this.intLen -= nInts;
   444         this.intLen -= nInts;
   357         if (nBits == 0)
   445         if (nBits == 0)
   358             return;
   446             return;
   359         int bitsInHighWord = BigInteger.bitLen(value[offset]);
   447         int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
   360         if (nBits >= bitsInHighWord) {
   448         if (nBits >= bitsInHighWord) {
   361             this.primitiveLeftShift(32 - nBits);
   449             this.primitiveLeftShift(32 - nBits);
   362             this.intLen--;
   450             this.intLen--;
   363         } else {
   451         } else {
   364             primitiveRightShift(nBits);
   452             primitiveRightShift(nBits);
   377          */
   465          */
   378         if (intLen == 0)
   466         if (intLen == 0)
   379            return;
   467            return;
   380         int nInts = n >>> 5;
   468         int nInts = n >>> 5;
   381         int nBits = n&0x1F;
   469         int nBits = n&0x1F;
   382         int bitsInHighWord = BigInteger.bitLen(value[offset]);
   470         int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
   383 
   471 
   384         // If shift can be done without moving words, do so
   472         // If shift can be done without moving words, do so
   385         if (n <= (32-bitsInHighWord)) {
   473         if (n <= (32-bitsInHighWord)) {
   386             primitiveLeftShift(nBits);
   474             primitiveLeftShift(nBits);
   387             return;
   475             return;
   497         int y = addend.intLen;
   585         int y = addend.intLen;
   498         int resultLen = (intLen > addend.intLen ? intLen : addend.intLen);
   586         int resultLen = (intLen > addend.intLen ? intLen : addend.intLen);
   499         int[] result = (value.length < resultLen ? new int[resultLen] : value);
   587         int[] result = (value.length < resultLen ? new int[resultLen] : value);
   500 
   588 
   501         int rstart = result.length-1;
   589         int rstart = result.length-1;
   502         long sum = 0;
   590         long sum;
       
   591         long carry = 0;
   503 
   592 
   504         // Add common parts of both numbers
   593         // Add common parts of both numbers
   505         while(x>0 && y>0) {
   594         while(x>0 && y>0) {
   506             x--; y--;
   595             x--; y--;
   507             sum = (value[x+offset] & LONG_MASK) +
   596             sum = (value[x+offset] & LONG_MASK) +
   508                 (addend.value[y+addend.offset] & LONG_MASK) + (sum >>> 32);
   597                 (addend.value[y+addend.offset] & LONG_MASK) + carry;
   509             result[rstart--] = (int)sum;
   598             result[rstart--] = (int)sum;
       
   599             carry = sum >>> 32;
   510         }
   600         }
   511 
   601 
   512         // Add remainder of the longer number
   602         // Add remainder of the longer number
   513         while(x>0) {
   603         while(x>0) {
   514             x--;
   604             x--;
   515             sum = (value[x+offset] & LONG_MASK) + (sum >>> 32);
   605             if (carry == 0 && result == value && rstart == (x + offset))
       
   606                 return;
       
   607             sum = (value[x+offset] & LONG_MASK) + carry;
   516             result[rstart--] = (int)sum;
   608             result[rstart--] = (int)sum;
       
   609             carry = sum >>> 32;
   517         }
   610         }
   518         while(y>0) {
   611         while(y>0) {
   519             y--;
   612             y--;
   520             sum = (addend.value[y+addend.offset] & LONG_MASK) + (sum >>> 32);
   613             sum = (addend.value[y+addend.offset] & LONG_MASK) + carry;
   521             result[rstart--] = (int)sum;
   614             result[rstart--] = (int)sum;
   522         }
   615             carry = sum >>> 32;
   523 
   616         }
   524         if ((sum >>> 32) > 0) { // Result must grow in length
   617 
       
   618         if (carry > 0) { // Result must grow in length
   525             resultLen++;
   619             resultLen++;
   526             if (result.length < resultLen) {
   620             if (result.length < resultLen) {
   527                 int temp[] = new int[resultLen];
   621                 int temp[] = new int[resultLen];
   528                 for (int i=resultLen-1; i>0; i--)
   622                 // Result one word longer from carry-out; copy low-order
   529                     temp[i] = result[i-1];
   623                 // bits into new result.
       
   624                 System.arraycopy(result, 0, temp, 1, result.length);
   530                 temp[0] = 1;
   625                 temp[0] = 1;
   531                 result = temp;
   626                 result = temp;
   532             } else {
   627             } else {
   533                 result[rstart--] = 1;
   628                 result[rstart--] = 1;
   534             }
   629             }
   706             zval[0] = (int)carry;
   801             zval[0] = (int)carry;
   707         }
   802         }
   708         z.value = zval;
   803         z.value = zval;
   709     }
   804     }
   710 
   805 
   711     /**
   806      /**
   712      * This method is used for division of an n word dividend by a one word
   807      * This method is used for division of an n word dividend by a one word
   713      * divisor. The quotient is placed into quotient. The one word divisor is
   808      * divisor. The quotient is placed into quotient. The one word divisor is
   714      * specified by divisor. The value of this MutableBigInteger is the
   809      * specified by divisor.
   715      * dividend at invocation but is replaced by the remainder.
       
   716      *
   810      *
   717      * NOTE: The value of this MutableBigInteger is modified by this method.
   811      * @return the remainder of the division is returned.
   718      */
   812      *
   719     void divideOneWord(int divisor, MutableBigInteger quotient) {
   813      */
   720         long divLong = divisor & LONG_MASK;
   814     int divideOneWord(int divisor, MutableBigInteger quotient) {
       
   815         long divisorLong = divisor & LONG_MASK;
   721 
   816 
   722         // Special case of one word dividend
   817         // Special case of one word dividend
   723         if (intLen == 1) {
   818         if (intLen == 1) {
   724             long remValue = value[offset] & LONG_MASK;
   819             long dividendValue = value[offset] & LONG_MASK;
   725             quotient.value[0] = (int) (remValue / divLong);
   820             int q = (int) (dividendValue / divisorLong);
   726             quotient.intLen = (quotient.value[0] == 0) ? 0 : 1;
   821             int r = (int) (dividendValue - q * divisorLong);
       
   822             quotient.value[0] = q;
       
   823             quotient.intLen = (q == 0) ? 0 : 1;
   727             quotient.offset = 0;
   824             quotient.offset = 0;
   728 
   825             return r;
   729             value[0] = (int) (remValue - (quotient.value[0] * divLong));
       
   730             offset = 0;
       
   731             intLen = (value[0] == 0) ? 0 : 1;
       
   732 
       
   733             return;
       
   734         }
   826         }
   735 
   827 
   736         if (quotient.value.length < intLen)
   828         if (quotient.value.length < intLen)
   737             quotient.value = new int[intLen];
   829             quotient.value = new int[intLen];
   738         quotient.offset = 0;
   830         quotient.offset = 0;
   739         quotient.intLen = intLen;
   831         quotient.intLen = intLen;
   740 
   832 
   741         // Normalize the divisor
   833         // Normalize the divisor
   742         int shift = 32 - BigInteger.bitLen(divisor);
   834         int shift = Integer.numberOfLeadingZeros(divisor);
   743 
   835 
   744         int rem = value[offset];
   836         int rem = value[offset];
   745         long remLong = rem & LONG_MASK;
   837         long remLong = rem & LONG_MASK;
   746         if (remLong < divLong) {
   838         if (remLong < divisorLong) {
   747             quotient.value[0] = 0;
   839             quotient.value[0] = 0;
   748         } else {
   840         } else {
   749             quotient.value[0] = (int)(remLong/divLong);
   841             quotient.value[0] = (int)(remLong / divisorLong);
   750             rem = (int) (remLong - (quotient.value[0] * divLong));
   842             rem = (int) (remLong - (quotient.value[0] * divisorLong));
   751             remLong = rem & LONG_MASK;
   843             remLong = rem & LONG_MASK;
   752         }
   844         }
   753 
   845 
   754         int xlen = intLen;
   846         int xlen = intLen;
   755         int[] qWord = new int[2];
   847         int[] qWord = new int[2];
   756         while (--xlen > 0) {
   848         while (--xlen > 0) {
   757             long dividendEstimate = (remLong<<32) |
   849             long dividendEstimate = (remLong<<32) |
   758                 (value[offset + intLen - xlen] & LONG_MASK);
   850                 (value[offset + intLen - xlen] & LONG_MASK);
   759             if (dividendEstimate >= 0) {
   851             if (dividendEstimate >= 0) {
   760                 qWord[0] = (int) (dividendEstimate/divLong);
   852                 qWord[0] = (int) (dividendEstimate / divisorLong);
   761                 qWord[1] = (int) (dividendEstimate - (qWord[0] * divLong));
   853                 qWord[1] = (int) (dividendEstimate - qWord[0] * divisorLong);
   762             } else {
   854             } else {
   763                 divWord(qWord, dividendEstimate, divisor);
   855                 divWord(qWord, dividendEstimate, divisor);
   764             }
   856             }
   765             quotient.value[intLen - xlen] = qWord[0];
   857             quotient.value[intLen - xlen] = qWord[0];
   766             rem = qWord[1];
   858             rem = qWord[1];
   767             remLong = rem & LONG_MASK;
   859             remLong = rem & LONG_MASK;
   768         }
   860         }
   769 
   861 
       
   862         quotient.normalize();
   770         // Unnormalize
   863         // Unnormalize
   771         if (shift > 0)
   864         if (shift > 0)
   772             value[0] = rem %= divisor;
   865             return rem % divisor;
   773         else
   866         else
   774             value[0] = rem;
   867             return rem;
   775         intLen = (value[0] == 0) ? 0 : 1;
   868     }
   776 
   869 
   777         quotient.normalize();
   870     /**
   778     }
   871      * Calculates the quotient of this div b and places the quotient in the
   779 
   872      * provided MutableBigInteger objects and the remainder object is returned.
   780 
       
   781     /**
       
   782      * Calculates the quotient and remainder of this div b and places them
       
   783      * in the MutableBigInteger objects provided.
       
   784      *
   873      *
   785      * Uses Algorithm D in Knuth section 4.3.1.
   874      * Uses Algorithm D in Knuth section 4.3.1.
   786      * Many optimizations to that algorithm have been adapted from the Colin
   875      * Many optimizations to that algorithm have been adapted from the Colin
   787      * Plumb C library.
   876      * Plumb C library.
   788      * It special cases one word divisors for speed.
   877      * It special cases one word divisors for speed. The content of b is not
   789      * The contents of a and b are not changed.
   878      * changed.
   790      *
   879      *
   791      */
   880      */
   792     void divide(MutableBigInteger b,
   881     MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) {
   793                         MutableBigInteger quotient, MutableBigInteger rem) {
       
   794         if (b.intLen == 0)
   882         if (b.intLen == 0)
   795             throw new ArithmeticException("BigInteger divide by zero");
   883             throw new ArithmeticException("BigInteger divide by zero");
   796 
   884 
   797         // Dividend is zero
   885         // Dividend is zero
   798         if (intLen == 0) {
   886         if (intLen == 0) {
   799             quotient.intLen = quotient.offset = rem.intLen = rem.offset = 0;
   887             quotient.intLen = quotient.offset;
   800             return;
   888             return new MutableBigInteger();
   801         }
   889         }
   802 
   890 
   803         int cmp = compare(b);
   891         int cmp = compare(b);
   804 
       
   805         // Dividend less than divisor
   892         // Dividend less than divisor
   806         if (cmp < 0) {
   893         if (cmp < 0) {
   807             quotient.intLen = quotient.offset = 0;
   894             quotient.intLen = quotient.offset = 0;
   808             rem.copyValue(this);
   895             return new MutableBigInteger(this);
   809             return;
       
   810         }
   896         }
   811         // Dividend equal to divisor
   897         // Dividend equal to divisor
   812         if (cmp == 0) {
   898         if (cmp == 0) {
   813             quotient.value[0] = quotient.intLen = 1;
   899             quotient.value[0] = quotient.intLen = 1;
   814             quotient.offset = rem.intLen = rem.offset = 0;
   900             quotient.offset = 0;
   815             return;
   901             return new MutableBigInteger();
   816         }
   902         }
   817 
   903 
   818         quotient.clear();
   904         quotient.clear();
   819 
       
   820         // Special case one word divisor
   905         // Special case one word divisor
   821         if (b.intLen == 1) {
   906         if (b.intLen == 1) {
   822             rem.copyValue(this);
   907             int r = divideOneWord(b.value[b.offset], quotient);
   823             rem.divideOneWord(b.value[b.offset], quotient);
   908             if (r == 0)
   824             return;
   909                 return new MutableBigInteger();
       
   910             return new MutableBigInteger(r);
   825         }
   911         }
   826 
   912 
   827         // Copy divisor value to protect divisor
   913         // Copy divisor value to protect divisor
   828         int[] d = new int[b.intLen];
   914         int[] div = Arrays.copyOfRange(b.value, b.offset, b.offset + b.intLen);
   829         for(int i=0; i<b.intLen; i++)
   915         return divideMagnitude(div, quotient);
   830             d[i] = b.value[b.offset+i];
   916     }
   831         int dlen = b.intLen;
   917 
       
   918     /**
       
   919      * Internally used  to calculate the quotient of this div v and places the
       
   920      * quotient in the provided MutableBigInteger object and the remainder is
       
   921      * returned.
       
   922      *
       
   923      * @return the remainder of the division will be returned.
       
   924      */
       
   925     long divide(long v, MutableBigInteger quotient) {
       
   926         if (v == 0)
       
   927             throw new ArithmeticException("BigInteger divide by zero");
       
   928 
       
   929         // Dividend is zero
       
   930         if (intLen == 0) {
       
   931             quotient.intLen = quotient.offset = 0;
       
   932             return 0;
       
   933         }
       
   934         if (v < 0)
       
   935             v = -v;
       
   936 
       
   937         int d = (int)(v >>> 32);
       
   938         quotient.clear();
       
   939         // Special case on word divisor
       
   940         if (d == 0)
       
   941             return divideOneWord((int)v, quotient) & LONG_MASK;
       
   942         else {
       
   943             int[] div = new int[]{ d, (int)(v & LONG_MASK) };
       
   944             return divideMagnitude(div, quotient).toLong();
       
   945         }
       
   946     }
       
   947 
       
   948     /**
       
   949      * Divide this MutableBigInteger by the divisor represented by its magnitude
       
   950      * array. The quotient will be placed into the provided quotient object &
       
   951      * the remainder object is returned.
       
   952      */
       
   953     private MutableBigInteger divideMagnitude(int[] divisor,
       
   954                                               MutableBigInteger quotient) {
   832 
   955 
   833         // Remainder starts as dividend with space for a leading zero
   956         // Remainder starts as dividend with space for a leading zero
   834         if (rem.value.length < intLen +1)
   957         MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]);
   835             rem.value = new int[intLen+1];
   958         System.arraycopy(value, offset, rem.value, 1, intLen);
   836 
       
   837         for (int i=0; i<intLen; i++)
       
   838             rem.value[i+1] = value[i+offset];
       
   839         rem.intLen = intLen;
   959         rem.intLen = intLen;
   840         rem.offset = 1;
   960         rem.offset = 1;
   841 
   961 
   842         int nlen = rem.intLen;
   962         int nlen = rem.intLen;
   843 
   963 
   844         // Set the quotient size
   964         // Set the quotient size
       
   965         int dlen = divisor.length;
   845         int limit = nlen - dlen + 1;
   966         int limit = nlen - dlen + 1;
   846         if (quotient.value.length < limit) {
   967         if (quotient.value.length < limit) {
   847             quotient.value = new int[limit];
   968             quotient.value = new int[limit];
   848             quotient.offset = 0;
   969             quotient.offset = 0;
   849         }
   970         }
   850         quotient.intLen = limit;
   971         quotient.intLen = limit;
   851         int[] q = quotient.value;
   972         int[] q = quotient.value;
   852 
   973 
   853         // D1 normalize the divisor
   974         // D1 normalize the divisor
   854         int shift = 32 - BigInteger.bitLen(d[0]);
   975         int shift = Integer.numberOfLeadingZeros(divisor[0]);
   855         if (shift > 0) {
   976         if (shift > 0) {
   856             // First shift will not grow array
   977             // First shift will not grow array
   857             BigInteger.primitiveLeftShift(d, dlen, shift);
   978             BigInteger.primitiveLeftShift(divisor, dlen, shift);
   858             // But this one might
   979             // But this one might
   859             rem.leftShift(shift);
   980             rem.leftShift(shift);
   860         }
   981         }
   861 
   982 
   862         // Must insert leading 0 in rem if its length did not change
   983         // Must insert leading 0 in rem if its length did not change
   864             rem.offset = 0;
   985             rem.offset = 0;
   865             rem.value[0] = 0;
   986             rem.value[0] = 0;
   866             rem.intLen++;
   987             rem.intLen++;
   867         }
   988         }
   868 
   989 
   869         int dh = d[0];
   990         int dh = divisor[0];
   870         long dhLong = dh & LONG_MASK;
   991         long dhLong = dh & LONG_MASK;
   871         int dl = d[1];
   992         int dl = divisor[1];
   872         int[] qWord = new int[2];
   993         int[] qWord = new int[2];
   873 
   994 
   874         // D2 Initialize j
   995         // D2 Initialize j
   875         for(int j=0; j<limit; j++) {
   996         for(int j=0; j<limit; j++) {
   876             // D3 Calculate qhat
   997             // D3 Calculate qhat
   908 
  1029 
   909                 if (unsignedLongCompare(estProduct, rs)) {
  1030                 if (unsignedLongCompare(estProduct, rs)) {
   910                     qhat--;
  1031                     qhat--;
   911                     qrem = (int)((qrem & LONG_MASK) + dhLong);
  1032                     qrem = (int)((qrem & LONG_MASK) + dhLong);
   912                     if ((qrem & LONG_MASK) >=  dhLong) {
  1033                     if ((qrem & LONG_MASK) >=  dhLong) {
   913                         estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
  1034                         estProduct -= (dl & LONG_MASK);
   914                         rs = ((qrem & LONG_MASK) << 32) | nl;
  1035                         rs = ((qrem & LONG_MASK) << 32) | nl;
   915                         if (unsignedLongCompare(estProduct, rs))
  1036                         if (unsignedLongCompare(estProduct, rs))
   916                             qhat--;
  1037                             qhat--;
   917                     }
  1038                     }
   918                 }
  1039                 }
   919             }
  1040             }
   920 
  1041 
   921             // D4 Multiply and subtract
  1042             // D4 Multiply and subtract
   922             rem.value[j+rem.offset] = 0;
  1043             rem.value[j+rem.offset] = 0;
   923             int borrow = mulsub(rem.value, d, qhat, dlen, j+rem.offset);
  1044             int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset);
   924 
  1045 
   925             // D5 Test remainder
  1046             // D5 Test remainder
   926             if (borrow + 0x80000000 > nh2) {
  1047             if (borrow + 0x80000000 > nh2) {
   927                 // D6 Add back
  1048                 // D6 Add back
   928                 divadd(d, rem.value, j+1+rem.offset);
  1049                 divadd(divisor, rem.value, j+1+rem.offset);
   929                 qhat--;
  1050                 qhat--;
   930             }
  1051             }
   931 
  1052 
   932             // Store the quotient digit
  1053             // Store the quotient digit
   933             q[j] = qhat;
  1054             q[j] = qhat;
   935 
  1056 
   936         // D8 Unnormalize
  1057         // D8 Unnormalize
   937         if (shift > 0)
  1058         if (shift > 0)
   938             rem.rightShift(shift);
  1059             rem.rightShift(shift);
   939 
  1060 
       
  1061         quotient.normalize();
   940         rem.normalize();
  1062         rem.normalize();
   941         quotient.normalize();
  1063         return rem;
   942     }
  1064     }
   943 
  1065 
   944     /**
  1066     /**
   945      * Compare two longs as if they were unsigned.
  1067      * Compare two longs as if they were unsigned.
   946      * Returns true iff one is bigger than two.
  1068      * Returns true iff one is bigger than two.
   987      */
  1109      */
   988     MutableBigInteger hybridGCD(MutableBigInteger b) {
  1110     MutableBigInteger hybridGCD(MutableBigInteger b) {
   989         // Use Euclid's algorithm until the numbers are approximately the
  1111         // Use Euclid's algorithm until the numbers are approximately the
   990         // same length, then use the binary GCD algorithm to find the GCD.
  1112         // same length, then use the binary GCD algorithm to find the GCD.
   991         MutableBigInteger a = this;
  1113         MutableBigInteger a = this;
   992         MutableBigInteger q = new MutableBigInteger(),
  1114         MutableBigInteger q = new MutableBigInteger();
   993                           r = new MutableBigInteger();
       
   994 
  1115 
   995         while (b.intLen != 0) {
  1116         while (b.intLen != 0) {
   996             if (Math.abs(a.intLen - b.intLen) < 2)
  1117             if (Math.abs(a.intLen - b.intLen) < 2)
   997                 return a.binaryGCD(b);
  1118                 return a.binaryGCD(b);
   998 
  1119 
   999             a.divide(b, q, r);
  1120             MutableBigInteger r = a.divide(b, q);
  1000             MutableBigInteger swapper = a;
  1121             a = b;
  1001             a = b; b = r; r = swapper;
  1122             b = r;
  1002         }
  1123         }
  1003         return a;
  1124         return a;
  1004     }
  1125     }
  1005 
  1126 
  1006     /**
  1127     /**
  1067         if (b==0)
  1188         if (b==0)
  1068             return a;
  1189             return a;
  1069         if (a==0)
  1190         if (a==0)
  1070             return b;
  1191             return b;
  1071 
  1192 
  1072         int x;
  1193         // Right shift a & b till their last bits equal to 1.
  1073         int aZeros = 0;
  1194         int aZeros = Integer.numberOfTrailingZeros(a);
  1074         while ((x = a & 0xff) == 0) {
  1195         int bZeros = Integer.numberOfTrailingZeros(b);
  1075             a >>>= 8;
  1196         a >>>= aZeros;
  1076             aZeros += 8;
  1197         b >>>= bZeros;
  1077         }
       
  1078         int y = BigInteger.trailingZeroTable[x];
       
  1079         aZeros += y;
       
  1080         a >>>= y;
       
  1081 
       
  1082         int bZeros = 0;
       
  1083         while ((x = b & 0xff) == 0) {
       
  1084             b >>>= 8;
       
  1085             bZeros += 8;
       
  1086         }
       
  1087         y = BigInteger.trailingZeroTable[x];
       
  1088         bZeros += y;
       
  1089         b >>>= y;
       
  1090 
  1198 
  1091         int t = (aZeros < bZeros ? aZeros : bZeros);
  1199         int t = (aZeros < bZeros ? aZeros : bZeros);
  1092 
  1200 
  1093         while (a != b) {
  1201         while (a != b) {
  1094             if ((a+0x80000000) > (b+0x80000000)) {  // a > b as unsigned
  1202             if ((a+0x80000000) > (b+0x80000000)) {  // a > b as unsigned
  1095                 a -= b;
  1203                 a -= b;
  1096 
  1204                 a >>>= Integer.numberOfTrailingZeros(a);
  1097                 while ((x = a & 0xff) == 0)
       
  1098                     a >>>= 8;
       
  1099                 a >>>= BigInteger.trailingZeroTable[x];
       
  1100             } else {
  1205             } else {
  1101                 b -= a;
  1206                 b -= a;
  1102 
  1207                 b >>>= Integer.numberOfTrailingZeros(b);
  1103                 while ((x = b & 0xff) == 0)
       
  1104                     b >>>= 8;
       
  1105                 b >>>= BigInteger.trailingZeroTable[x];
       
  1106             }
  1208             }
  1107         }
  1209         }
  1108         return a<<t;
  1210         return a<<t;
  1109     }
  1211     }
  1110 
  1212 
  1150 
  1252 
  1151         evenPart.multiply(oddMod, temp1);
  1253         evenPart.multiply(oddMod, temp1);
  1152         temp1.multiply(y2, temp2);
  1254         temp1.multiply(y2, temp2);
  1153 
  1255 
  1154         result.add(temp2);
  1256         result.add(temp2);
  1155         result.divide(p, temp1, temp2);
  1257         return result.divide(p, temp1);
  1156         return temp2;
       
  1157     }
  1258     }
  1158 
  1259 
  1159     /*
  1260     /*
  1160      * Calculate the multiplicative inverse of this mod 2^k.
  1261      * Calculate the multiplicative inverse of this mod 2^k.
  1161      */
  1262      */
  1319         b.leftShift(k);
  1420         b.leftShift(k);
  1320         MutableBigInteger mod = new MutableBigInteger(b);
  1421         MutableBigInteger mod = new MutableBigInteger(b);
  1321 
  1422 
  1322         MutableBigInteger a = new MutableBigInteger(this);
  1423         MutableBigInteger a = new MutableBigInteger(this);
  1323         MutableBigInteger q = new MutableBigInteger();
  1424         MutableBigInteger q = new MutableBigInteger();
  1324         MutableBigInteger r = new MutableBigInteger();
  1425         MutableBigInteger r = b.divide(a, q);
  1325 
  1426 
  1326         b.divide(a, q, r);
  1427         MutableBigInteger swapper = b;
  1327         MutableBigInteger swapper = b; b = r; r = swapper;
  1428         // swap b & r
       
  1429         b = r;
       
  1430         r = swapper;
  1328 
  1431 
  1329         MutableBigInteger t1 = new MutableBigInteger(q);
  1432         MutableBigInteger t1 = new MutableBigInteger(q);
  1330         MutableBigInteger t0 = new MutableBigInteger(1);
  1433         MutableBigInteger t0 = new MutableBigInteger(1);
  1331         MutableBigInteger temp = new MutableBigInteger();
  1434         MutableBigInteger temp = new MutableBigInteger();
  1332 
  1435 
  1333         while (!b.isOne()) {
  1436         while (!b.isOne()) {
  1334             a.divide(b, q, r);
  1437             r = a.divide(b, q);
  1335 
  1438 
  1336             if (r.intLen == 0)
  1439             if (r.intLen == 0)
  1337                 throw new ArithmeticException("BigInteger not invertible.");
  1440                 throw new ArithmeticException("BigInteger not invertible.");
  1338 
  1441 
  1339             swapper = r; r = a; a = swapper;
  1442             swapper = r;
       
  1443             a = swapper;
  1340 
  1444 
  1341             if (q.intLen == 1)
  1445             if (q.intLen == 1)
  1342                 t1.mul(q.value[q.offset], temp);
  1446                 t1.mul(q.value[q.offset], temp);
  1343             else
  1447             else
  1344                 q.multiply(t1, temp);
  1448                 q.multiply(t1, temp);
  1345             swapper = q; q = temp; temp = swapper;
  1449             swapper = q;
  1346 
  1450             q = temp;
       
  1451             temp = swapper;
  1347             t0.add(q);
  1452             t0.add(q);
  1348 
  1453 
  1349             if (a.isOne())
  1454             if (a.isOne())
  1350                 return t0;
  1455                 return t0;
  1351 
  1456 
  1352             b.divide(a, q, r);
  1457             r = b.divide(a, q);
  1353 
  1458 
  1354             if (r.intLen == 0)
  1459             if (r.intLen == 0)
  1355                 throw new ArithmeticException("BigInteger not invertible.");
  1460                 throw new ArithmeticException("BigInteger not invertible.");
  1356 
  1461 
  1357             swapper = b; b = r; r = swapper;
  1462             swapper = b;
       
  1463             b =  r;
  1358 
  1464 
  1359             if (q.intLen == 1)
  1465             if (q.intLen == 1)
  1360                 t0.mul(q.value[q.offset], temp);
  1466                 t0.mul(q.value[q.offset], temp);
  1361             else
  1467             else
  1362                 q.multiply(t0, temp);
  1468                 q.multiply(t0, temp);