jdk/src/share/classes/java/math/BigInteger.java
changeset 2922 dd6d609861f0
parent 2 90ce3da70b43
child 4151 db7d59c0b0e6
equal deleted inserted replaced
2921:d9d491a5a169 2922:dd6d609861f0
   103      * a signum of 0.  This is necessary to ensures that there is exactly one
   103      * a signum of 0.  This is necessary to ensures that there is exactly one
   104      * representation for each BigInteger value.
   104      * representation for each BigInteger value.
   105      *
   105      *
   106      * @serial
   106      * @serial
   107      */
   107      */
   108     int signum;
   108     final int signum;
   109 
   109 
   110     /**
   110     /**
   111      * The magnitude of this BigInteger, in <i>big-endian</i> order: the
   111      * The magnitude of this BigInteger, in <i>big-endian</i> order: the
   112      * zeroth element of this array is the most-significant int of the
   112      * zeroth element of this array is the most-significant int of the
   113      * magnitude.  The magnitude must be "minimal" in that the most-significant
   113      * magnitude.  The magnitude must be "minimal" in that the most-significant
   114      * int ({@code mag[0]}) must be non-zero.  This is necessary to
   114      * int ({@code mag[0]}) must be non-zero.  This is necessary to
   115      * ensure that there is exactly one representation for each BigInteger
   115      * ensure that there is exactly one representation for each BigInteger
   116      * value.  Note that this implies that the BigInteger zero has a
   116      * value.  Note that this implies that the BigInteger zero has a
   117      * zero-length mag array.
   117      * zero-length mag array.
   118      */
   118      */
   119     int[] mag;
   119     final int[] mag;
   120 
   120 
   121     // These "redundant fields" are initialized with recognizable nonsense
   121     // These "redundant fields" are initialized with recognizable nonsense
   122     // values, and cached the first time they are needed (or never, if they
   122     // values, and cached the first time they are needed (or never, if they
   123     // aren't needed).
   123     // aren't needed).
   124 
   124 
   125     /**
   125      /**
   126      * The bitCount of this BigInteger, as returned by bitCount(), or -1
   126      * One plus the bitCount of this BigInteger. Zeros means unitialized.
   127      * (either value is acceptable).
       
   128      *
   127      *
   129      * @serial
   128      * @serial
   130      * @see #bitCount
   129      * @see #bitCount
   131      */
   130      * @deprecated Deprecated since logical value is offset from stored
   132     private int bitCount =  -1;
   131      * value and correction factor is applied in accessor method.
   133 
   132      */
   134     /**
   133     @Deprecated
   135      * The bitLength of this BigInteger, as returned by bitLength(), or -1
   134     private int bitCount;
       
   135 
       
   136     /**
       
   137      * One plus the bitLength of this BigInteger. Zeros means unitialized.
   136      * (either value is acceptable).
   138      * (either value is acceptable).
   137      *
   139      *
   138      * @serial
   140      * @serial
   139      * @see #bitLength()
   141      * @see #bitLength()
   140      */
   142      * @deprecated Deprecated since logical value is offset from stored
   141     private int bitLength = -1;
   143      * value and correction factor is applied in accessor method.
   142 
   144      */
   143     /**
   145     @Deprecated
   144      * The lowest set bit of this BigInteger, as returned by getLowestSetBit(),
   146     private int bitLength;
   145      * or -2 (either value is acceptable).
   147 
       
   148     /**
       
   149      * Two plus the lowest set bit of this BigInteger, as returned by
       
   150      * getLowestSetBit().
   146      *
   151      *
   147      * @serial
   152      * @serial
   148      * @see #getLowestSetBit
   153      * @see #getLowestSetBit
   149      */
   154      * @deprecated Deprecated since logical value is offset from stored
   150     private int lowestSetBit = -2;
   155      * value and correction factor is applied in accessor method.
   151 
   156      */
   152     /**
   157     @Deprecated
   153      * The index of the lowest-order byte in the magnitude of this BigInteger
   158     private int lowestSetBit;
   154      * that contains a nonzero byte, or -2 (either value is acceptable).  The
   159 
   155      * least significant byte has int-number 0, the next byte in order of
   160     /**
   156      * increasing significance has byte-number 1, and so forth.
   161      * Two plus the index of the lowest-order int in the magnitude of this
   157      *
   162      * BigInteger that contains a nonzero int, or -2 (either value is acceptable).
   158      * @serial
   163      * The least significant int has int-number 0, the next int in order of
   159      */
       
   160     private int firstNonzeroByteNum = -2;
       
   161 
       
   162     /**
       
   163      * The index of the lowest-order int in the magnitude of this BigInteger
       
   164      * that contains a nonzero int, or -2 (either value is acceptable).  The
       
   165      * least significant int has int-number 0, the next int in order of
       
   166      * increasing significance has int-number 1, and so forth.
   164      * increasing significance has int-number 1, and so forth.
   167      */
   165      * @deprecated Deprecated since logical value is offset from stored
   168     private int firstNonzeroIntNum = -2;
   166      * value and correction factor is applied in accessor method.
       
   167      */
       
   168     @Deprecated
       
   169     private int firstNonzeroIntNum;
   169 
   170 
   170     /**
   171     /**
   171      * This mask is used to obtain the value of an int as if it were unsigned.
   172      * This mask is used to obtain the value of an int as if it were unsigned.
   172      */
   173      */
   173     private final static long LONG_MASK = 0xffffffffL;
   174     final static long LONG_MASK = 0xffffffffL;
   174 
   175 
   175     //Constructors
   176     //Constructors
   176 
   177 
   177     /**
   178     /**
   178      * Translates a byte array containing the two's-complement binary
   179      * Translates a byte array containing the two's-complement binary
   293             throw new NumberFormatException("Radix out of range");
   294             throw new NumberFormatException("Radix out of range");
   294         if (val.length() == 0)
   295         if (val.length() == 0)
   295             throw new NumberFormatException("Zero length BigInteger");
   296             throw new NumberFormatException("Zero length BigInteger");
   296 
   297 
   297         // Check for at most one leading sign
   298         // Check for at most one leading sign
   298         signum = 1;
   299         int sign = 1;
   299         int index1 = val.lastIndexOf('-');
   300         int index1 = val.lastIndexOf('-');
   300         int index2 = val.lastIndexOf('+');
   301         int index2 = val.lastIndexOf('+');
   301         if ((index1 + index2) <= -1) {
   302         if ((index1 + index2) <= -1) {
   302             // No leading sign character or at most one leading sign character
   303             // No leading sign character or at most one leading sign character
   303             if (index1 == 0 || index2 == 0) {
   304             if (index1 == 0 || index2 == 0) {
   304                 cursor = 1;
   305                 cursor = 1;
   305                 if (val.length() == 1)
   306                 if (val.length() == 1)
   306                     throw new NumberFormatException("Zero length BigInteger");
   307                     throw new NumberFormatException("Zero length BigInteger");
   307             }
   308             }
   308             if (index1 == 0)
   309             if (index1 == 0)
   309                 signum = -1;
   310                 sign = -1;
   310         } else
   311         } else
   311             throw new NumberFormatException("Illegal embedded sign character");
   312             throw new NumberFormatException("Illegal embedded sign character");
   312 
   313 
   313         // Skip leading zeros and compute number of digits in magnitude
   314         // Skip leading zeros and compute number of digits in magnitude
   314         while (cursor < len &&
   315         while (cursor < len &&
   316             cursor++;
   317             cursor++;
   317         if (cursor == len) {
   318         if (cursor == len) {
   318             signum = 0;
   319             signum = 0;
   319             mag = ZERO.mag;
   320             mag = ZERO.mag;
   320             return;
   321             return;
   321         } else {
   322         }
   322             numDigits = len - cursor;
   323 
   323         }
   324         numDigits = len - cursor;
       
   325         signum = sign;
   324 
   326 
   325         // Pre-allocate array of expected size. May be too large but can
   327         // Pre-allocate array of expected size. May be too large but can
   326         // never be too small. Typically exact.
   328         // never be too small. Typically exact.
   327         int numBits = (int)(((numDigits * bitsPerDigit[radix]) >>> 10) + 1);
   329         int numBits = (int)(((numDigits * bitsPerDigit[radix]) >>> 10) + 1);
   328         int numWords = (numBits + 31) /32;
   330         int numWords = (numBits + 31) >>> 5;
   329         mag = new int[numWords];
   331         int[] magnitude = new int[numWords];
   330 
   332 
   331         // Process first (potentially short) digit group
   333         // Process first (potentially short) digit group
   332         int firstGroupLen = numDigits % digitsPerInt[radix];
   334         int firstGroupLen = numDigits % digitsPerInt[radix];
   333         if (firstGroupLen == 0)
   335         if (firstGroupLen == 0)
   334             firstGroupLen = digitsPerInt[radix];
   336             firstGroupLen = digitsPerInt[radix];
   335         String group = val.substring(cursor, cursor += firstGroupLen);
   337         String group = val.substring(cursor, cursor += firstGroupLen);
   336         mag[mag.length - 1] = Integer.parseInt(group, radix);
   338         magnitude[numWords - 1] = Integer.parseInt(group, radix);
   337         if (mag[mag.length - 1] < 0)
   339         if (magnitude[numWords - 1] < 0)
   338             throw new NumberFormatException("Illegal digit");
   340             throw new NumberFormatException("Illegal digit");
   339 
   341 
   340         // Process remaining digit groups
   342         // Process remaining digit groups
   341         int superRadix = intRadix[radix];
   343         int superRadix = intRadix[radix];
   342         int groupVal = 0;
   344         int groupVal = 0;
   343         while (cursor < val.length()) {
   345         while (cursor < val.length()) {
   344             group = val.substring(cursor, cursor += digitsPerInt[radix]);
   346             group = val.substring(cursor, cursor += digitsPerInt[radix]);
   345             groupVal = Integer.parseInt(group, radix);
   347             groupVal = Integer.parseInt(group, radix);
   346             if (groupVal < 0)
   348             if (groupVal < 0)
   347                 throw new NumberFormatException("Illegal digit");
   349                 throw new NumberFormatException("Illegal digit");
   348             destructiveMulAdd(mag, superRadix, groupVal);
   350             destructiveMulAdd(magnitude, superRadix, groupVal);
   349         }
   351         }
   350         // Required for cases where the array was overallocated.
   352         // Required for cases where the array was overallocated.
   351         mag = trustedStripLeadingZeroInts(mag);
   353         mag = trustedStripLeadingZeroInts(magnitude);
   352     }
   354     }
   353 
   355 
   354     // Constructs a new BigInteger using a char array with radix=10
   356     // Constructs a new BigInteger using a char array with radix=10
   355     BigInteger(char[] val) {
   357     BigInteger(char[] val) {
   356         int cursor = 0, numDigits;
   358         int cursor = 0, numDigits;
   357         int len = val.length;
   359         int len = val.length;
   358 
   360 
   359         // Check for leading minus sign
   361         // Check for leading minus sign
   360         signum = 1;
   362         int sign = 1;
   361         if (val[0] == '-') {
   363         if (val[0] == '-') {
   362             if (len == 1)
   364             if (len == 1)
   363                 throw new NumberFormatException("Zero length BigInteger");
   365                 throw new NumberFormatException("Zero length BigInteger");
   364             signum = -1;
   366             sign = -1;
   365             cursor = 1;
   367             cursor = 1;
   366         } else if (val[0] == '+') {
   368         } else if (val[0] == '+') {
   367             if (len == 1)
   369             if (len == 1)
   368                 throw new NumberFormatException("Zero length BigInteger");
   370                 throw new NumberFormatException("Zero length BigInteger");
   369             cursor = 1;
   371             cursor = 1;
   374             cursor++;
   376             cursor++;
   375         if (cursor == len) {
   377         if (cursor == len) {
   376             signum = 0;
   378             signum = 0;
   377             mag = ZERO.mag;
   379             mag = ZERO.mag;
   378             return;
   380             return;
   379         } else {
   381         }
   380             numDigits = len - cursor;
   382 
   381         }
   383         numDigits = len - cursor;
       
   384         signum = sign;
   382 
   385 
   383         // Pre-allocate array of expected size
   386         // Pre-allocate array of expected size
   384         int numWords;
   387         int numWords;
   385         if (len < 10) {
   388         if (len < 10) {
   386             numWords = 1;
   389             numWords = 1;
   387         } else {
   390         } else {
   388             int numBits = (int)(((numDigits * bitsPerDigit[10]) >>> 10) + 1);
   391             int numBits = (int)(((numDigits * bitsPerDigit[10]) >>> 10) + 1);
   389             numWords = (numBits + 31) /32;
   392             numWords = (numBits + 31) >>> 5;
   390         }
   393         }
   391         mag = new int[numWords];
   394         int[] magnitude = new int[numWords];
   392 
   395 
   393         // Process first (potentially short) digit group
   396         // Process first (potentially short) digit group
   394         int firstGroupLen = numDigits % digitsPerInt[10];
   397         int firstGroupLen = numDigits % digitsPerInt[10];
   395         if (firstGroupLen == 0)
   398         if (firstGroupLen == 0)
   396             firstGroupLen = digitsPerInt[10];
   399             firstGroupLen = digitsPerInt[10];
   397         mag[mag.length-1] = parseInt(val, cursor,  cursor += firstGroupLen);
   400         magnitude[numWords - 1] = parseInt(val, cursor,  cursor += firstGroupLen);
   398 
   401 
   399         // Process remaining digit groups
   402         // Process remaining digit groups
   400         while (cursor < len) {
   403         while (cursor < len) {
   401             int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
   404             int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
   402             destructiveMulAdd(mag, intRadix[10], groupVal);
   405             destructiveMulAdd(magnitude, intRadix[10], groupVal);
   403         }
   406         }
   404         mag = trustedStripLeadingZeroInts(mag);
   407         mag = trustedStripLeadingZeroInts(magnitude);
   405     }
   408     }
   406 
   409 
   407     // Create an integer with the digits between the two indexes
   410     // Create an integer with the digits between the two indexes
   408     // Assumes start < end. The result may be negative, but it
   411     // Assumes start < end. The result may be negative, but it
   409     // is to be treated as an unsigned value.
   412     // is to be treated as an unsigned value.
   840 
   843 
   841         for (int i=k.bitLength()-2; i>=0; i--) {
   844         for (int i=k.bitLength()-2; i>=0; i--) {
   842             u2 = u.multiply(v).mod(n);
   845             u2 = u.multiply(v).mod(n);
   843 
   846 
   844             v2 = v.square().add(d.multiply(u.square())).mod(n);
   847             v2 = v.square().add(d.multiply(u.square())).mod(n);
   845             if (v2.testBit(0)) {
   848             if (v2.testBit(0))
   846                 v2 = n.subtract(v2);
   849                 v2 = v2.subtract(n);
   847                 v2.signum = - v2.signum;
   850 
   848             }
       
   849             v2 = v2.shiftRight(1);
   851             v2 = v2.shiftRight(1);
   850 
   852 
   851             u = u2; v = v2;
   853             u = u2; v = v2;
   852             if (k.testBit(i)) {
   854             if (k.testBit(i)) {
   853                 u2 = u.add(v).mod(n);
   855                 u2 = u.add(v).mod(n);
   854                 if (u2.testBit(0)) {
   856                 if (u2.testBit(0))
   855                     u2 = n.subtract(u2);
   857                     u2 = u2.subtract(n);
   856                     u2.signum = - u2.signum;
   858 
   857                 }
       
   858                 u2 = u2.shiftRight(1);
   859                 u2 = u2.shiftRight(1);
   859 
       
   860                 v2 = v.add(d.multiply(u)).mod(n);
   860                 v2 = v.add(d.multiply(u)).mod(n);
   861                 if (v2.testBit(0)) {
   861                 if (v2.testBit(0))
   862                     v2 = n.subtract(v2);
   862                     v2 = v2.subtract(n);
   863                     v2.signum = - v2.signum;
       
   864                 }
       
   865                 v2 = v2.shiftRight(1);
   863                 v2 = v2.shiftRight(1);
   866 
   864 
   867                 u = u2; v = v2;
   865                 u = u2; v = v2;
   868             }
   866             }
   869         }
   867         }
   916         }
   914         }
   917         return true;
   915         return true;
   918     }
   916     }
   919 
   917 
   920     /**
   918     /**
   921      * This private constructor differs from its public cousin
   919      * This internal constructor differs from its public cousin
   922      * with the arguments reversed in two ways: it assumes that its
   920      * with the arguments reversed in two ways: it assumes that its
   923      * arguments are correct, and it doesn't copy the magnitude array.
   921      * arguments are correct, and it doesn't copy the magnitude array.
   924      */
   922      */
   925     private BigInteger(int[] magnitude, int signum) {
   923     BigInteger(int[] magnitude, int signum) {
   926         this.signum = (magnitude.length==0 ? 0 : signum);
   924         this.signum = (magnitude.length==0 ? 0 : signum);
   927         this.mag = magnitude;
   925         this.mag = magnitude;
   928     }
   926     }
   929 
   927 
   930     /**
   928     /**
   932      * arguments are correct.
   930      * arguments are correct.
   933      */
   931      */
   934     private BigInteger(byte[] magnitude, int signum) {
   932     private BigInteger(byte[] magnitude, int signum) {
   935         this.signum = (magnitude.length==0 ? 0 : signum);
   933         this.signum = (magnitude.length==0 ? 0 : signum);
   936         this.mag = stripLeadingZeroBytes(magnitude);
   934         this.mag = stripLeadingZeroBytes(magnitude);
   937     }
       
   938 
       
   939     /**
       
   940      * This private constructor is for internal use in converting
       
   941      * from a MutableBigInteger object into a BigInteger.
       
   942      */
       
   943     BigInteger(MutableBigInteger val, int sign) {
       
   944         if (val.offset > 0 || val.value.length != val.intLen) {
       
   945             mag = new int[val.intLen];
       
   946             for(int i=0; i<val.intLen; i++)
       
   947                 mag[i] = val.value[val.offset+i];
       
   948         } else {
       
   949             mag = val.value;
       
   950         }
       
   951 
       
   952         this.signum = (val.intLen == 0) ? 0 : sign;
       
   953     }
   935     }
   954 
   936 
   955     //Static Factory Methods
   937     //Static Factory Methods
   956 
   938 
   957     /**
   939     /**
   978     /**
   960     /**
   979      * Constructs a BigInteger with the specified value, which may not be zero.
   961      * Constructs a BigInteger with the specified value, which may not be zero.
   980      */
   962      */
   981     private BigInteger(long val) {
   963     private BigInteger(long val) {
   982         if (val < 0) {
   964         if (val < 0) {
       
   965             val = -val;
   983             signum = -1;
   966             signum = -1;
   984             val = -val;
       
   985         } else {
   967         } else {
   986             signum = 1;
   968             signum = 1;
   987         }
   969         }
   988 
   970 
   989         int highWord = (int)(val >>> 32);
   971         int highWord = (int)(val >>> 32);
  1056      *
  1038      *
  1057      * @param  val value to be added to this BigInteger.
  1039      * @param  val value to be added to this BigInteger.
  1058      * @return {@code this + val}
  1040      * @return {@code this + val}
  1059      */
  1041      */
  1060     public BigInteger add(BigInteger val) {
  1042     public BigInteger add(BigInteger val) {
  1061         int[] resultMag;
       
  1062         if (val.signum == 0)
  1043         if (val.signum == 0)
  1063             return this;
  1044             return this;
  1064         if (signum == 0)
  1045         if (signum == 0)
  1065             return val;
  1046             return val;
  1066         if (val.signum == signum)
  1047         if (val.signum == signum)
  1067             return new BigInteger(add(mag, val.mag), signum);
  1048             return new BigInteger(add(mag, val.mag), signum);
  1068 
  1049 
  1069         int cmp = intArrayCmp(mag, val.mag);
  1050         int cmp = compareMagnitude(val);
  1070         if (cmp==0)
  1051         if (cmp == 0)
  1071             return ZERO;
  1052             return ZERO;
  1072         resultMag = (cmp>0 ? subtract(mag, val.mag)
  1053         int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
  1073                            : subtract(val.mag, mag));
  1054                            : subtract(val.mag, mag));
  1074         resultMag = trustedStripLeadingZeroInts(resultMag);
  1055         resultMag = trustedStripLeadingZeroInts(resultMag);
  1075 
  1056 
  1076         return new BigInteger(resultMag, cmp*signum);
  1057         return new BigInteger(resultMag, cmp == signum ? 1 : -1);
  1077     }
  1058     }
  1078 
  1059 
  1079     /**
  1060     /**
  1080      * Adds the contents of the int arrays x and y. This method allocates
  1061      * Adds the contents of the int arrays x and y. This method allocates
  1081      * a new int array to hold the answer and returns a reference to that
  1062      * a new int array to hold the answer and returns a reference to that
  1110         while (xIndex > 0)
  1091         while (xIndex > 0)
  1111             result[--xIndex] = x[xIndex];
  1092             result[--xIndex] = x[xIndex];
  1112 
  1093 
  1113         // Grow result if necessary
  1094         // Grow result if necessary
  1114         if (carry) {
  1095         if (carry) {
  1115             int newLen = result.length + 1;
  1096             int bigger[] = new int[result.length + 1];
  1116             int temp[] = new int[newLen];
  1097             System.arraycopy(result, 0, bigger, 1, result.length);
  1117             for (int i = 1; i<newLen; i++)
  1098             bigger[0] = 0x01;
  1118                 temp[i] = result[i-1];
  1099             return bigger;
  1119             temp[0] = 0x01;
       
  1120             result = temp;
       
  1121         }
  1100         }
  1122         return result;
  1101         return result;
  1123     }
  1102     }
  1124 
  1103 
  1125     /**
  1104     /**
  1127      *
  1106      *
  1128      * @param  val value to be subtracted from this BigInteger.
  1107      * @param  val value to be subtracted from this BigInteger.
  1129      * @return {@code this - val}
  1108      * @return {@code this - val}
  1130      */
  1109      */
  1131     public BigInteger subtract(BigInteger val) {
  1110     public BigInteger subtract(BigInteger val) {
  1132         int[] resultMag;
       
  1133         if (val.signum == 0)
  1111         if (val.signum == 0)
  1134             return this;
  1112             return this;
  1135         if (signum == 0)
  1113         if (signum == 0)
  1136             return val.negate();
  1114             return val.negate();
  1137         if (val.signum != signum)
  1115         if (val.signum != signum)
  1138             return new BigInteger(add(mag, val.mag), signum);
  1116             return new BigInteger(add(mag, val.mag), signum);
  1139 
  1117 
  1140         int cmp = intArrayCmp(mag, val.mag);
  1118         int cmp = compareMagnitude(val);
  1141         if (cmp==0)
  1119         if (cmp == 0)
  1142             return ZERO;
  1120             return ZERO;
  1143         resultMag = (cmp>0 ? subtract(mag, val.mag)
  1121         int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
  1144                            : subtract(val.mag, mag));
  1122                            : subtract(val.mag, mag));
  1145         resultMag = trustedStripLeadingZeroInts(resultMag);
  1123         resultMag = trustedStripLeadingZeroInts(resultMag);
  1146         return new BigInteger(resultMag, cmp*signum);
  1124         return new BigInteger(resultMag, cmp == signum ? 1 : -1);
  1147     }
  1125     }
  1148 
  1126 
  1149     /**
  1127     /**
  1150      * Subtracts the contents of the second int arrays (little) from the
  1128      * Subtracts the contents of the second int arrays (little) from the
  1151      * first (big).  The first int array (big) must represent a larger number
  1129      * first (big).  The first int array (big) must represent a larger number
  1189             return ZERO;
  1167             return ZERO;
  1190 
  1168 
  1191         int[] result = multiplyToLen(mag, mag.length,
  1169         int[] result = multiplyToLen(mag, mag.length,
  1192                                      val.mag, val.mag.length, null);
  1170                                      val.mag, val.mag.length, null);
  1193         result = trustedStripLeadingZeroInts(result);
  1171         result = trustedStripLeadingZeroInts(result);
  1194         return new BigInteger(result, signum*val.signum);
  1172         return new BigInteger(result, signum == val.signum ? 1 : -1);
       
  1173     }
       
  1174 
       
  1175     /**
       
  1176      * Package private methods used by BigDecimal code to multiply a BigInteger
       
  1177      * with a long. Assumes v is not equal to INFLATED.
       
  1178      */
       
  1179     BigInteger multiply(long v) {
       
  1180         if (v == 0 || signum == 0)
       
  1181           return ZERO;
       
  1182         if (v == BigDecimal.INFLATED)
       
  1183             return multiply(BigInteger.valueOf(v));
       
  1184         int rsign = (v > 0 ? signum : -signum);
       
  1185         if (v < 0)
       
  1186             v = -v;
       
  1187         long dh = v >>> 32;      // higher order bits
       
  1188         long dl = v & LONG_MASK; // lower order bits
       
  1189 
       
  1190         int xlen = mag.length;
       
  1191         int[] value = mag;
       
  1192         int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]);
       
  1193         long carry = 0;
       
  1194         int rstart = rmag.length - 1;
       
  1195         for (int i = xlen - 1; i >= 0; i--) {
       
  1196             long product = (value[i] & LONG_MASK) * dl + carry;
       
  1197             rmag[rstart--] = (int)product;
       
  1198             carry = product >>> 32;
       
  1199         }
       
  1200         rmag[rstart] = (int)carry;
       
  1201         if (dh != 0L) {
       
  1202             carry = 0;
       
  1203             rstart = rmag.length - 2;
       
  1204             for (int i = xlen - 1; i >= 0; i--) {
       
  1205                 long product = (value[i] & LONG_MASK) * dh +
       
  1206                     (rmag[rstart] & LONG_MASK) + carry;
       
  1207                 rmag[rstart--] = (int)product;
       
  1208                 carry = product >>> 32;
       
  1209             }
       
  1210             rmag[0] = (int)carry;
       
  1211         }
       
  1212         if (carry == 0L)
       
  1213             rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
       
  1214         return new BigInteger(rmag, rsign);
  1195     }
  1215     }
  1196 
  1216 
  1197     /**
  1217     /**
  1198      * Multiplies int arrays x and y to the specified lengths and places
  1218      * Multiplies int arrays x and y to the specified lengths and places
  1199      * the result into z.
  1219      * the result into z. There will be no leading zeros in the resultant array.
  1200      */
  1220      */
  1201     private int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
  1221     private int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
  1202         int xstart = xlen - 1;
  1222         int xstart = xlen - 1;
  1203         int ystart = ylen - 1;
  1223         int ystart = ylen - 1;
  1204 
  1224 
  1314      * @return {@code this / val}
  1334      * @return {@code this / val}
  1315      * @throws ArithmeticException {@code val==0}
  1335      * @throws ArithmeticException {@code val==0}
  1316      */
  1336      */
  1317     public BigInteger divide(BigInteger val) {
  1337     public BigInteger divide(BigInteger val) {
  1318         MutableBigInteger q = new MutableBigInteger(),
  1338         MutableBigInteger q = new MutableBigInteger(),
  1319                           r = new MutableBigInteger(),
       
  1320                           a = new MutableBigInteger(this.mag),
  1339                           a = new MutableBigInteger(this.mag),
  1321                           b = new MutableBigInteger(val.mag);
  1340                           b = new MutableBigInteger(val.mag);
  1322 
  1341 
  1323         a.divide(b, q, r);
  1342         a.divide(b, q);
  1324         return new BigInteger(q, this.signum * val.signum);
  1343         return q.toBigInteger(this.signum == val.signum ? 1 : -1);
  1325     }
  1344     }
  1326 
  1345 
  1327     /**
  1346     /**
  1328      * Returns an array of two BigIntegers containing {@code (this / val)}
  1347      * Returns an array of two BigIntegers containing {@code (this / val)}
  1329      * followed by {@code (this % val)}.
  1348      * followed by {@code (this % val)}.
  1336      * @throws ArithmeticException {@code val==0}
  1355      * @throws ArithmeticException {@code val==0}
  1337      */
  1356      */
  1338     public BigInteger[] divideAndRemainder(BigInteger val) {
  1357     public BigInteger[] divideAndRemainder(BigInteger val) {
  1339         BigInteger[] result = new BigInteger[2];
  1358         BigInteger[] result = new BigInteger[2];
  1340         MutableBigInteger q = new MutableBigInteger(),
  1359         MutableBigInteger q = new MutableBigInteger(),
  1341                           r = new MutableBigInteger(),
       
  1342                           a = new MutableBigInteger(this.mag),
  1360                           a = new MutableBigInteger(this.mag),
  1343                           b = new MutableBigInteger(val.mag);
  1361                           b = new MutableBigInteger(val.mag);
  1344         a.divide(b, q, r);
  1362         MutableBigInteger r = a.divide(b, q);
  1345         result[0] = new BigInteger(q, this.signum * val.signum);
  1363         result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);
  1346         result[1] = new BigInteger(r, this.signum);
  1364         result[1] = r.toBigInteger(this.signum);
  1347         return result;
  1365         return result;
  1348     }
  1366     }
  1349 
  1367 
  1350     /**
  1368     /**
  1351      * Returns a BigInteger whose value is {@code (this % val)}.
  1369      * Returns a BigInteger whose value is {@code (this % val)}.
  1355      * @return {@code this % val}
  1373      * @return {@code this % val}
  1356      * @throws ArithmeticException {@code val==0}
  1374      * @throws ArithmeticException {@code val==0}
  1357      */
  1375      */
  1358     public BigInteger remainder(BigInteger val) {
  1376     public BigInteger remainder(BigInteger val) {
  1359         MutableBigInteger q = new MutableBigInteger(),
  1377         MutableBigInteger q = new MutableBigInteger(),
  1360                           r = new MutableBigInteger(),
       
  1361                           a = new MutableBigInteger(this.mag),
  1378                           a = new MutableBigInteger(this.mag),
  1362                           b = new MutableBigInteger(val.mag);
  1379                           b = new MutableBigInteger(val.mag);
  1363 
  1380 
  1364         a.divide(b, q, r);
  1381         return a.divide(b, q).toBigInteger(this.signum);
  1365         return new BigInteger(r, this.signum);
       
  1366     }
  1382     }
  1367 
  1383 
  1368     /**
  1384     /**
  1369      * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>.
  1385      * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>.
  1370      * Note that {@code exponent} is an integer rather than a BigInteger.
  1386      * Note that {@code exponent} is an integer rather than a BigInteger.
  1416         MutableBigInteger a = new MutableBigInteger(this);
  1432         MutableBigInteger a = new MutableBigInteger(this);
  1417         MutableBigInteger b = new MutableBigInteger(val);
  1433         MutableBigInteger b = new MutableBigInteger(val);
  1418 
  1434 
  1419         MutableBigInteger result = a.hybridGCD(b);
  1435         MutableBigInteger result = a.hybridGCD(b);
  1420 
  1436 
  1421         return new BigInteger(result, 1);
  1437         return result.toBigInteger(1);
       
  1438     }
       
  1439 
       
  1440     /**
       
  1441      * Package private method to return bit length for an integer.
       
  1442      */
       
  1443     static int bitLengthForInt(int n) {
       
  1444         return 32 - Integer.numberOfLeadingZeros(n);
  1422     }
  1445     }
  1423 
  1446 
  1424     /**
  1447     /**
  1425      * Left shift int array a up to len by n bits. Returns the array that
  1448      * Left shift int array a up to len by n bits. Returns the array that
  1426      * results from the shift since space may have to be reallocated.
  1449      * results from the shift since space may have to be reallocated.
  1427      */
  1450      */
  1428     private static int[] leftShift(int[] a, int len, int n) {
  1451     private static int[] leftShift(int[] a, int len, int n) {
  1429         int nInts = n >>> 5;
  1452         int nInts = n >>> 5;
  1430         int nBits = n&0x1F;
  1453         int nBits = n&0x1F;
  1431         int bitsInHighWord = bitLen(a[0]);
  1454         int bitsInHighWord = bitLengthForInt(a[0]);
  1432 
  1455 
  1433         // If shift can be done without recopy, do so
  1456         // If shift can be done without recopy, do so
  1434         if (n <= (32-bitsInHighWord)) {
  1457         if (n <= (32-bitsInHighWord)) {
  1435             primitiveLeftShift(a, len, nBits);
  1458             primitiveLeftShift(a, len, nBits);
  1436             return a;
  1459             return a;
  1479     /**
  1502     /**
  1480      * Calculate bitlength of contents of the first len elements an int array,
  1503      * Calculate bitlength of contents of the first len elements an int array,
  1481      * assuming there are no leading zero ints.
  1504      * assuming there are no leading zero ints.
  1482      */
  1505      */
  1483     private static int bitLength(int[] val, int len) {
  1506     private static int bitLength(int[] val, int len) {
  1484         if (len==0)
  1507         if (len == 0)
  1485             return 0;
  1508             return 0;
  1486         return ((len-1)<<5) + bitLen(val[0]);
  1509         return ((len - 1) << 5) + bitLengthForInt(val[0]);
  1487     }
  1510     }
  1488 
  1511 
  1489     /**
  1512     /**
  1490      * Returns a BigInteger whose value is the absolute value of this
  1513      * Returns a BigInteger whose value is the absolute value of this
  1491      * BigInteger.
  1514      * BigInteger.
  1708 
  1731 
  1709         // Convert base to Montgomery form
  1732         // Convert base to Montgomery form
  1710         int[] a = leftShift(base, base.length, modLen << 5);
  1733         int[] a = leftShift(base, base.length, modLen << 5);
  1711 
  1734 
  1712         MutableBigInteger q = new MutableBigInteger(),
  1735         MutableBigInteger q = new MutableBigInteger(),
  1713                           r = new MutableBigInteger(),
       
  1714                           a2 = new MutableBigInteger(a),
  1736                           a2 = new MutableBigInteger(a),
  1715                           b2 = new MutableBigInteger(mod);
  1737                           b2 = new MutableBigInteger(mod);
  1716 
  1738 
  1717         a2.divide(b2, q, r);
  1739         MutableBigInteger r= a2.divide(b2, q);
  1718         table[0] = r.toIntArray();
  1740         table[0] = r.toIntArray();
  1719 
  1741 
  1720         // Pad table[0] with leading zeros so its length is at least modLen
  1742         // Pad table[0] with leading zeros so its length is at least modLen
  1721         if (table[0].length < modLen) {
  1743         if (table[0].length < modLen) {
  1722            int offset = modLen - table[0].length;
  1744            int offset = modLen - table[0].length;
  1974     private BigInteger mod2(int p) {
  1996     private BigInteger mod2(int p) {
  1975         if (bitLength() <= p)
  1997         if (bitLength() <= p)
  1976             return this;
  1998             return this;
  1977 
  1999 
  1978         // Copy remaining ints of mag
  2000         // Copy remaining ints of mag
  1979         int numInts = (p+31)/32;
  2001         int numInts = (p + 31) >>> 5;
  1980         int[] mag = new int[numInts];
  2002         int[] mag = new int[numInts];
  1981         for (int i=0; i<numInts; i++)
  2003         for (int i=0; i<numInts; i++)
  1982             mag[i] = this.mag[i + (this.mag.length - numInts)];
  2004             mag[i] = this.mag[i + (this.mag.length - numInts)];
  1983 
  2005 
  1984         // Mask out any excess bits
  2006         // Mask out any excess bits
  2004         if (m.equals(ONE))
  2026         if (m.equals(ONE))
  2005             return ZERO;
  2027             return ZERO;
  2006 
  2028 
  2007         // Calculate (this mod m)
  2029         // Calculate (this mod m)
  2008         BigInteger modVal = this;
  2030         BigInteger modVal = this;
  2009         if (signum < 0 || (intArrayCmp(mag, m.mag) >= 0))
  2031         if (signum < 0 || (this.compareMagnitude(m) >= 0))
  2010             modVal = this.mod(m);
  2032             modVal = this.mod(m);
  2011 
  2033 
  2012         if (modVal.equals(ONE))
  2034         if (modVal.equals(ONE))
  2013             return ONE;
  2035             return ONE;
  2014 
  2036 
  2015         MutableBigInteger a = new MutableBigInteger(modVal);
  2037         MutableBigInteger a = new MutableBigInteger(modVal);
  2016         MutableBigInteger b = new MutableBigInteger(m);
  2038         MutableBigInteger b = new MutableBigInteger(m);
  2017 
  2039 
  2018         MutableBigInteger result = a.mutableModInverse(b);
  2040         MutableBigInteger result = a.mutableModInverse(b);
  2019         return new BigInteger(result, 1);
  2041         return result.toBigInteger(1);
  2020     }
  2042     }
  2021 
  2043 
  2022     // Shift Operations
  2044     // Shift Operations
  2023 
  2045 
  2024     /**
  2046     /**
  2239      */
  2261      */
  2240     public boolean testBit(int n) {
  2262     public boolean testBit(int n) {
  2241         if (n<0)
  2263         if (n<0)
  2242             throw new ArithmeticException("Negative bit address");
  2264             throw new ArithmeticException("Negative bit address");
  2243 
  2265 
  2244         return (getInt(n/32) & (1 << (n%32))) != 0;
  2266         return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
  2245     }
  2267     }
  2246 
  2268 
  2247     /**
  2269     /**
  2248      * Returns a BigInteger whose value is equivalent to this BigInteger
  2270      * Returns a BigInteger whose value is equivalent to this BigInteger
  2249      * with the designated bit set.  (Computes {@code (this | (1<<n))}.)
  2271      * with the designated bit set.  (Computes {@code (this | (1<<n))}.)
  2254      */
  2276      */
  2255     public BigInteger setBit(int n) {
  2277     public BigInteger setBit(int n) {
  2256         if (n<0)
  2278         if (n<0)
  2257             throw new ArithmeticException("Negative bit address");
  2279             throw new ArithmeticException("Negative bit address");
  2258 
  2280 
  2259         int intNum = n/32;
  2281         int intNum = n >>> 5;
  2260         int[] result = new int[Math.max(intLength(), intNum+2)];
  2282         int[] result = new int[Math.max(intLength(), intNum+2)];
  2261 
  2283 
  2262         for (int i=0; i<result.length; i++)
  2284         for (int i=0; i<result.length; i++)
  2263             result[result.length-i-1] = getInt(i);
  2285             result[result.length-i-1] = getInt(i);
  2264 
  2286 
  2265         result[result.length-intNum-1] |= (1 << (n%32));
  2287         result[result.length-intNum-1] |= (1 << (n & 31));
  2266 
  2288 
  2267         return valueOf(result);
  2289         return valueOf(result);
  2268     }
  2290     }
  2269 
  2291 
  2270     /**
  2292     /**
  2278      */
  2300      */
  2279     public BigInteger clearBit(int n) {
  2301     public BigInteger clearBit(int n) {
  2280         if (n<0)
  2302         if (n<0)
  2281             throw new ArithmeticException("Negative bit address");
  2303             throw new ArithmeticException("Negative bit address");
  2282 
  2304 
  2283         int intNum = n/32;
  2305         int intNum = n >>> 5;
  2284         int[] result = new int[Math.max(intLength(), (n+1)/32+1)];
  2306         int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];
  2285 
  2307 
  2286         for (int i=0; i<result.length; i++)
  2308         for (int i=0; i<result.length; i++)
  2287             result[result.length-i-1] = getInt(i);
  2309             result[result.length-i-1] = getInt(i);
  2288 
  2310 
  2289         result[result.length-intNum-1] &= ~(1 << (n%32));
  2311         result[result.length-intNum-1] &= ~(1 << (n & 31));
  2290 
  2312 
  2291         return valueOf(result);
  2313         return valueOf(result);
  2292     }
  2314     }
  2293 
  2315 
  2294     /**
  2316     /**
  2302      */
  2324      */
  2303     public BigInteger flipBit(int n) {
  2325     public BigInteger flipBit(int n) {
  2304         if (n<0)
  2326         if (n<0)
  2305             throw new ArithmeticException("Negative bit address");
  2327             throw new ArithmeticException("Negative bit address");
  2306 
  2328 
  2307         int intNum = n/32;
  2329         int intNum = n >>> 5;
  2308         int[] result = new int[Math.max(intLength(), intNum+2)];
  2330         int[] result = new int[Math.max(intLength(), intNum+2)];
  2309 
  2331 
  2310         for (int i=0; i<result.length; i++)
  2332         for (int i=0; i<result.length; i++)
  2311             result[result.length-i-1] = getInt(i);
  2333             result[result.length-i-1] = getInt(i);
  2312 
  2334 
  2313         result[result.length-intNum-1] ^= (1 << (n%32));
  2335         result[result.length-intNum-1] ^= (1 << (n & 31));
  2314 
  2336 
  2315         return valueOf(result);
  2337         return valueOf(result);
  2316     }
  2338     }
  2317 
  2339 
  2318     /**
  2340     /**
  2322      * (Computes {@code (this==0? -1 : log2(this & -this))}.)
  2344      * (Computes {@code (this==0? -1 : log2(this & -this))}.)
  2323      *
  2345      *
  2324      * @return index of the rightmost one bit in this BigInteger.
  2346      * @return index of the rightmost one bit in this BigInteger.
  2325      */
  2347      */
  2326     public int getLowestSetBit() {
  2348     public int getLowestSetBit() {
  2327         /*
  2349         @SuppressWarnings("deprecation") int lsb = lowestSetBit - 2;
  2328          * Initialize lowestSetBit field the first time this method is
  2350         if (lsb == -2) {  // lowestSetBit not initialized yet
  2329          * executed. This method depends on the atomicity of int modifies;
  2351             lsb = 0;
  2330          * without this guarantee, it would have to be synchronized.
       
  2331          */
       
  2332         if (lowestSetBit == -2) {
       
  2333             if (signum == 0) {
  2352             if (signum == 0) {
  2334                 lowestSetBit = -1;
  2353                 lsb -= 1;
  2335             } else {
  2354             } else {
  2336                 // Search for lowest order nonzero int
  2355                 // Search for lowest order nonzero int
  2337                 int i,b;
  2356                 int i,b;
  2338                 for (i=0; (b = getInt(i))==0; i++)
  2357                 for (i=0; (b = getInt(i))==0; i++)
  2339                     ;
  2358                     ;
  2340                 lowestSetBit = (i << 5) + trailingZeroCnt(b);
  2359                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
  2341             }
  2360             }
  2342         }
  2361             lowestSetBit = lsb + 2;
  2343         return lowestSetBit;
  2362         }
       
  2363         return lsb;
  2344     }
  2364     }
  2345 
  2365 
  2346 
  2366 
  2347     // Miscellaneous Bit Operations
  2367     // Miscellaneous Bit Operations
  2348 
  2368 
  2355      *
  2375      *
  2356      * @return number of bits in the minimal two's-complement
  2376      * @return number of bits in the minimal two's-complement
  2357      *         representation of this BigInteger, <i>excluding</i> a sign bit.
  2377      *         representation of this BigInteger, <i>excluding</i> a sign bit.
  2358      */
  2378      */
  2359     public int bitLength() {
  2379     public int bitLength() {
  2360         /*
  2380         @SuppressWarnings("deprecation") int n = bitLength - 1;
  2361          * Initialize bitLength field the first time this method is executed.
  2381         if (n == -1) { // bitLength not initialized yet
  2362          * This method depends on the atomicity of int modifies; without
  2382             int[] m = mag;
  2363          * this guarantee, it would have to be synchronized.
  2383             int len = m.length;
  2364          */
  2384             if (len == 0) {
  2365         if (bitLength == -1) {
  2385                 n = 0; // offset by one to initialize
  2366             if (signum == 0) {
  2386             }  else {
  2367                 bitLength = 0;
       
  2368             } else {
       
  2369                 // Calculate the bit length of the magnitude
  2387                 // Calculate the bit length of the magnitude
  2370                 int magBitLength = ((mag.length-1) << 5) + bitLen(mag[0]);
  2388                 int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
  2371 
  2389                  if (signum < 0) {
  2372                 if (signum < 0) {
  2390                      // Check if magnitude is a power of two
  2373                     // Check if magnitude is a power of two
  2391                      boolean pow2 = (Integer.bitCount(mag[0]) == 1);
  2374                     boolean pow2 = (bitCnt(mag[0]) == 1);
  2392                      for(int i=1; i< len && pow2; i++)
  2375                     for(int i=1; i<mag.length && pow2; i++)
  2393                          pow2 = (mag[i] == 0);
  2376                         pow2 = (mag[i]==0);
  2394 
  2377 
  2395                      n = (pow2 ? magBitLength -1 : magBitLength);
  2378                     bitLength = (pow2 ? magBitLength-1 : magBitLength);
  2396                  } else {
  2379                 } else {
  2397                      n = magBitLength;
  2380                     bitLength = magBitLength;
  2398                  }
  2381                 }
       
  2382             }
  2399             }
  2383         }
  2400             bitLength = n + 1;
  2384         return bitLength;
  2401         }
  2385     }
  2402         return n;
  2386 
  2403     }
  2387     /**
       
  2388      * bitLen(val) is the number of bits in val.
       
  2389      */
       
  2390     static int bitLen(int w) {
       
  2391         // Binary search - decision tree (5 tests, rarely 6)
       
  2392         return
       
  2393          (w < 1<<15 ?
       
  2394           (w < 1<<7 ?
       
  2395            (w < 1<<3 ?
       
  2396             (w < 1<<1 ? (w < 1<<0 ? (w<0 ? 32 : 0) : 1) : (w < 1<<2 ? 2 : 3)) :
       
  2397             (w < 1<<5 ? (w < 1<<4 ? 4 : 5) : (w < 1<<6 ? 6 : 7))) :
       
  2398            (w < 1<<11 ?
       
  2399             (w < 1<<9 ? (w < 1<<8 ? 8 : 9) : (w < 1<<10 ? 10 : 11)) :
       
  2400             (w < 1<<13 ? (w < 1<<12 ? 12 : 13) : (w < 1<<14 ? 14 : 15)))) :
       
  2401           (w < 1<<23 ?
       
  2402            (w < 1<<19 ?
       
  2403             (w < 1<<17 ? (w < 1<<16 ? 16 : 17) : (w < 1<<18 ? 18 : 19)) :
       
  2404             (w < 1<<21 ? (w < 1<<20 ? 20 : 21) : (w < 1<<22 ? 22 : 23))) :
       
  2405            (w < 1<<27 ?
       
  2406             (w < 1<<25 ? (w < 1<<24 ? 24 : 25) : (w < 1<<26 ? 26 : 27)) :
       
  2407             (w < 1<<29 ? (w < 1<<28 ? 28 : 29) : (w < 1<<30 ? 30 : 31)))));
       
  2408     }
       
  2409 
       
  2410     /*
       
  2411      * trailingZeroTable[i] is the number of trailing zero bits in the binary
       
  2412      * representation of i.
       
  2413      */
       
  2414     final static byte trailingZeroTable[] = {
       
  2415       -25, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2416         4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2417         5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2418         4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2419         6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2420         4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2421         5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2422         4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2423         7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2424         4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2425         5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2426         4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2427         6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2428         4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2429         5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
       
  2430         4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
       
  2431 
  2404 
  2432     /**
  2405     /**
  2433      * Returns the number of bits in the two's complement representation
  2406      * Returns the number of bits in the two's complement representation
  2434      * of this BigInteger that differ from its sign bit.  This method is
  2407      * of this BigInteger that differ from its sign bit.  This method is
  2435      * useful when implementing bit-vector style sets atop BigIntegers.
  2408      * useful when implementing bit-vector style sets atop BigIntegers.
  2436      *
  2409      *
  2437      * @return number of bits in the two's complement representation
  2410      * @return number of bits in the two's complement representation
  2438      *         of this BigInteger that differ from its sign bit.
  2411      *         of this BigInteger that differ from its sign bit.
  2439      */
  2412      */
  2440     public int bitCount() {
  2413     public int bitCount() {
  2441         /*
  2414         @SuppressWarnings("deprecation") int bc = bitCount - 1;
  2442          * Initialize bitCount field the first time this method is executed.
  2415         if (bc == -1) {  // bitCount not initialized yet
  2443          * This method depends on the atomicity of int modifies; without
  2416             bc = 0;      // offset by one to initialize
  2444          * this guarantee, it would have to be synchronized.
       
  2445          */
       
  2446         if (bitCount == -1) {
       
  2447             // Count the bits in the magnitude
  2417             // Count the bits in the magnitude
  2448             int magBitCount = 0;
       
  2449             for (int i=0; i<mag.length; i++)
  2418             for (int i=0; i<mag.length; i++)
  2450                 magBitCount += bitCnt(mag[i]);
  2419                 bc += Integer.bitCount(mag[i]);
  2451 
       
  2452             if (signum < 0) {
  2420             if (signum < 0) {
  2453                 // Count the trailing zeros in the magnitude
  2421                 // Count the trailing zeros in the magnitude
  2454                 int magTrailingZeroCount = 0, j;
  2422                 int magTrailingZeroCount = 0, j;
  2455                 for (j=mag.length-1; mag[j]==0; j--)
  2423                 for (j=mag.length-1; mag[j]==0; j--)
  2456                     magTrailingZeroCount += 32;
  2424                     magTrailingZeroCount += 32;
  2457                 magTrailingZeroCount +=
  2425                 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
  2458                             trailingZeroCnt(mag[j]);
  2426                 bc += magTrailingZeroCount - 1;
  2459 
       
  2460                 bitCount = magBitCount + magTrailingZeroCount - 1;
       
  2461             } else {
       
  2462                 bitCount = magBitCount;
       
  2463             }
  2427             }
  2464         }
  2428             bitCount = bc + 1;
  2465         return bitCount;
  2429         }
  2466     }
  2430         return bc;
  2467 
       
  2468     static int bitCnt(int val) {
       
  2469         val -= (0xaaaaaaaa & val) >>> 1;
       
  2470         val = (val & 0x33333333) + ((val >>> 2) & 0x33333333);
       
  2471         val = val + (val >>> 4) & 0x0f0f0f0f;
       
  2472         val += val >>> 8;
       
  2473         val += val >>> 16;
       
  2474         return val & 0xff;
       
  2475     }
       
  2476 
       
  2477     static int trailingZeroCnt(int val) {
       
  2478         // Loop unrolled for performance
       
  2479         int byteVal = val & 0xff;
       
  2480         if (byteVal != 0)
       
  2481             return trailingZeroTable[byteVal];
       
  2482 
       
  2483         byteVal = (val >>> 8) & 0xff;
       
  2484         if (byteVal != 0)
       
  2485             return trailingZeroTable[byteVal] + 8;
       
  2486 
       
  2487         byteVal = (val >>> 16) & 0xff;
       
  2488         if (byteVal != 0)
       
  2489             return trailingZeroTable[byteVal] + 16;
       
  2490 
       
  2491         byteVal = (val >>> 24) & 0xff;
       
  2492         return trailingZeroTable[byteVal] + 24;
       
  2493     }
  2431     }
  2494 
  2432 
  2495     // Primality Testing
  2433     // Primality Testing
  2496 
  2434 
  2497     /**
  2435     /**
  2534      * @param  val BigInteger to which this BigInteger is to be compared.
  2472      * @param  val BigInteger to which this BigInteger is to be compared.
  2535      * @return -1, 0 or 1 as this BigInteger is numerically less than, equal
  2473      * @return -1, 0 or 1 as this BigInteger is numerically less than, equal
  2536      *         to, or greater than {@code val}.
  2474      *         to, or greater than {@code val}.
  2537      */
  2475      */
  2538     public int compareTo(BigInteger val) {
  2476     public int compareTo(BigInteger val) {
  2539         return (signum==val.signum
  2477         if (signum == val.signum) {
  2540                 ? signum*intArrayCmp(mag, val.mag)
  2478             switch (signum) {
  2541                 : (signum>val.signum ? 1 : -1));
  2479             case 1:
  2542     }
  2480                 return compareMagnitude(val);
  2543 
  2481             case -1:
  2544     /*
  2482                 return val.compareMagnitude(this);
  2545      * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is
  2483             default:
  2546      * less than, equal to, or greater than arg2.
  2484                 return 0;
  2547      */
  2485             }
  2548     private static int intArrayCmp(int[] arg1, int[] arg2) {
  2486         }
  2549         if (arg1.length < arg2.length)
  2487         return signum > val.signum ? 1 : -1;
       
  2488     }
       
  2489 
       
  2490     /**
       
  2491      * Compares the magnitude array of this BigInteger with the specified
       
  2492      * BigInteger's. This is the version of compareTo ignoring sign.
       
  2493      *
       
  2494      * @param val BigInteger whose magnitude array to be compared.
       
  2495      * @return -1, 0 or 1 as this magnitude array is less than, equal to or
       
  2496      *         greater than the magnitude aray for the specified BigInteger's.
       
  2497      */
       
  2498     final int compareMagnitude(BigInteger val) {
       
  2499         int[] m1 = mag;
       
  2500         int len1 = m1.length;
       
  2501         int[] m2 = val.mag;
       
  2502         int len2 = m2.length;
       
  2503         if (len1 < len2)
  2550             return -1;
  2504             return -1;
  2551         if (arg1.length > arg2.length)
  2505         if (len1 > len2)
  2552             return 1;
  2506             return 1;
  2553 
  2507         for (int i = 0; i < len1; i++) {
  2554         // Argument lengths are equal; compare the values
  2508             int a = m1[i];
  2555         for (int i=0; i<arg1.length; i++) {
  2509             int b = m2[i];
  2556             long b1 = arg1[i] & LONG_MASK;
  2510             if (a != b)
  2557             long b2 = arg2[i] & LONG_MASK;
  2511                 return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
  2558             if (b1 < b2)
       
  2559                 return -1;
       
  2560             if (b1 > b2)
       
  2561                 return 1;
       
  2562         }
  2512         }
  2563         return 0;
  2513         return 0;
  2564     }
  2514     }
  2565 
  2515 
  2566     /**
  2516     /**
  2575         if (x == this)
  2525         if (x == this)
  2576             return true;
  2526             return true;
  2577 
  2527 
  2578         if (!(x instanceof BigInteger))
  2528         if (!(x instanceof BigInteger))
  2579             return false;
  2529             return false;
       
  2530 
  2580         BigInteger xInt = (BigInteger) x;
  2531         BigInteger xInt = (BigInteger) x;
  2581 
  2532         if (xInt.signum != signum)
  2582         if (xInt.signum != signum || xInt.mag.length != mag.length)
       
  2583             return false;
  2533             return false;
  2584 
  2534 
  2585         for (int i=0; i<mag.length; i++)
  2535         int[] m = mag;
  2586             if (xInt.mag[i] != mag[i])
  2536         int len = m.length;
       
  2537         int[] xm = xInt.mag;
       
  2538         if (len != xm.length)
       
  2539             return false;
       
  2540 
       
  2541         for (int i = 0; i < len; i++)
       
  2542             if (xm[i] != m[i])
  2587                 return false;
  2543                 return false;
  2588 
  2544 
  2589         return true;
  2545         return true;
  2590     }
  2546     }
  2591 
  2547 
  2660         int numGroups = 0;
  2616         int numGroups = 0;
  2661         while (tmp.signum != 0) {
  2617         while (tmp.signum != 0) {
  2662             BigInteger d = longRadix[radix];
  2618             BigInteger d = longRadix[radix];
  2663 
  2619 
  2664             MutableBigInteger q = new MutableBigInteger(),
  2620             MutableBigInteger q = new MutableBigInteger(),
  2665                               r = new MutableBigInteger(),
       
  2666                               a = new MutableBigInteger(tmp.mag),
  2621                               a = new MutableBigInteger(tmp.mag),
  2667                               b = new MutableBigInteger(d.mag);
  2622                               b = new MutableBigInteger(d.mag);
  2668             a.divide(b, q, r);
  2623             MutableBigInteger r = a.divide(b, q);
  2669             BigInteger q2 = new BigInteger(q, tmp.signum * d.signum);
  2624             BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);
  2670             BigInteger r2 = new BigInteger(r, tmp.signum * d.signum);
  2625             BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
  2671 
  2626 
  2672             digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
  2627             digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
  2673             tmp = q2;
  2628             tmp = q2;
  2674         }
  2629         }
  2675 
  2630 
  2834 
  2789 
  2835     /**
  2790     /**
  2836      * Returns a copy of the input array stripped of any leading zero bytes.
  2791      * Returns a copy of the input array stripped of any leading zero bytes.
  2837      */
  2792      */
  2838     private static int[] stripLeadingZeroInts(int val[]) {
  2793     private static int[] stripLeadingZeroInts(int val[]) {
  2839         int byteLength = val.length;
  2794         int vlen = val.length;
  2840         int keep;
  2795         int keep;
  2841 
  2796 
  2842         // Find first nonzero byte
  2797         // Find first nonzero byte
  2843         for (keep=0; keep<val.length && val[keep]==0; keep++)
  2798         for (keep = 0; keep < vlen && val[keep] == 0; keep++)
  2844             ;
  2799             ;
  2845 
  2800         return java.util.Arrays.copyOfRange(val, keep, vlen);
  2846         int result[] = new int[val.length - keep];
       
  2847         for(int i=0; i<val.length - keep; i++)
       
  2848             result[i] = val[keep+i];
       
  2849 
       
  2850         return result;
       
  2851     }
  2801     }
  2852 
  2802 
  2853     /**
  2803     /**
  2854      * Returns the input array stripped of any leading zero bytes.
  2804      * Returns the input array stripped of any leading zero bytes.
  2855      * Since the source is trusted the copying may be skipped.
  2805      * Since the source is trusted the copying may be skipped.
  2856      */
  2806      */
  2857     private static int[] trustedStripLeadingZeroInts(int val[]) {
  2807     private static int[] trustedStripLeadingZeroInts(int val[]) {
  2858         int byteLength = val.length;
  2808         int vlen = val.length;
  2859         int keep;
  2809         int keep;
  2860 
  2810 
  2861         // Find first nonzero byte
  2811         // Find first nonzero byte
  2862         for (keep=0; keep<val.length && val[keep]==0; keep++)
  2812         for (keep = 0; keep < vlen && val[keep] == 0; keep++)
  2863             ;
  2813             ;
  2864 
  2814         return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen);
  2865         // Only perform copy if necessary
       
  2866         if (keep > 0) {
       
  2867             int result[] = new int[val.length - keep];
       
  2868             for(int i=0; i<val.length - keep; i++)
       
  2869                result[i] = val[keep+i];
       
  2870             return result;
       
  2871         }
       
  2872         return val;
       
  2873     }
  2815     }
  2874 
  2816 
  2875     /**
  2817     /**
  2876      * Returns a copy of the input array stripped of any leading zero bytes.
  2818      * Returns a copy of the input array stripped of any leading zero bytes.
  2877      */
  2819      */
  2878     private static int[] stripLeadingZeroBytes(byte a[]) {
  2820     private static int[] stripLeadingZeroBytes(byte a[]) {
  2879         int byteLength = a.length;
  2821         int byteLength = a.length;
  2880         int keep;
  2822         int keep;
  2881 
  2823 
  2882         // Find first nonzero byte
  2824         // Find first nonzero byte
  2883         for (keep=0; keep<a.length && a[keep]==0; keep++)
  2825         for (keep = 0; keep < byteLength && a[keep]==0; keep++)
  2884             ;
  2826             ;
  2885 
  2827 
  2886         // Allocate new array and copy relevant part of input array
  2828         // Allocate new array and copy relevant part of input array
  2887         int intLength = ((byteLength - keep) + 3)/4;
  2829         int intLength = ((byteLength - keep) + 3) >>> 2;
  2888         int[] result = new int[intLength];
  2830         int[] result = new int[intLength];
  2889         int b = byteLength - 1;
  2831         int b = byteLength - 1;
  2890         for (int i = intLength-1; i >= 0; i--) {
  2832         for (int i = intLength-1; i >= 0; i--) {
  2891             result[i] = a[b--] & 0xff;
  2833             result[i] = a[b--] & 0xff;
  2892             int bytesRemaining = b - keep + 1;
  2834             int bytesRemaining = b - keep + 1;
  2893             int bytesToTransfer = Math.min(3, bytesRemaining);
  2835             int bytesToTransfer = Math.min(3, bytesRemaining);
  2894             for (int j=8; j <= 8*bytesToTransfer; j += 8)
  2836             for (int j=8; j <= (bytesToTransfer << 3); j += 8)
  2895                 result[i] |= ((a[b--] & 0xff) << j);
  2837                 result[i] |= ((a[b--] & 0xff) << j);
  2896         }
  2838         }
  2897         return result;
  2839         return result;
  2898     }
  2840     }
  2899 
  2841 
  3035     /**
  2977     /**
  3036      * Returns the length of the two's complement representation in ints,
  2978      * Returns the length of the two's complement representation in ints,
  3037      * including space for at least one sign bit.
  2979      * including space for at least one sign bit.
  3038      */
  2980      */
  3039     private int intLength() {
  2981     private int intLength() {
  3040         return bitLength()/32 + 1;
  2982         return (bitLength() >>> 5) + 1;
  3041     }
  2983     }
  3042 
  2984 
  3043     /* Returns sign bit */
  2985     /* Returns sign bit */
  3044     private int signBit() {
  2986     private int signBit() {
  3045         return signum < 0 ? 1 : 0;
  2987         return signum < 0 ? 1 : 0;
  3072      * Returns the index of the int that contains the first nonzero int in the
  3014      * Returns the index of the int that contains the first nonzero int in the
  3073      * little-endian binary representation of the magnitude (int 0 is the
  3015      * little-endian binary representation of the magnitude (int 0 is the
  3074      * least significant). If the magnitude is zero, return value is undefined.
  3016      * least significant). If the magnitude is zero, return value is undefined.
  3075      */
  3017      */
  3076      private int firstNonzeroIntNum() {
  3018      private int firstNonzeroIntNum() {
  3077         /*
  3019          int fn = firstNonzeroIntNum - 2;
  3078          * Initialize firstNonzeroIntNum field the first time this method is
  3020          if (fn == -2) { // firstNonzeroIntNum not initialized yet
  3079          * executed. This method depends on the atomicity of int modifies;
  3021              fn = 0;
  3080          * without this guarantee, it would have to be synchronized.
  3022 
  3081          */
  3023              // Search for the first nonzero int
  3082         if (firstNonzeroIntNum == -2) {
  3024              int i;
  3083             // Search for the first nonzero int
  3025              int mlen = mag.length;
  3084             int i;
  3026              for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
  3085             for (i=mag.length-1; i>=0 && mag[i]==0; i--)
  3027                  ;
  3086                 ;
  3028              fn = mlen - i - 1;
  3087             firstNonzeroIntNum = mag.length-i-1;
  3029              firstNonzeroIntNum = fn + 2; // offset by two to initialize
  3088         }
  3030          }
  3089         return firstNonzeroIntNum;
  3031          return fn;
  3090     }
  3032      }
  3091 
  3033 
  3092     /** use serialVersionUID from JDK 1.1. for interoperability */
  3034     /** use serialVersionUID from JDK 1.1. for interoperability */
  3093     private static final long serialVersionUID = -8287574255936472291L;
  3035     private static final long serialVersionUID = -8287574255936472291L;
  3094 
  3036 
  3095     /**
  3037     /**
  3119     /**
  3061     /**
  3120      * Reconstitute the {@code BigInteger} instance from a stream (that is,
  3062      * Reconstitute the {@code BigInteger} instance from a stream (that is,
  3121      * deserialize it). The magnitude is read in as an array of bytes
  3063      * deserialize it). The magnitude is read in as an array of bytes
  3122      * for historical reasons, but it is converted to an array of ints
  3064      * for historical reasons, but it is converted to an array of ints
  3123      * and the byte array is discarded.
  3065      * and the byte array is discarded.
       
  3066      * Note:
       
  3067      * The current convention is to initialize the cache fields, bitCount,
       
  3068      * bitLength and lowestSetBit, to 0 rather than some other marker value.
       
  3069      * Therefore, no explicit action to set these fields needs to be taken in
       
  3070      * readObject because those fields already have a 0 value be default since
       
  3071      * defaultReadObject is not being used.
  3124      */
  3072      */
  3125     private void readObject(java.io.ObjectInputStream s)
  3073     private void readObject(java.io.ObjectInputStream s)
  3126         throws java.io.IOException, ClassNotFoundException {
  3074         throws java.io.IOException, ClassNotFoundException {
  3127         /*
  3075         /*
  3128          * In order to maintain compatibility with previous serialized forms,
  3076          * In order to maintain compatibility with previous serialized forms,
  3134 
  3082 
  3135         // prepare to read the alternate persistent fields
  3083         // prepare to read the alternate persistent fields
  3136         ObjectInputStream.GetField fields = s.readFields();
  3084         ObjectInputStream.GetField fields = s.readFields();
  3137 
  3085 
  3138         // Read the alternate persistent fields that we care about
  3086         // Read the alternate persistent fields that we care about
  3139         signum = fields.get("signum", -2);
  3087         int sign = fields.get("signum", -2);
  3140         byte[] magnitude = (byte[])fields.get("magnitude", null);
  3088         byte[] magnitude = (byte[])fields.get("magnitude", null);
  3141 
  3089 
  3142         // Validate signum
  3090         // Validate signum
  3143         if (signum < -1 || signum > 1) {
  3091         if (sign < -1 || sign > 1) {
  3144             String message = "BigInteger: Invalid signum value";
  3092             String message = "BigInteger: Invalid signum value";
  3145             if (fields.defaulted("signum"))
  3093             if (fields.defaulted("signum"))
  3146                 message = "BigInteger: Signum not present in stream";
  3094                 message = "BigInteger: Signum not present in stream";
  3147             throw new java.io.StreamCorruptedException(message);
  3095             throw new java.io.StreamCorruptedException(message);
  3148         }
  3096         }
  3149         if ((magnitude.length==0) != (signum==0)) {
  3097         if ((magnitude.length == 0) != (sign == 0)) {
  3150             String message = "BigInteger: signum-magnitude mismatch";
  3098             String message = "BigInteger: signum-magnitude mismatch";
  3151             if (fields.defaulted("magnitude"))
  3099             if (fields.defaulted("magnitude"))
  3152                 message = "BigInteger: Magnitude not present in stream";
  3100                 message = "BigInteger: Magnitude not present in stream";
  3153             throw new java.io.StreamCorruptedException(message);
  3101             throw new java.io.StreamCorruptedException(message);
  3154         }
  3102         }
  3155 
  3103 
  3156         // Set "cached computation" fields to their initial values
  3104         // Commit final fields via Unsafe
  3157         bitCount = bitLength = -1;
  3105         unsafe.putIntVolatile(this, signumOffset, sign);
  3158         lowestSetBit = firstNonzeroByteNum = firstNonzeroIntNum = -2;
       
  3159 
  3106 
  3160         // Calculate mag field from magnitude and discard magnitude
  3107         // Calculate mag field from magnitude and discard magnitude
  3161         mag = stripLeadingZeroBytes(magnitude);
  3108         unsafe.putObjectVolatile(this, magOffset,
       
  3109                                  stripLeadingZeroBytes(magnitude));
       
  3110     }
       
  3111 
       
  3112     // Support for resetting final fields while deserializing
       
  3113     private static final sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
       
  3114     private static final long signumOffset;
       
  3115     private static final long magOffset;
       
  3116     static {
       
  3117         try {
       
  3118             signumOffset = unsafe.objectFieldOffset
       
  3119                 (BigInteger.class.getDeclaredField("signum"));
       
  3120             magOffset = unsafe.objectFieldOffset
       
  3121                 (BigInteger.class.getDeclaredField("mag"));
       
  3122         } catch (Exception ex) {
       
  3123             throw new Error(ex);
       
  3124         }
  3162     }
  3125     }
  3163 
  3126 
  3164     /**
  3127     /**
  3165      * Save the {@code BigInteger} instance to a stream.
  3128      * Save the {@code BigInteger} instance to a stream.
  3166      * The magnitude of a BigInteger is serialized as a byte array for
  3129      * The magnitude of a BigInteger is serialized as a byte array for
  3172     private void writeObject(ObjectOutputStream s) throws IOException {
  3135     private void writeObject(ObjectOutputStream s) throws IOException {
  3173         // set the values of the Serializable fields
  3136         // set the values of the Serializable fields
  3174         ObjectOutputStream.PutField fields = s.putFields();
  3137         ObjectOutputStream.PutField fields = s.putFields();
  3175         fields.put("signum", signum);
  3138         fields.put("signum", signum);
  3176         fields.put("magnitude", magSerializedForm());
  3139         fields.put("magnitude", magSerializedForm());
       
  3140         // The values written for cached fields are compatible with older
       
  3141         // versions, but are ignored in readObject so don't otherwise matter.
  3177         fields.put("bitCount", -1);
  3142         fields.put("bitCount", -1);
  3178         fields.put("bitLength", -1);
  3143         fields.put("bitLength", -1);
  3179         fields.put("lowestSetBit", -2);
  3144         fields.put("lowestSetBit", -2);
  3180         fields.put("firstNonzeroByteNum", -2);
  3145         fields.put("firstNonzeroByteNum", -2);
  3181 
  3146 
  3185 
  3150 
  3186     /**
  3151     /**
  3187      * Returns the mag array as an array of bytes.
  3152      * Returns the mag array as an array of bytes.
  3188      */
  3153      */
  3189     private byte[] magSerializedForm() {
  3154     private byte[] magSerializedForm() {
  3190         int bitLen = (mag.length == 0 ? 0 :
  3155         int len = mag.length;
  3191                       ((mag.length - 1) << 5) + bitLen(mag[0]));
  3156 
  3192         int byteLen = (bitLen + 7)/8;
  3157         int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0]));
       
  3158         int byteLen = (bitLen + 7) >>> 3;
  3193         byte[] result = new byte[byteLen];
  3159         byte[] result = new byte[byteLen];
  3194 
  3160 
  3195         for (int i=byteLen-1, bytesCopied=4, intIndex=mag.length-1, nextInt=0;
  3161         for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;
  3196              i>=0; i--) {
  3162              i>=0; i--) {
  3197             if (bytesCopied == 4) {
  3163             if (bytesCopied == 4) {
  3198                 nextInt = mag[intIndex--];
  3164                 nextInt = mag[intIndex--];
  3199                 bytesCopied = 1;
  3165                 bytesCopied = 1;
  3200             } else {
  3166             } else {