jdk/src/share/classes/java/math/BigInteger.java
changeset 23332 c36c4773fe96
parent 22042 98541fec9c62
child 24367 705490680527
equal deleted inserted replaced
23331:f2a3a7c9ed66 23332:c36c4773fe96
   124     /**
   124     /**
   125      * The signum of this BigInteger: -1 for negative, 0 for zero, or
   125      * The signum of this BigInteger: -1 for negative, 0 for zero, or
   126      * 1 for positive.  Note that the BigInteger zero <i>must</i> have
   126      * 1 for positive.  Note that the BigInteger zero <i>must</i> have
   127      * a signum of 0.  This is necessary to ensures that there is exactly one
   127      * a signum of 0.  This is necessary to ensures that there is exactly one
   128      * representation for each BigInteger value.
   128      * representation for each BigInteger value.
   129      *
       
   130      * @serial
       
   131      */
   129      */
   132     final int signum;
   130     final int signum;
   133 
   131 
   134     /**
   132     /**
   135      * The magnitude of this BigInteger, in <i>big-endian</i> order: the
   133      * The magnitude of this BigInteger, in <i>big-endian</i> order: the
   140      * value.  Note that this implies that the BigInteger zero has a
   138      * value.  Note that this implies that the BigInteger zero has a
   141      * zero-length mag array.
   139      * zero-length mag array.
   142      */
   140      */
   143     final int[] mag;
   141     final int[] mag;
   144 
   142 
   145     // These "redundant fields" are initialized with recognizable nonsense
   143     // The following fields are stable variables. A stable variable's value
   146     // values, and cached the first time they are needed (or never, if they
   144     // changes at most once from the default zero value to a non-zero stable
   147     // aren't needed).
   145     // value. A stable value is calculated lazily on demand.
   148 
   146 
   149      /**
   147     /**
   150      * One plus the bitCount of this BigInteger. Zeros means unitialized.
   148      * One plus the bitCount of this BigInteger. This is a stable variable.
   151      *
   149      *
   152      * @serial
       
   153      * @see #bitCount
   150      * @see #bitCount
   154      * @deprecated Deprecated since logical value is offset from stored
   151      */
   155      * value and correction factor is applied in accessor method.
   152     private int bitCountPlusOne;
   156      */
   153 
   157     @Deprecated
   154     /**
   158     private int bitCount;
   155      * One plus the bitLength of this BigInteger. This is a stable variable.
   159 
       
   160     /**
       
   161      * One plus the bitLength of this BigInteger. Zeros means unitialized.
       
   162      * (either value is acceptable).
   156      * (either value is acceptable).
   163      *
   157      *
   164      * @serial
       
   165      * @see #bitLength()
   158      * @see #bitLength()
   166      * @deprecated Deprecated since logical value is offset from stored
   159      */
   167      * value and correction factor is applied in accessor method.
   160     private int bitLengthPlusOne;
   168      */
   161 
   169     @Deprecated
   162     /**
   170     private int bitLength;
   163      * Two plus the lowest set bit of this BigInteger. This is a stable variable.
   171 
   164      *
   172     /**
       
   173      * Two plus the lowest set bit of this BigInteger, as returned by
       
   174      * getLowestSetBit().
       
   175      *
       
   176      * @serial
       
   177      * @see #getLowestSetBit
   165      * @see #getLowestSetBit
   178      * @deprecated Deprecated since logical value is offset from stored
   166      */
   179      * value and correction factor is applied in accessor method.
   167     private int lowestSetBitPlusTwo;
   180      */
       
   181     @Deprecated
       
   182     private int lowestSetBit;
       
   183 
   168 
   184     /**
   169     /**
   185      * Two plus the index of the lowest-order int in the magnitude of this
   170      * Two plus the index of the lowest-order int in the magnitude of this
   186      * BigInteger that contains a nonzero int, or -2 (either value is acceptable).
   171      * BigInteger that contains a nonzero int. This is a stable variable. The
   187      * The least significant int has int-number 0, the next int in order of
   172      * least significant int has int-number 0, the next int in order of
   188      * increasing significance has int-number 1, and so forth.
   173      * increasing significance has int-number 1, and so forth.
   189      * @deprecated Deprecated since logical value is offset from stored
   174      *
   190      * value and correction factor is applied in accessor method.
   175      * <p>Note: never used for a BigInteger with a magnitude of zero.
   191      */
   176      *
   192     @Deprecated
   177      * @see #firstNonzeroIntNum()
   193     private int firstNonzeroIntNum;
   178      */
       
   179     private int firstNonzeroIntNumPlusTwo;
   194 
   180 
   195     /**
   181     /**
   196      * This mask is used to obtain the value of an int as if it were unsigned.
   182      * This mask is used to obtain the value of an int as if it were unsigned.
   197      */
   183      */
   198     final static long LONG_MASK = 0xffffffffL;
   184     final static long LONG_MASK = 0xffffffffL;
  3238      * (Computes {@code (this == 0? -1 : log2(this & -this))}.)
  3224      * (Computes {@code (this == 0? -1 : log2(this & -this))}.)
  3239      *
  3225      *
  3240      * @return index of the rightmost one bit in this BigInteger.
  3226      * @return index of the rightmost one bit in this BigInteger.
  3241      */
  3227      */
  3242     public int getLowestSetBit() {
  3228     public int getLowestSetBit() {
  3243         @SuppressWarnings("deprecation") int lsb = lowestSetBit - 2;
  3229         int lsb = lowestSetBitPlusTwo - 2;
  3244         if (lsb == -2) {  // lowestSetBit not initialized yet
  3230         if (lsb == -2) {  // lowestSetBit not initialized yet
  3245             lsb = 0;
  3231             lsb = 0;
  3246             if (signum == 0) {
  3232             if (signum == 0) {
  3247                 lsb -= 1;
  3233                 lsb -= 1;
  3248             } else {
  3234             } else {
  3250                 int i,b;
  3236                 int i,b;
  3251                 for (i=0; (b = getInt(i)) == 0; i++)
  3237                 for (i=0; (b = getInt(i)) == 0; i++)
  3252                     ;
  3238                     ;
  3253                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
  3239                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
  3254             }
  3240             }
  3255             lowestSetBit = lsb + 2;
  3241             lowestSetBitPlusTwo = lsb + 2;
  3256         }
  3242         }
  3257         return lsb;
  3243         return lsb;
  3258     }
  3244     }
  3259 
  3245 
  3260 
  3246 
  3269      *
  3255      *
  3270      * @return number of bits in the minimal two's-complement
  3256      * @return number of bits in the minimal two's-complement
  3271      *         representation of this BigInteger, <i>excluding</i> a sign bit.
  3257      *         representation of this BigInteger, <i>excluding</i> a sign bit.
  3272      */
  3258      */
  3273     public int bitLength() {
  3259     public int bitLength() {
  3274         @SuppressWarnings("deprecation") int n = bitLength - 1;
  3260         int n = bitLengthPlusOne - 1;
  3275         if (n == -1) { // bitLength not initialized yet
  3261         if (n == -1) { // bitLength not initialized yet
  3276             int[] m = mag;
  3262             int[] m = mag;
  3277             int len = m.length;
  3263             int len = m.length;
  3278             if (len == 0) {
  3264             if (len == 0) {
  3279                 n = 0; // offset by one to initialize
  3265                 n = 0; // offset by one to initialize
  3289                      n = (pow2 ? magBitLength -1 : magBitLength);
  3275                      n = (pow2 ? magBitLength -1 : magBitLength);
  3290                  } else {
  3276                  } else {
  3291                      n = magBitLength;
  3277                      n = magBitLength;
  3292                  }
  3278                  }
  3293             }
  3279             }
  3294             bitLength = n + 1;
  3280             bitLengthPlusOne = n + 1;
  3295         }
  3281         }
  3296         return n;
  3282         return n;
  3297     }
  3283     }
  3298 
  3284 
  3299     /**
  3285     /**
  3303      *
  3289      *
  3304      * @return number of bits in the two's complement representation
  3290      * @return number of bits in the two's complement representation
  3305      *         of this BigInteger that differ from its sign bit.
  3291      *         of this BigInteger that differ from its sign bit.
  3306      */
  3292      */
  3307     public int bitCount() {
  3293     public int bitCount() {
  3308         @SuppressWarnings("deprecation") int bc = bitCount - 1;
  3294         int bc = bitCountPlusOne - 1;
  3309         if (bc == -1) {  // bitCount not initialized yet
  3295         if (bc == -1) {  // bitCount not initialized yet
  3310             bc = 0;      // offset by one to initialize
  3296             bc = 0;      // offset by one to initialize
  3311             // Count the bits in the magnitude
  3297             // Count the bits in the magnitude
  3312             for (int i=0; i < mag.length; i++)
  3298             for (int i=0; i < mag.length; i++)
  3313                 bc += Integer.bitCount(mag[i]);
  3299                 bc += Integer.bitCount(mag[i]);
  3317                 for (j=mag.length-1; mag[j] == 0; j--)
  3303                 for (j=mag.length-1; mag[j] == 0; j--)
  3318                     magTrailingZeroCount += 32;
  3304                     magTrailingZeroCount += 32;
  3319                 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
  3305                 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
  3320                 bc += magTrailingZeroCount - 1;
  3306                 bc += magTrailingZeroCount - 1;
  3321             }
  3307             }
  3322             bitCount = bc + 1;
  3308             bitCountPlusOne = bc + 1;
  3323         }
  3309         }
  3324         return bc;
  3310         return bc;
  3325     }
  3311     }
  3326 
  3312 
  3327     // Primality Testing
  3313     // Primality Testing
  3620      * @param radix  The base to convert to.
  3606      * @param radix  The base to convert to.
  3621      * @param digits The minimum number of digits to pad to.
  3607      * @param digits The minimum number of digits to pad to.
  3622      */
  3608      */
  3623     private static void toString(BigInteger u, StringBuilder sb, int radix,
  3609     private static void toString(BigInteger u, StringBuilder sb, int radix,
  3624                                  int digits) {
  3610                                  int digits) {
  3625         /* If we're smaller than a certain threshold, use the smallToString
  3611         // If we're smaller than a certain threshold, use the smallToString
  3626            method, padding with leading zeroes when necessary. */
  3612         // method, padding with leading zeroes when necessary.
  3627         if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
  3613         if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
  3628             String s = u.smallToString(radix);
  3614             String s = u.smallToString(radix);
  3629 
  3615 
  3630             // Pad with internal zeros if necessary.
  3616             // Pad with internal zeros if necessary.
  3631             // Don't pad if we're at the beginning of the string.
  3617             // Don't pad if we're at the beginning of the string.
  3632             if ((s.length() < digits) && (sb.length() > 0)) {
  3618             if ((s.length() < digits) && (sb.length() > 0)) {
  3633                 for (int i=s.length(); i < digits; i++) { // May be a faster way to
  3619                 for (int i=s.length(); i < digits; i++) {
  3634                     sb.append('0');                    // do this?
  3620                     sb.append('0');
  3635                 }
  3621                 }
  3636             }
  3622             }
  3637 
  3623 
  3638             sb.append(s);
  3624             sb.append(s);
  3639             return;
  3625             return;
  4183         return (signum >= 0 ? magInt :
  4169         return (signum >= 0 ? magInt :
  4184                 (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
  4170                 (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
  4185     }
  4171     }
  4186 
  4172 
  4187     /**
  4173     /**
  4188      * Returns the index of the int that contains the first nonzero int in the
  4174     * Returns the index of the int that contains the first nonzero int in the
  4189      * little-endian binary representation of the magnitude (int 0 is the
  4175     * little-endian binary representation of the magnitude (int 0 is the
  4190      * least significant). If the magnitude is zero, return value is undefined.
  4176     * least significant). If the magnitude is zero, return value is undefined.
  4191      */
  4177     *
       
  4178     * <p>Note: never used for a BigInteger with a magnitude of zero.
       
  4179     * @see #getInt.
       
  4180     */
  4192     private int firstNonzeroIntNum() {
  4181     private int firstNonzeroIntNum() {
  4193         int fn = firstNonzeroIntNum - 2;
  4182         int fn = firstNonzeroIntNumPlusTwo - 2;
  4194         if (fn == -2) { // firstNonzeroIntNum not initialized yet
  4183         if (fn == -2) { // firstNonzeroIntNum not initialized yet
  4195             fn = 0;
       
  4196 
       
  4197             // Search for the first nonzero int
  4184             // Search for the first nonzero int
  4198             int i;
  4185             int i;
  4199             int mlen = mag.length;
  4186             int mlen = mag.length;
  4200             for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
  4187             for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
  4201                 ;
  4188                 ;
  4202             fn = mlen - i - 1;
  4189             fn = mlen - i - 1;
  4203             firstNonzeroIntNum = fn + 2; // offset by two to initialize
  4190             firstNonzeroIntNumPlusTwo = fn + 2; // offset by two to initialize
  4204         }
  4191         }
  4205         return fn;
  4192         return fn;
  4206     }
  4193     }
  4207 
  4194 
  4208     /** use serialVersionUID from JDK 1.1. for interoperability */
  4195     /** use serialVersionUID from JDK 1.1. for interoperability */
  4210 
  4197 
  4211     /**
  4198     /**
  4212      * Serializable fields for BigInteger.
  4199      * Serializable fields for BigInteger.
  4213      *
  4200      *
  4214      * @serialField signum  int
  4201      * @serialField signum  int
  4215      *              signum of this BigInteger.
  4202      *              signum of this BigInteger
  4216      * @serialField magnitude int[]
  4203      * @serialField magnitude byte[]
  4217      *              magnitude array of this BigInteger.
  4204      *              magnitude array of this BigInteger
  4218      * @serialField bitCount  int
  4205      * @serialField bitCount  int
  4219      *              number of bits in this BigInteger
  4206      *              appears in the serialized form for backward compatibility
  4220      * @serialField bitLength int
  4207      * @serialField bitLength int
  4221      *              the number of bits in the minimal two's-complement
  4208      *              appears in the serialized form for backward compatibility
  4222      *              representation of this BigInteger
  4209      * @serialField firstNonzeroByteNum int
       
  4210      *              appears in the serialized form for backward compatibility
  4223      * @serialField lowestSetBit int
  4211      * @serialField lowestSetBit int
  4224      *              lowest set bit in the twos complement representation
  4212      *              appears in the serialized form for backward compatibility
  4225      */
  4213      */
  4226     private static final ObjectStreamField[] serialPersistentFields = {
  4214     private static final ObjectStreamField[] serialPersistentFields = {
  4227         new ObjectStreamField("signum", Integer.TYPE),
  4215         new ObjectStreamField("signum", Integer.TYPE),
  4228         new ObjectStreamField("magnitude", byte[].class),
  4216         new ObjectStreamField("magnitude", byte[].class),
  4229         new ObjectStreamField("bitCount", Integer.TYPE),
  4217         new ObjectStreamField("bitCount", Integer.TYPE),
  4236      * Reconstitute the {@code BigInteger} instance from a stream (that is,
  4224      * Reconstitute the {@code BigInteger} instance from a stream (that is,
  4237      * deserialize it). The magnitude is read in as an array of bytes
  4225      * deserialize it). The magnitude is read in as an array of bytes
  4238      * for historical reasons, but it is converted to an array of ints
  4226      * for historical reasons, but it is converted to an array of ints
  4239      * and the byte array is discarded.
  4227      * and the byte array is discarded.
  4240      * Note:
  4228      * Note:
  4241      * The current convention is to initialize the cache fields, bitCount,
  4229      * The current convention is to initialize the cache fields, bitCountPlusOne,
  4242      * bitLength and lowestSetBit, to 0 rather than some other marker value.
  4230      * bitLengthPlusOne and lowestSetBitPlusTwo, to 0 rather than some other
  4243      * Therefore, no explicit action to set these fields needs to be taken in
  4231      * marker value. Therefore, no explicit action to set these fields needs to
  4244      * readObject because those fields already have a 0 value be default since
  4232      * be taken in readObject because those fields already have a 0 value by
  4245      * defaultReadObject is not being used.
  4233      * default since defaultReadObject is not being used.
  4246      */
  4234      */
  4247     private void readObject(java.io.ObjectInputStream s)
  4235     private void readObject(java.io.ObjectInputStream s)
  4248         throws java.io.IOException, ClassNotFoundException {
  4236         throws java.io.IOException, ClassNotFoundException {
  4249         /*
       
  4250          * In order to maintain compatibility with previous serialized forms,
       
  4251          * the magnitude of a BigInteger is serialized as an array of bytes.
       
  4252          * The magnitude field is used as a temporary store for the byte array
       
  4253          * that is deserialized. The cached computation fields should be
       
  4254          * transient but are serialized for compatibility reasons.
       
  4255          */
       
  4256 
       
  4257         // prepare to read the alternate persistent fields
  4237         // prepare to read the alternate persistent fields
  4258         ObjectInputStream.GetField fields = s.readFields();
  4238         ObjectInputStream.GetField fields = s.readFields();
  4259 
  4239 
  4260         // Read the alternate persistent fields that we care about
  4240         // Read the alternate persistent fields that we care about
  4261         int sign = fields.get("signum", -2);
  4241         int sign = fields.get("signum", -2);
  4315             unsafe.putObjectVolatile(bi, magOffset, magnitude);
  4295             unsafe.putObjectVolatile(bi, magOffset, magnitude);
  4316         }
  4296         }
  4317     }
  4297     }
  4318 
  4298 
  4319     /**
  4299     /**
  4320      * Save the {@code BigInteger} instance to a stream.
  4300      * Save the {@code BigInteger} instance to a stream.  The magnitude of a
  4321      * The magnitude of a BigInteger is serialized as a byte array for
  4301      * {@code BigInteger} is serialized as a byte array for historical reasons.
  4322      * historical reasons.
  4302      * To maintain compatibility with older implementations, the integers
  4323      *
  4303      * -1, -1, -2, and -2 are written as the values of the obsolete fields
  4324      * @serialData two necessary fields are written as well as obsolete
  4304      * {@code bitCount}, {@code bitLength}, {@code lowestSetBit}, and
  4325      *             fields for compatibility with older versions.
  4305      * {@code firstNonzeroByteNum}, respectively.  These values are compatible
       
  4306      * with older implementations, but will be ignored by current
       
  4307      * implementations.
  4326      */
  4308      */
  4327     private void writeObject(ObjectOutputStream s) throws IOException {
  4309     private void writeObject(ObjectOutputStream s) throws IOException {
  4328         // set the values of the Serializable fields
  4310         // set the values of the Serializable fields
  4329         ObjectOutputStream.PutField fields = s.putFields();
  4311         ObjectOutputStream.PutField fields = s.putFields();
  4330         fields.put("signum", signum);
  4312         fields.put("signum", signum);
  4336         fields.put("lowestSetBit", -2);
  4318         fields.put("lowestSetBit", -2);
  4337         fields.put("firstNonzeroByteNum", -2);
  4319         fields.put("firstNonzeroByteNum", -2);
  4338 
  4320 
  4339         // save them
  4321         // save them
  4340         s.writeFields();
  4322         s.writeFields();
  4341 }
  4323     }
  4342 
  4324 
  4343     /**
  4325     /**
  4344      * Returns the mag array as an array of bytes.
  4326      * Returns the mag array as an array of bytes.
  4345      */
  4327      */
  4346     private byte[] magSerializedForm() {
  4328     private byte[] magSerializedForm() {