src/java.base/share/classes/java/math/BigInteger.java
changeset 53327 620b31ed8807
parent 52220 9c260a6b6471
child 57956 e0b8b019d2f5
equal deleted inserted replaced
53326:0060e9d7c450 53327:620b31ed8807
   305      * @since 9
   305      * @since 9
   306      */
   306      */
   307     public BigInteger(byte[] val, int off, int len) {
   307     public BigInteger(byte[] val, int off, int len) {
   308         if (val.length == 0) {
   308         if (val.length == 0) {
   309             throw new NumberFormatException("Zero length BigInteger");
   309             throw new NumberFormatException("Zero length BigInteger");
   310         } else if ((off < 0) || (off >= val.length) || (len < 0) ||
   310         }
   311                    (len > val.length - off)) { // 0 <= off < val.length
   311         Objects.checkFromIndexSize(off, len, val.length);
   312             throw new IndexOutOfBoundsException();
       
   313         }
       
   314 
   312 
   315         if (val[off] < 0) {
   313         if (val[off] < 0) {
   316             mag = makePositive(val, off, len);
   314             mag = makePositive(val, off, len);
   317             signum = -1;
   315             signum = -1;
   318         } else {
   316         } else {
   393      * @since 9
   391      * @since 9
   394      */
   392      */
   395     public BigInteger(int signum, byte[] magnitude, int off, int len) {
   393     public BigInteger(int signum, byte[] magnitude, int off, int len) {
   396         if (signum < -1 || signum > 1) {
   394         if (signum < -1 || signum > 1) {
   397             throw(new NumberFormatException("Invalid signum value"));
   395             throw(new NumberFormatException("Invalid signum value"));
   398         } else if ((off < 0) || (len < 0) ||
   396         }
   399             (len > 0 &&
   397         Objects.checkFromIndexSize(off, len, magnitude.length);
   400                 ((off >= magnitude.length) ||
       
   401                  (len > magnitude.length - off)))) { // 0 <= off < magnitude.length
       
   402             throw new IndexOutOfBoundsException();
       
   403         }
       
   404 
   398 
   405         // stripLeadingZeroBytes() returns a zero length array if len == 0
   399         // stripLeadingZeroBytes() returns a zero length array if len == 0
   406         this.mag = stripLeadingZeroBytes(magnitude, off, len);
   400         this.mag = stripLeadingZeroBytes(magnitude, off, len);
   407 
   401 
   408         if (this.mag.length == 0) {
   402         if (this.mag.length == 0) {
  1237 
  1231 
  1238     /** The natural log of 2.  This is used in computing cache indices. */
  1232     /** The natural log of 2.  This is used in computing cache indices. */
  1239     private static final double LOG_TWO = Math.log(2.0);
  1233     private static final double LOG_TWO = Math.log(2.0);
  1240 
  1234 
  1241     static {
  1235     static {
       
  1236         assert 0 < KARATSUBA_THRESHOLD
       
  1237             && KARATSUBA_THRESHOLD < TOOM_COOK_THRESHOLD
       
  1238             && TOOM_COOK_THRESHOLD < Integer.MAX_VALUE
       
  1239             && 0 < KARATSUBA_SQUARE_THRESHOLD
       
  1240             && KARATSUBA_SQUARE_THRESHOLD < TOOM_COOK_SQUARE_THRESHOLD
       
  1241             && TOOM_COOK_SQUARE_THRESHOLD < Integer.MAX_VALUE :
       
  1242             "Algorithm thresholds are inconsistent";
       
  1243 
  1242         for (int i = 1; i <= MAX_CONSTANT; i++) {
  1244         for (int i = 1; i <= MAX_CONSTANT; i++) {
  1243             int[] magnitude = new int[1];
  1245             int[] magnitude = new int[1];
  1244             magnitude[0] = i;
  1246             magnitude[0] = i;
  1245             posConst[i] = new BigInteger(magnitude,  1);
  1247             posConst[i] = new BigInteger(magnitude,  1);
  1246             negConst[i] = new BigInteger(magnitude, -1);
  1248             negConst[i] = new BigInteger(magnitude, -1);
  1560      *
  1562      *
  1561      * @param  val value to be multiplied by this BigInteger.
  1563      * @param  val value to be multiplied by this BigInteger.
  1562      * @return {@code this * val}
  1564      * @return {@code this * val}
  1563      */
  1565      */
  1564     public BigInteger multiply(BigInteger val) {
  1566     public BigInteger multiply(BigInteger val) {
       
  1567         return multiply(val, false);
       
  1568     }
       
  1569 
       
  1570     /**
       
  1571      * Returns a BigInteger whose value is {@code (this * val)}.  If
       
  1572      * the invocation is recursive certain overflow checks are skipped.
       
  1573      *
       
  1574      * @param  val value to be multiplied by this BigInteger.
       
  1575      * @param  isRecursion whether this is a recursive invocation
       
  1576      * @return {@code this * val}
       
  1577      */
       
  1578     private BigInteger multiply(BigInteger val, boolean isRecursion) {
  1565         if (val.signum == 0 || signum == 0)
  1579         if (val.signum == 0 || signum == 0)
  1566             return ZERO;
  1580             return ZERO;
  1567 
  1581 
  1568         int xlen = mag.length;
  1582         int xlen = mag.length;
  1569 
  1583 
  1587             return new BigInteger(result, resultSign);
  1601             return new BigInteger(result, resultSign);
  1588         } else {
  1602         } else {
  1589             if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {
  1603             if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {
  1590                 return multiplyKaratsuba(this, val);
  1604                 return multiplyKaratsuba(this, val);
  1591             } else {
  1605             } else {
       
  1606                 //
       
  1607                 // In "Hacker's Delight" section 2-13, p.33, it is explained
       
  1608                 // that if x and y are unsigned 32-bit quantities and m and n
       
  1609                 // are their respective numbers of leading zeros within 32 bits,
       
  1610                 // then the number of leading zeros within their product as a
       
  1611                 // 64-bit unsigned quantity is either m + n or m + n + 1. If
       
  1612                 // their product is not to overflow, it cannot exceed 32 bits,
       
  1613                 // and so the number of leading zeros of the product within 64
       
  1614                 // bits must be at least 32, i.e., the leftmost set bit is at
       
  1615                 // zero-relative position 31 or less.
       
  1616                 //
       
  1617                 // From the above there are three cases:
       
  1618                 //
       
  1619                 //     m + n    leftmost set bit    condition
       
  1620                 //     -----    ----------------    ---------
       
  1621                 //     >= 32    x <= 64 - 32 = 32   no overflow
       
  1622                 //     == 31    x >= 64 - 32 = 32   possible overflow
       
  1623                 //     <= 30    x >= 64 - 31 = 33   definite overflow
       
  1624                 //
       
  1625                 // The "possible overflow" condition cannot be detected by
       
  1626                 // examning data lengths alone and requires further calculation.
       
  1627                 //
       
  1628                 // By analogy, if 'this' and 'val' have m and n as their
       
  1629                 // respective numbers of leading zeros within 32*MAX_MAG_LENGTH
       
  1630                 // bits, then:
       
  1631                 //
       
  1632                 //     m + n >= 32*MAX_MAG_LENGTH        no overflow
       
  1633                 //     m + n == 32*MAX_MAG_LENGTH - 1    possible overflow
       
  1634                 //     m + n <= 32*MAX_MAG_LENGTH - 2    definite overflow
       
  1635                 //
       
  1636                 // Note however that if the number of ints in the result
       
  1637                 // were to be MAX_MAG_LENGTH and mag[0] < 0, then there would
       
  1638                 // be overflow. As a result the leftmost bit (of mag[0]) cannot
       
  1639                 // be used and the constraints must be adjusted by one bit to:
       
  1640                 //
       
  1641                 //     m + n >  32*MAX_MAG_LENGTH        no overflow
       
  1642                 //     m + n == 32*MAX_MAG_LENGTH        possible overflow
       
  1643                 //     m + n <  32*MAX_MAG_LENGTH        definite overflow
       
  1644                 //
       
  1645                 // The foregoing leading zero-based discussion is for clarity
       
  1646                 // only. The actual calculations use the estimated bit length
       
  1647                 // of the product as this is more natural to the internal
       
  1648                 // array representation of the magnitude which has no leading
       
  1649                 // zero elements.
       
  1650                 //
       
  1651                 if (!isRecursion) {
       
  1652                     // The bitLength() instance method is not used here as we
       
  1653                     // are only considering the magnitudes as non-negative. The
       
  1654                     // Toom-Cook multiplication algorithm determines the sign
       
  1655                     // at its end from the two signum values.
       
  1656                     if (bitLength(mag, mag.length) +
       
  1657                         bitLength(val.mag, val.mag.length) >
       
  1658                         32L*MAX_MAG_LENGTH) {
       
  1659                         reportOverflow();
       
  1660                     }
       
  1661                 }
       
  1662 
  1592                 return multiplyToomCook3(this, val);
  1663                 return multiplyToomCook3(this, val);
  1593             }
  1664             }
  1594         }
  1665         }
  1595     }
  1666     }
  1596 
  1667 
  1672     private static int[] implMultiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
  1743     private static int[] implMultiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
  1673         int xstart = xlen - 1;
  1744         int xstart = xlen - 1;
  1674         int ystart = ylen - 1;
  1745         int ystart = ylen - 1;
  1675 
  1746 
  1676         if (z == null || z.length < (xlen+ ylen))
  1747         if (z == null || z.length < (xlen+ ylen))
  1677             z = new int[xlen+ylen];
  1748              z = new int[xlen+ylen];
  1678 
  1749 
  1679         long carry = 0;
  1750         long carry = 0;
  1680         for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {
  1751         for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {
  1681             long product = (y[j] & LONG_MASK) *
  1752             long product = (y[j] & LONG_MASK) *
  1682                            (x[xstart] & LONG_MASK) + carry;
  1753                            (x[xstart] & LONG_MASK) + carry;
  1806         b1 = b.getToomSlice(k, r, 1, largest);
  1877         b1 = b.getToomSlice(k, r, 1, largest);
  1807         b0 = b.getToomSlice(k, r, 2, largest);
  1878         b0 = b.getToomSlice(k, r, 2, largest);
  1808 
  1879 
  1809         BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
  1880         BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
  1810 
  1881 
  1811         v0 = a0.multiply(b0);
  1882         v0 = a0.multiply(b0, true);
  1812         da1 = a2.add(a0);
  1883         da1 = a2.add(a0);
  1813         db1 = b2.add(b0);
  1884         db1 = b2.add(b0);
  1814         vm1 = da1.subtract(a1).multiply(db1.subtract(b1));
  1885         vm1 = da1.subtract(a1).multiply(db1.subtract(b1), true);
  1815         da1 = da1.add(a1);
  1886         da1 = da1.add(a1);
  1816         db1 = db1.add(b1);
  1887         db1 = db1.add(b1);
  1817         v1 = da1.multiply(db1);
  1888         v1 = da1.multiply(db1, true);
  1818         v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
  1889         v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
  1819              db1.add(b2).shiftLeft(1).subtract(b0));
  1890              db1.add(b2).shiftLeft(1).subtract(b0), true);
  1820         vinf = a2.multiply(b2);
  1891         vinf = a2.multiply(b2, true);
  1821 
  1892 
  1822         // The algorithm requires two divisions by 2 and one by 3.
  1893         // The algorithm requires two divisions by 2 and one by 3.
  1823         // All divisions are known to be exact, that is, they do not produce
  1894         // All divisions are known to be exact, that is, they do not produce
  1824         // remainders, and all results are positive.  The divisions by 2 are
  1895         // remainders, and all results are positive.  The divisions by 2 are
  1825         // implemented as right shifts which are relatively efficient, leaving
  1896         // implemented as right shifts which are relatively efficient, leaving
  1981      * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.
  2052      * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.
  1982      *
  2053      *
  1983      * @return {@code this<sup>2</sup>}
  2054      * @return {@code this<sup>2</sup>}
  1984      */
  2055      */
  1985     private BigInteger square() {
  2056     private BigInteger square() {
       
  2057         return square(false);
       
  2058     }
       
  2059 
       
  2060     /**
       
  2061      * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}. If
       
  2062      * the invocation is recursive certain overflow checks are skipped.
       
  2063      *
       
  2064      * @param isRecursion whether this is a recursive invocation
       
  2065      * @return {@code this<sup>2</sup>}
       
  2066      */
       
  2067     private BigInteger square(boolean isRecursion) {
  1986         if (signum == 0) {
  2068         if (signum == 0) {
  1987             return ZERO;
  2069             return ZERO;
  1988         }
  2070         }
  1989         int len = mag.length;
  2071         int len = mag.length;
  1990 
  2072 
  1993             return new BigInteger(trustedStripLeadingZeroInts(z), 1);
  2075             return new BigInteger(trustedStripLeadingZeroInts(z), 1);
  1994         } else {
  2076         } else {
  1995             if (len < TOOM_COOK_SQUARE_THRESHOLD) {
  2077             if (len < TOOM_COOK_SQUARE_THRESHOLD) {
  1996                 return squareKaratsuba();
  2078                 return squareKaratsuba();
  1997             } else {
  2079             } else {
       
  2080                 //
       
  2081                 // For a discussion of overflow detection see multiply()
       
  2082                 //
       
  2083                 if (!isRecursion) {
       
  2084                     if (bitLength(mag, mag.length) > 16L*MAX_MAG_LENGTH) {
       
  2085                         reportOverflow();
       
  2086                     }
       
  2087                 }
       
  2088 
  1998                 return squareToomCook3();
  2089                 return squareToomCook3();
  1999             }
  2090             }
  2000         }
  2091         }
  2001     }
  2092     }
  2002 
  2093 
  2144         a2 = getToomSlice(k, r, 0, len);
  2235         a2 = getToomSlice(k, r, 0, len);
  2145         a1 = getToomSlice(k, r, 1, len);
  2236         a1 = getToomSlice(k, r, 1, len);
  2146         a0 = getToomSlice(k, r, 2, len);
  2237         a0 = getToomSlice(k, r, 2, len);
  2147         BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
  2238         BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
  2148 
  2239 
  2149         v0 = a0.square();
  2240         v0 = a0.square(true);
  2150         da1 = a2.add(a0);
  2241         da1 = a2.add(a0);
  2151         vm1 = da1.subtract(a1).square();
  2242         vm1 = da1.subtract(a1).square(true);
  2152         da1 = da1.add(a1);
  2243         da1 = da1.add(a1);
  2153         v1 = da1.square();
  2244         v1 = da1.square(true);
  2154         vinf = a2.square();
  2245         vinf = a2.square(true);
  2155         v2 = da1.add(a2).shiftLeft(1).subtract(a0).square();
  2246         v2 = da1.add(a2).shiftLeft(1).subtract(a0).square(true);
  2156 
  2247 
  2157         // The algorithm requires two divisions by 2 and one by 3.
  2248         // The algorithm requires two divisions by 2 and one by 3.
  2158         // All divisions are known to be exact, that is, they do not produce
  2249         // All divisions are known to be exact, that is, they do not produce
  2159         // remainders, and all results are positive.  The divisions by 2 are
  2250         // remainders, and all results are positive.  The divisions by 2 are
  2160         // implemented as right shifts which are relatively efficient, leaving
  2251         // implemented as right shifts which are relatively efficient, leaving
  2321         // Factor out powers of two from the base, as the exponentiation of
  2412         // Factor out powers of two from the base, as the exponentiation of
  2322         // these can be done by left shifts only.
  2413         // these can be done by left shifts only.
  2323         // The remaining part can then be exponentiated faster.  The
  2414         // The remaining part can then be exponentiated faster.  The
  2324         // powers of two will be multiplied back at the end.
  2415         // powers of two will be multiplied back at the end.
  2325         int powersOfTwo = partToSquare.getLowestSetBit();
  2416         int powersOfTwo = partToSquare.getLowestSetBit();
  2326         long bitsToShift = (long)powersOfTwo * exponent;
  2417         long bitsToShiftLong = (long)powersOfTwo * exponent;
  2327         if (bitsToShift > Integer.MAX_VALUE) {
  2418         if (bitsToShiftLong > Integer.MAX_VALUE) {
  2328             reportOverflow();
  2419             reportOverflow();
  2329         }
  2420         }
       
  2421         int bitsToShift = (int)bitsToShiftLong;
  2330 
  2422 
  2331         int remainingBits;
  2423         int remainingBits;
  2332 
  2424 
  2333         // Factor the powers of two out quickly by shifting right, if needed.
  2425         // Factor the powers of two out quickly by shifting right, if needed.
  2334         if (powersOfTwo > 0) {
  2426         if (powersOfTwo > 0) {
  2335             partToSquare = partToSquare.shiftRight(powersOfTwo);
  2427             partToSquare = partToSquare.shiftRight(powersOfTwo);
  2336             remainingBits = partToSquare.bitLength();
  2428             remainingBits = partToSquare.bitLength();
  2337             if (remainingBits == 1) {  // Nothing left but +/- 1?
  2429             if (remainingBits == 1) {  // Nothing left but +/- 1?
  2338                 if (signum < 0 && (exponent&1) == 1) {
  2430                 if (signum < 0 && (exponent&1) == 1) {
  2339                     return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent);
  2431                     return NEGATIVE_ONE.shiftLeft(bitsToShift);
  2340                 } else {
  2432                 } else {
  2341                     return ONE.shiftLeft(powersOfTwo*exponent);
  2433                     return ONE.shiftLeft(bitsToShift);
  2342                 }
  2434                 }
  2343             }
  2435             }
  2344         } else {
  2436         } else {
  2345             remainingBits = partToSquare.bitLength();
  2437             remainingBits = partToSquare.bitLength();
  2346             if (remainingBits == 1) { // Nothing left but +/- 1?
  2438             if (remainingBits == 1) { // Nothing left but +/- 1?
  2381             // Multiply back the powers of two (quickly, by shifting left)
  2473             // Multiply back the powers of two (quickly, by shifting left)
  2382             if (powersOfTwo > 0) {
  2474             if (powersOfTwo > 0) {
  2383                 if (bitsToShift + scaleFactor <= 62) { // Fits in long?
  2475                 if (bitsToShift + scaleFactor <= 62) { // Fits in long?
  2384                     return valueOf((result << bitsToShift) * newSign);
  2476                     return valueOf((result << bitsToShift) * newSign);
  2385                 } else {
  2477                 } else {
  2386                     return valueOf(result*newSign).shiftLeft((int) bitsToShift);
  2478                     return valueOf(result*newSign).shiftLeft(bitsToShift);
  2387                 }
  2479                 }
  2388             }
  2480             } else {
  2389             else {
       
  2390                 return valueOf(result*newSign);
  2481                 return valueOf(result*newSign);
  2391             }
  2482             }
  2392         } else {
  2483         } else {
       
  2484             if ((long)bitLength() * exponent / Integer.SIZE > MAX_MAG_LENGTH) {
       
  2485                 reportOverflow();
       
  2486             }
       
  2487 
  2393             // Large number algorithm.  This is basically identical to
  2488             // Large number algorithm.  This is basically identical to
  2394             // the algorithm above, but calls multiply() and square()
  2489             // the algorithm above, but calls multiply() and square()
  2395             // which may use more efficient algorithms for large numbers.
  2490             // which may use more efficient algorithms for large numbers.
  2396             BigInteger answer = ONE;
  2491             BigInteger answer = ONE;
  2397 
  2492 
  2407                 }
  2502                 }
  2408             }
  2503             }
  2409             // Multiply back the (exponentiated) powers of two (quickly,
  2504             // Multiply back the (exponentiated) powers of two (quickly,
  2410             // by shifting left)
  2505             // by shifting left)
  2411             if (powersOfTwo > 0) {
  2506             if (powersOfTwo > 0) {
  2412                 answer = answer.shiftLeft(powersOfTwo*exponent);
  2507                 answer = answer.shiftLeft(bitsToShift);
  2413             }
  2508             }
  2414 
  2509 
  2415             if (signum < 0 && (exponent&1) == 1) {
  2510             if (signum < 0 && (exponent&1) == 1) {
  2416                 return answer.negate();
  2511                 return answer.negate();
  2417             } else {
  2512             } else {
  3582                      // Check if magnitude is a power of two
  3677                      // Check if magnitude is a power of two
  3583                      boolean pow2 = (Integer.bitCount(mag[0]) == 1);
  3678                      boolean pow2 = (Integer.bitCount(mag[0]) == 1);
  3584                      for (int i=1; i< len && pow2; i++)
  3679                      for (int i=1; i< len && pow2; i++)
  3585                          pow2 = (mag[i] == 0);
  3680                          pow2 = (mag[i] == 0);
  3586 
  3681 
  3587                      n = (pow2 ? magBitLength -1 : magBitLength);
  3682                      n = (pow2 ? magBitLength - 1 : magBitLength);
  3588                  } else {
  3683                  } else {
  3589                      n = magBitLength;
  3684                      n = magBitLength;
  3590                  }
  3685                  }
  3591             }
  3686             }
  3592             bitLengthPlusOne = n + 1;
  3687             bitLengthPlusOne = n + 1;