jdk/src/share/classes/java/math/BigInteger.java
changeset 18286 b38489d5aadf
parent 10588 d8173a78bdca
child 18538 642cc17315fd
equal deleted inserted replaced
18285:dc840ac75e93 18286:b38489d5aadf
     1 /*
     1 /*
     2  * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
     2  * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     7  * published by the Free Software Foundation.  Oracle designates this
    27  * Portions Copyright (c) 1995  Colin Plumb.  All rights reserved.
    27  * Portions Copyright (c) 1995  Colin Plumb.  All rights reserved.
    28  */
    28  */
    29 
    29 
    30 package java.math;
    30 package java.math;
    31 
    31 
       
    32 import java.io.IOException;
       
    33 import java.io.ObjectInputStream;
       
    34 import java.io.ObjectOutputStream;
       
    35 import java.io.ObjectStreamField;
       
    36 import java.util.Arrays;
    32 import java.util.Random;
    37 import java.util.Random;
    33 import java.io.*;
       
    34 import java.util.Arrays;
       
    35 
    38 
    36 /**
    39 /**
    37  * Immutable arbitrary-precision integers.  All operations behave as if
    40  * Immutable arbitrary-precision integers.  All operations behave as if
    38  * BigIntegers were represented in two's-complement notation (like Java's
    41  * BigIntegers were represented in two's-complement notation (like Java's
    39  * primitive integer types).  BigInteger provides analogues to all of Java's
    42  * primitive integer types).  BigInteger provides analogues to all of Java's
    92  * a null object reference for any input parameter.
    95  * a null object reference for any input parameter.
    93  *
    96  *
    94  * @see     BigDecimal
    97  * @see     BigDecimal
    95  * @author  Josh Bloch
    98  * @author  Josh Bloch
    96  * @author  Michael McCloskey
    99  * @author  Michael McCloskey
       
   100  * @author  Alan Eliasen
    97  * @since JDK1.1
   101  * @since JDK1.1
    98  */
   102  */
    99 
   103 
   100 public class BigInteger extends Number implements Comparable<BigInteger> {
   104 public class BigInteger extends Number implements Comparable<BigInteger> {
   101     /**
   105     /**
   171 
   175 
   172     /**
   176     /**
   173      * This mask is used to obtain the value of an int as if it were unsigned.
   177      * This mask is used to obtain the value of an int as if it were unsigned.
   174      */
   178      */
   175     final static long LONG_MASK = 0xffffffffL;
   179     final static long LONG_MASK = 0xffffffffL;
       
   180 
       
   181     /**
       
   182      * The threshold value for using Karatsuba multiplication.  If the number
       
   183      * of ints in both mag arrays are greater than this number, then
       
   184      * Karatsuba multiplication will be used.   This value is found
       
   185      * experimentally to work well.
       
   186      */
       
   187     private static final int KARATSUBA_THRESHOLD = 50;
       
   188 
       
   189     /**
       
   190      * The threshold value for using 3-way Toom-Cook multiplication.
       
   191      * If the number of ints in each mag array is greater than the
       
   192      * Karatsuba threshold, and the number of ints in at least one of
       
   193      * the mag arrays is greater than this threshold, then Toom-Cook
       
   194      * multiplication will be used.
       
   195      */
       
   196     private static final int TOOM_COOK_THRESHOLD = 75;
       
   197 
       
   198     /**
       
   199      * The threshold value for using Karatsuba squaring.  If the number
       
   200      * of ints in the number are larger than this value,
       
   201      * Karatsuba squaring will be used.   This value is found
       
   202      * experimentally to work well.
       
   203      */
       
   204     private static final int KARATSUBA_SQUARE_THRESHOLD = 90;
       
   205 
       
   206     /**
       
   207      * The threshold value for using Toom-Cook squaring.  If the number
       
   208      * of ints in the number are larger than this value,
       
   209      * Toom-Cook squaring will be used.   This value is found
       
   210      * experimentally to work well.
       
   211      */
       
   212     private static final int TOOM_COOK_SQUARE_THRESHOLD = 140;
   176 
   213 
   177     //Constructors
   214     //Constructors
   178 
   215 
   179     /**
   216     /**
   180      * Translates a byte array containing the two's-complement binary
   217      * Translates a byte array containing the two's-complement binary
   520     public BigInteger(int bitLength, int certainty, Random rnd) {
   557     public BigInteger(int bitLength, int certainty, Random rnd) {
   521         BigInteger prime;
   558         BigInteger prime;
   522 
   559 
   523         if (bitLength < 2)
   560         if (bitLength < 2)
   524             throw new ArithmeticException("bitLength < 2");
   561             throw new ArithmeticException("bitLength < 2");
   525         // The cutoff of 95 was chosen empirically for best performance
   562         prime = (bitLength < SMALL_PRIME_THRESHOLD
   526         prime = (bitLength < 95 ? smallPrime(bitLength, certainty, rnd)
   563                                 ? smallPrime(bitLength, certainty, rnd)
   527                                 : largePrime(bitLength, certainty, rnd));
   564                                 : largePrime(bitLength, certainty, rnd));
   528         signum = 1;
   565         signum = 1;
   529         mag = prime.mag;
   566         mag = prime.mag;
   530     }
   567     }
   531 
   568 
   532     // Minimum size in bits that the requested prime number has
   569     // Minimum size in bits that the requested prime number has
   533     // before we use the large prime number generating algorithms
   570     // before we use the large prime number generating algorithms.
       
   571     // The cutoff of 95 was chosen empirically for best performance.
   534     private static final int SMALL_PRIME_THRESHOLD = 95;
   572     private static final int SMALL_PRIME_THRESHOLD = 95;
   535 
   573 
   536     // Certainty required to meet the spec of probablePrime
   574     // Certainty required to meet the spec of probablePrime
   537     private static final int DEFAULT_PRIME_CERTAINTY = 100;
   575     private static final int DEFAULT_PRIME_CERTAINTY = 100;
   538 
   576 
   551      */
   589      */
   552     public static BigInteger probablePrime(int bitLength, Random rnd) {
   590     public static BigInteger probablePrime(int bitLength, Random rnd) {
   553         if (bitLength < 2)
   591         if (bitLength < 2)
   554             throw new ArithmeticException("bitLength < 2");
   592             throw new ArithmeticException("bitLength < 2");
   555 
   593 
   556         // The cutoff of 95 was chosen empirically for best performance
       
   557         return (bitLength < SMALL_PRIME_THRESHOLD ?
   594         return (bitLength < SMALL_PRIME_THRESHOLD ?
   558                 smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
   595                 smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
   559                 largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
   596                 largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
   560     }
   597     }
   561 
   598 
   984      * Initialize static constant array when class is loaded.
  1021      * Initialize static constant array when class is loaded.
   985      */
  1022      */
   986     private final static int MAX_CONSTANT = 16;
  1023     private final static int MAX_CONSTANT = 16;
   987     private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
  1024     private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
   988     private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
  1025     private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
       
  1026 
   989     static {
  1027     static {
   990         for (int i = 1; i <= MAX_CONSTANT; i++) {
  1028         for (int i = 1; i <= MAX_CONSTANT; i++) {
   991             int[] magnitude = new int[1];
  1029             int[] magnitude = new int[1];
   992             magnitude[0] = i;
  1030             magnitude[0] = i;
   993             posConst[i] = new BigInteger(magnitude,  1);
  1031             posConst[i] = new BigInteger(magnitude,  1);
  1011 
  1049 
  1012     /**
  1050     /**
  1013      * The BigInteger constant two.  (Not exported.)
  1051      * The BigInteger constant two.  (Not exported.)
  1014      */
  1052      */
  1015     private static final BigInteger TWO = valueOf(2);
  1053     private static final BigInteger TWO = valueOf(2);
       
  1054 
       
  1055     /**
       
  1056      * The BigInteger constant -1.  (Not exported.)
       
  1057      */
       
  1058     private static final BigInteger NEGATIVE_ONE = valueOf(-1);
  1016 
  1059 
  1017     /**
  1060     /**
  1018      * The BigInteger constant ten.
  1061      * The BigInteger constant ten.
  1019      *
  1062      *
  1020      * @since   1.5
  1063      * @since   1.5
  1288      * @return {@code this * val}
  1331      * @return {@code this * val}
  1289      */
  1332      */
  1290     public BigInteger multiply(BigInteger val) {
  1333     public BigInteger multiply(BigInteger val) {
  1291         if (val.signum == 0 || signum == 0)
  1334         if (val.signum == 0 || signum == 0)
  1292             return ZERO;
  1335             return ZERO;
  1293         int resultSign = signum == val.signum ? 1 : -1;
  1336 
  1294         if (val.mag.length == 1) {
  1337         int xlen = mag.length;
  1295             return  multiplyByInt(mag,val.mag[0], resultSign);
  1338         int ylen = val.mag.length;
  1296         }
  1339 
  1297         if(mag.length == 1) {
  1340         if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD))
  1298             return multiplyByInt(val.mag,mag[0], resultSign);
  1341         {
  1299         }
  1342             int resultSign = signum == val.signum ? 1 : -1;
  1300         int[] result = multiplyToLen(mag, mag.length,
  1343             if (val.mag.length == 1) {
  1301                                      val.mag, val.mag.length, null);
  1344                 return multiplyByInt(mag,val.mag[0], resultSign);
  1302         result = trustedStripLeadingZeroInts(result);
  1345             }
  1303         return new BigInteger(result, resultSign);
  1346             if(mag.length == 1) {
       
  1347                 return multiplyByInt(val.mag,mag[0], resultSign);
       
  1348             }
       
  1349             int[] result = multiplyToLen(mag, xlen,
       
  1350                                          val.mag, ylen, null);
       
  1351             result = trustedStripLeadingZeroInts(result);
       
  1352             return new BigInteger(result, resultSign);
       
  1353         }
       
  1354         else
       
  1355             if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD))
       
  1356                 return multiplyKaratsuba(this, val);
       
  1357             else
       
  1358                return multiplyToomCook3(this, val);
  1304     }
  1359     }
  1305 
  1360 
  1306     private static BigInteger multiplyByInt(int[] x, int y, int sign) {
  1361     private static BigInteger multiplyByInt(int[] x, int y, int sign) {
  1307         if(Integer.bitCount(y)==1) {
  1362         if(Integer.bitCount(y)==1) {
  1308             return new BigInteger(shiftLeft(x,Integer.numberOfTrailingZeros(y)), sign);
  1363             return new BigInteger(shiftLeft(x,Integer.numberOfTrailingZeros(y)), sign);
  1400         }
  1455         }
  1401         return z;
  1456         return z;
  1402     }
  1457     }
  1403 
  1458 
  1404     /**
  1459     /**
       
  1460      * Multiplies two BigIntegers using the Karatsuba multiplication
       
  1461      * algorithm.  This is a recursive divide-and-conquer algorithm which is
       
  1462      * more efficient for large numbers than what is commonly called the
       
  1463      * "grade-school" algorithm used in multiplyToLen.  If the numbers to be
       
  1464      * multiplied have length n, the "grade-school" algorithm has an
       
  1465      * asymptotic complexity of O(n^2).  In contrast, the Karatsuba algorithm
       
  1466      * has complexity of O(n^(log2(3))), or O(n^1.585).  It achieves this
       
  1467      * increased performance by doing 3 multiplies instead of 4 when
       
  1468      * evaluating the product.  As it has some overhead, should be used when
       
  1469      * both numbers are larger than a certain threshold (found
       
  1470      * experimentally).
       
  1471      *
       
  1472      * See:  http://en.wikipedia.org/wiki/Karatsuba_algorithm
       
  1473      */
       
  1474     private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y)
       
  1475     {
       
  1476         int xlen = x.mag.length;
       
  1477         int ylen = y.mag.length;
       
  1478 
       
  1479         // The number of ints in each half of the number.
       
  1480         int half = (Math.max(xlen, ylen)+1) / 2;
       
  1481 
       
  1482         // xl and yl are the lower halves of x and y respectively,
       
  1483         // xh and yh are the upper halves.
       
  1484         BigInteger xl = x.getLower(half);
       
  1485         BigInteger xh = x.getUpper(half);
       
  1486         BigInteger yl = y.getLower(half);
       
  1487         BigInteger yh = y.getUpper(half);
       
  1488 
       
  1489         BigInteger p1 = xh.multiply(yh);  // p1 = xh*yh
       
  1490         BigInteger p2 = xl.multiply(yl);  // p2 = xl*yl
       
  1491 
       
  1492         // p3=(xh+xl)*(yh+yl)
       
  1493         BigInteger p3 = xh.add(xl).multiply(yh.add(yl));
       
  1494 
       
  1495         // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2
       
  1496         BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2);
       
  1497 
       
  1498         if (x.signum != y.signum)
       
  1499             return result.negate();
       
  1500         else
       
  1501             return result;
       
  1502     }
       
  1503 
       
  1504     /**
       
  1505      * Multiplies two BigIntegers using a 3-way Toom-Cook multiplication
       
  1506      * algorithm.  This is a recursive divide-and-conquer algorithm which is
       
  1507      * more efficient for large numbers than what is commonly called the
       
  1508      * "grade-school" algorithm used in multiplyToLen.  If the numbers to be
       
  1509      * multiplied have length n, the "grade-school" algorithm has an
       
  1510      * asymptotic complexity of O(n^2).  In contrast, 3-way Toom-Cook has a
       
  1511      * complexity of about O(n^1.465).  It achieves this increased asymptotic
       
  1512      * performance by breaking each number into three parts and by doing 5
       
  1513      * multiplies instead of 9 when evaluating the product.  Due to overhead
       
  1514      * (additions, shifts, and one division) in the Toom-Cook algorithm, it
       
  1515      * should only be used when both numbers are larger than a certain
       
  1516      * threshold (found experimentally).  This threshold is generally larger
       
  1517      * than that for Karatsuba multiplication, so this algorithm is generally
       
  1518      * only used when numbers become significantly larger.
       
  1519      *
       
  1520      * The algorithm used is the "optimal" 3-way Toom-Cook algorithm outlined
       
  1521      * by Marco Bodrato.
       
  1522      *
       
  1523      *  See: http://bodrato.it/toom-cook/
       
  1524      *       http://bodrato.it/papers/#WAIFI2007
       
  1525      *
       
  1526      * "Towards Optimal Toom-Cook Multiplication for Univariate and
       
  1527      * Multivariate Polynomials in Characteristic 2 and 0." by Marco BODRATO;
       
  1528      * In C.Carlet and B.Sunar, Eds., "WAIFI'07 proceedings", p. 116-133,
       
  1529      * LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007.
       
  1530      *
       
  1531      */
       
  1532     private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b)
       
  1533     {
       
  1534         int alen = a.mag.length;
       
  1535         int blen = b.mag.length;
       
  1536 
       
  1537         int largest = Math.max(alen, blen);
       
  1538 
       
  1539         // k is the size (in ints) of the lower-order slices.
       
  1540         int k = (largest+2)/3;   // Equal to ceil(largest/3)
       
  1541 
       
  1542         // r is the size (in ints) of the highest-order slice.
       
  1543         int r = largest - 2*k;
       
  1544 
       
  1545         // Obtain slices of the numbers. a2 and b2 are the most significant
       
  1546         // bits of the numbers a and b, and a0 and b0 the least significant.
       
  1547         BigInteger a0, a1, a2, b0, b1, b2;
       
  1548         a2 = a.getToomSlice(k, r, 0, largest);
       
  1549         a1 = a.getToomSlice(k, r, 1, largest);
       
  1550         a0 = a.getToomSlice(k, r, 2, largest);
       
  1551         b2 = b.getToomSlice(k, r, 0, largest);
       
  1552         b1 = b.getToomSlice(k, r, 1, largest);
       
  1553         b0 = b.getToomSlice(k, r, 2, largest);
       
  1554 
       
  1555         BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
       
  1556 
       
  1557         v0 = a0.multiply(b0);
       
  1558         da1 = a2.add(a0);
       
  1559         db1 = b2.add(b0);
       
  1560         vm1 = da1.subtract(a1).multiply(db1.subtract(b1));
       
  1561         da1 = da1.add(a1);
       
  1562         db1 = db1.add(b1);
       
  1563         v1 = da1.multiply(db1);
       
  1564         v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
       
  1565              db1.add(b2).shiftLeft(1).subtract(b0));
       
  1566         vinf = a2.multiply(b2);
       
  1567 
       
  1568         /* The algorithm requires two divisions by 2 and one by 3.
       
  1569            All divisions are known to be exact, that is, they do not produce
       
  1570            remainders, and all results are positive.  The divisions by 2 are
       
  1571            implemented as right shifts which are relatively efficient, leaving
       
  1572            only an exact division by 3, which is done by a specialized
       
  1573            linear-time algorithm. */
       
  1574         t2 = v2.subtract(vm1).exactDivideBy3();
       
  1575         tm1 = v1.subtract(vm1).shiftRight(1);
       
  1576         t1 = v1.subtract(v0);
       
  1577         t2 = t2.subtract(t1).shiftRight(1);
       
  1578         t1 = t1.subtract(tm1).subtract(vinf);
       
  1579         t2 = t2.subtract(vinf.shiftLeft(1));
       
  1580         tm1 = tm1.subtract(t2);
       
  1581 
       
  1582         // Number of bits to shift left.
       
  1583         int ss = k*32;
       
  1584 
       
  1585         BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
       
  1586 
       
  1587         if (a.signum != b.signum)
       
  1588             return result.negate();
       
  1589         else
       
  1590             return result;
       
  1591     }
       
  1592 
       
  1593 
       
  1594     /**
       
  1595      * Returns a slice of a BigInteger for use in Toom-Cook multiplication.
       
  1596      *
       
  1597      * @param lowerSize The size of the lower-order bit slices.
       
  1598      * @param upperSize The size of the higher-order bit slices.
       
  1599      * @param slice The index of which slice is requested, which must be a
       
  1600      * number from 0 to size-1. Slice 0 is the highest-order bits, and slice
       
  1601      * size-1 are the lowest-order bits. Slice 0 may be of different size than
       
  1602      * the other slices.
       
  1603      * @param fullsize The size of the larger integer array, used to align
       
  1604      * slices to the appropriate position when multiplying different-sized
       
  1605      * numbers.
       
  1606      */
       
  1607     private BigInteger getToomSlice(int lowerSize, int upperSize, int slice,
       
  1608                                     int fullsize)
       
  1609     {
       
  1610         int start, end, sliceSize, len, offset;
       
  1611 
       
  1612         len = mag.length;
       
  1613         offset = fullsize - len;
       
  1614 
       
  1615         if (slice == 0)
       
  1616         {
       
  1617             start = 0 - offset;
       
  1618             end = upperSize - 1 - offset;
       
  1619         }
       
  1620         else
       
  1621         {
       
  1622             start = upperSize + (slice-1)*lowerSize - offset;
       
  1623             end = start + lowerSize - 1;
       
  1624         }
       
  1625 
       
  1626         if (start < 0)
       
  1627             start = 0;
       
  1628         if (end < 0)
       
  1629            return ZERO;
       
  1630 
       
  1631         sliceSize = (end-start) + 1;
       
  1632 
       
  1633         if (sliceSize <= 0)
       
  1634             return ZERO;
       
  1635 
       
  1636         // While performing Toom-Cook, all slices are positive and
       
  1637         // the sign is adjusted when the final number is composed.
       
  1638         if (start==0 && sliceSize >= len)
       
  1639             return this.abs();
       
  1640 
       
  1641         int intSlice[] = new int[sliceSize];
       
  1642         System.arraycopy(mag, start, intSlice, 0, sliceSize);
       
  1643 
       
  1644         return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1);
       
  1645     }
       
  1646 
       
  1647     /**
       
  1648      * Does an exact division (that is, the remainder is known to be zero)
       
  1649      * of the specified number by 3.  This is used in Toom-Cook
       
  1650      * multiplication.  This is an efficient algorithm that runs in linear
       
  1651      * time.  If the argument is not exactly divisible by 3, results are
       
  1652      * undefined.  Note that this is expected to be called with positive
       
  1653      * arguments only.
       
  1654      */
       
  1655     private BigInteger exactDivideBy3()
       
  1656     {
       
  1657         int len = mag.length;
       
  1658         int[] result = new int[len];
       
  1659         long x, w, q, borrow;
       
  1660         borrow = 0L;
       
  1661         for (int i=len-1; i>=0; i--)
       
  1662         {
       
  1663             x = (mag[i] & LONG_MASK);
       
  1664             w = x - borrow;
       
  1665             if (borrow > x)       // Did we make the number go negative?
       
  1666                 borrow = 1L;
       
  1667             else
       
  1668                 borrow = 0L;
       
  1669 
       
  1670             // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32).  Thus,
       
  1671             // the effect of this is to divide by 3 (mod 2^32).
       
  1672             // This is much faster than division on most architectures.
       
  1673             q = (w * 0xAAAAAAABL) & LONG_MASK;
       
  1674             result[i] = (int) q;
       
  1675 
       
  1676             // Now check the borrow. The second check can of course be
       
  1677             // eliminated if the first fails.
       
  1678             if (q >= 0x55555556L)
       
  1679             {
       
  1680                 borrow++;
       
  1681                 if (q >= 0xAAAAAAABL)
       
  1682                     borrow++;
       
  1683             }
       
  1684         }
       
  1685         result = trustedStripLeadingZeroInts(result);
       
  1686         return new BigInteger(result, signum);
       
  1687     }
       
  1688 
       
  1689     /**
       
  1690      * Returns a new BigInteger representing n lower ints of the number.
       
  1691      * This is used by Karatsuba multiplication and Karatsuba squaring.
       
  1692      */
       
  1693     private BigInteger getLower(int n) {
       
  1694         int len = mag.length;
       
  1695 
       
  1696         if (len <= n)
       
  1697             return this;
       
  1698 
       
  1699         int lowerInts[] = new int[n];
       
  1700         System.arraycopy(mag, len-n, lowerInts, 0, n);
       
  1701 
       
  1702         return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);
       
  1703     }
       
  1704 
       
  1705     /**
       
  1706      * Returns a new BigInteger representing mag.length-n upper
       
  1707      * ints of the number.  This is used by Karatsuba multiplication and
       
  1708      * Karatsuba squaring.
       
  1709      */
       
  1710     private BigInteger getUpper(int n) {
       
  1711         int len = mag.length;
       
  1712 
       
  1713         if (len <= n)
       
  1714             return ZERO;
       
  1715 
       
  1716         int upperLen = len - n;
       
  1717         int upperInts[] = new int[upperLen];
       
  1718         System.arraycopy(mag, 0, upperInts, 0, upperLen);
       
  1719 
       
  1720         return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1);
       
  1721     }
       
  1722 
       
  1723     // Squaring
       
  1724 
       
  1725     /**
  1405      * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.
  1726      * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.
  1406      *
  1727      *
  1407      * @return {@code this<sup>2</sup>}
  1728      * @return {@code this<sup>2</sup>}
  1408      */
  1729      */
  1409     private BigInteger square() {
  1730     private BigInteger square() {
  1410         if (signum == 0)
  1731         if (signum == 0)
  1411             return ZERO;
  1732             return ZERO;
  1412         int[] z = squareToLen(mag, mag.length, null);
  1733         int len = mag.length;
  1413         return new BigInteger(trustedStripLeadingZeroInts(z), 1);
  1734 
       
  1735         if (len < KARATSUBA_SQUARE_THRESHOLD)
       
  1736         {
       
  1737             int[] z = squareToLen(mag, len, null);
       
  1738             return new BigInteger(trustedStripLeadingZeroInts(z), 1);
       
  1739         }
       
  1740         else
       
  1741             if (len < TOOM_COOK_SQUARE_THRESHOLD)
       
  1742                 return squareKaratsuba();
       
  1743             else
       
  1744                return squareToomCook3();
  1414     }
  1745     }
  1415 
  1746 
  1416     /**
  1747     /**
  1417      * Squares the contents of the int array x. The result is placed into the
  1748      * Squares the contents of the int array x. The result is placed into the
  1418      * int array z.  The contents of x are not changed.
  1749      * int array z.  The contents of x are not changed.
  1479 
  1810 
  1480         return z;
  1811         return z;
  1481     }
  1812     }
  1482 
  1813 
  1483     /**
  1814     /**
       
  1815      * Squares a BigInteger using the Karatsuba squaring algorithm.  It should
       
  1816      * be used when both numbers are larger than a certain threshold (found
       
  1817      * experimentally).  It is a recursive divide-and-conquer algorithm that
       
  1818      * has better asymptotic performance than the algorithm used in
       
  1819      * squareToLen.
       
  1820      */
       
  1821     private BigInteger squareKaratsuba()
       
  1822     {
       
  1823         int half = (mag.length+1) / 2;
       
  1824 
       
  1825         BigInteger xl = getLower(half);
       
  1826         BigInteger xh = getUpper(half);
       
  1827 
       
  1828         BigInteger xhs = xh.square();  // xhs = xh^2
       
  1829         BigInteger xls = xl.square();  // xls = xl^2
       
  1830 
       
  1831         // xh^2 << 64  +  (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2
       
  1832         return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls);
       
  1833     }
       
  1834 
       
  1835     /**
       
  1836      * Squares a BigInteger using the 3-way Toom-Cook squaring algorithm.  It
       
  1837      * should be used when both numbers are larger than a certain threshold
       
  1838      * (found experimentally).  It is a recursive divide-and-conquer algorithm
       
  1839      * that has better asymptotic performance than the algorithm used in
       
  1840      * squareToLen or squareKaratsuba.
       
  1841      */
       
  1842     private BigInteger squareToomCook3()
       
  1843     {
       
  1844         int len = mag.length;
       
  1845 
       
  1846         // k is the size (in ints) of the lower-order slices.
       
  1847         int k = (len+2)/3;   // Equal to ceil(largest/3)
       
  1848 
       
  1849         // r is the size (in ints) of the highest-order slice.
       
  1850         int r = len - 2*k;
       
  1851 
       
  1852         // Obtain slices of the numbers. a2 is the most significant
       
  1853         // bits of the number, and a0 the least significant.
       
  1854         BigInteger a0, a1, a2;
       
  1855         a2 = getToomSlice(k, r, 0, len);
       
  1856         a1 = getToomSlice(k, r, 1, len);
       
  1857         a0 = getToomSlice(k, r, 2, len);
       
  1858         BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
       
  1859 
       
  1860         v0 = a0.square();
       
  1861         da1 = a2.add(a0);
       
  1862         vm1 = da1.subtract(a1).square();
       
  1863         da1 = da1.add(a1);
       
  1864         v1 = da1.square();
       
  1865         vinf = a2.square();
       
  1866         v2 = da1.add(a2).shiftLeft(1).subtract(a0).square();
       
  1867 
       
  1868         /* The algorithm requires two divisions by 2 and one by 3.
       
  1869            All divisions are known to be exact, that is, they do not produce
       
  1870            remainders, and all results are positive.  The divisions by 2 are
       
  1871            implemented as right shifts which are relatively efficient, leaving
       
  1872            only a division by 3.
       
  1873            The division by 3 is done by an optimized algorithm for this case.
       
  1874         */
       
  1875         t2 = v2.subtract(vm1).exactDivideBy3();
       
  1876         tm1 = v1.subtract(vm1).shiftRight(1);
       
  1877         t1 = v1.subtract(v0);
       
  1878         t2 = t2.subtract(t1).shiftRight(1);
       
  1879         t1 = t1.subtract(tm1).subtract(vinf);
       
  1880         t2 = t2.subtract(vinf.shiftLeft(1));
       
  1881         tm1 = tm1.subtract(t2);
       
  1882 
       
  1883         // Number of bits to shift left.
       
  1884         int ss = k*32;
       
  1885 
       
  1886         return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
       
  1887     }
       
  1888 
       
  1889     // Division
       
  1890 
       
  1891     /**
  1484      * Returns a BigInteger whose value is {@code (this / val)}.
  1892      * Returns a BigInteger whose value is {@code (this / val)}.
  1485      *
  1893      *
  1486      * @param  val value by which this BigInteger is to be divided.
  1894      * @param  val value by which this BigInteger is to be divided.
  1487      * @return {@code this / val}
  1895      * @return {@code this / val}
  1488      * @throws ArithmeticException if {@code val} is zero.
  1896      * @throws ArithmeticException if {@code val} is zero.
  1547         if (exponent < 0)
  1955         if (exponent < 0)
  1548             throw new ArithmeticException("Negative exponent");
  1956             throw new ArithmeticException("Negative exponent");
  1549         if (signum==0)
  1957         if (signum==0)
  1550             return (exponent==0 ? ONE : this);
  1958             return (exponent==0 ? ONE : this);
  1551 
  1959 
  1552         // Perform exponentiation using repeated squaring trick
  1960         BigInteger partToSquare = this.abs();
  1553         int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
  1961 
  1554         int[] baseToPow2 = this.mag;
  1962         // Factor out powers of two from the base, as the exponentiation of
  1555         int[] result = {1};
  1963         // these can be done by left shifts only.
  1556 
  1964         // The remaining part can then be exponentiated faster.  The
  1557         while (exponent != 0) {
  1965         // powers of two will be multiplied back at the end.
  1558             if ((exponent & 1)==1) {
  1966         int powersOfTwo = partToSquare.getLowestSetBit();
  1559                 result = multiplyToLen(result, result.length,
  1967 
  1560                                        baseToPow2, baseToPow2.length, null);
  1968         int remainingBits;
  1561                 result = trustedStripLeadingZeroInts(result);
  1969 
       
  1970         // Factor the powers of two out quickly by shifting right, if needed.
       
  1971         if (powersOfTwo > 0)
       
  1972         {
       
  1973             partToSquare = partToSquare.shiftRight(powersOfTwo);
       
  1974             remainingBits = partToSquare.bitLength();
       
  1975             if (remainingBits == 1)  // Nothing left but +/- 1?
       
  1976                 if (signum<0 && (exponent&1)==1)
       
  1977                     return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent);
       
  1978                 else
       
  1979                     return ONE.shiftLeft(powersOfTwo*exponent);
       
  1980         }
       
  1981         else
       
  1982         {
       
  1983             remainingBits = partToSquare.bitLength();
       
  1984             if (remainingBits == 1)  // Nothing left but +/- 1?
       
  1985                 if (signum<0 && (exponent&1)==1)
       
  1986                     return NEGATIVE_ONE;
       
  1987                 else
       
  1988                     return ONE;
       
  1989         }
       
  1990 
       
  1991         // This is a quick way to approximate the size of the result,
       
  1992         // similar to doing log2[n] * exponent.  This will give an upper bound
       
  1993         // of how big the result can be, and which algorithm to use.
       
  1994         int scaleFactor = remainingBits * exponent;
       
  1995 
       
  1996         // Use slightly different algorithms for small and large operands.
       
  1997         // See if the result will safely fit into a long. (Largest 2^63-1)
       
  1998         if (partToSquare.mag.length==1 && scaleFactor <= 62)
       
  1999         {
       
  2000             // Small number algorithm.  Everything fits into a long.
       
  2001             int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
       
  2002             long result = 1;
       
  2003             long baseToPow2 = partToSquare.mag[0] & LONG_MASK;
       
  2004 
       
  2005             int workingExponent = exponent;
       
  2006 
       
  2007             // Perform exponentiation using repeated squaring trick
       
  2008             while (workingExponent != 0) {
       
  2009                 if ((workingExponent & 1)==1)
       
  2010                     result = result * baseToPow2;
       
  2011 
       
  2012                 if ((workingExponent >>>= 1) != 0)
       
  2013                     baseToPow2 = baseToPow2 * baseToPow2;
  1562             }
  2014             }
  1563             if ((exponent >>>= 1) != 0) {
  2015 
  1564                 baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null);
  2016             // Multiply back the powers of two (quickly, by shifting left)
  1565                 baseToPow2 = trustedStripLeadingZeroInts(baseToPow2);
  2017             if (powersOfTwo > 0)
       
  2018             {
       
  2019                 int bitsToShift = powersOfTwo*exponent;
       
  2020                 if (bitsToShift + scaleFactor <= 62) // Fits in long?
       
  2021                     return valueOf((result << bitsToShift) * newSign);
       
  2022                 else
       
  2023                     return valueOf(result*newSign).shiftLeft(bitsToShift);
  1566             }
  2024             }
  1567         }
  2025             else
  1568         return new BigInteger(result, newSign);
  2026                 return valueOf(result*newSign);
       
  2027         }
       
  2028         else
       
  2029         {
       
  2030             // Large number algorithm.  This is basically identical to
       
  2031             // the algorithm above, but calls multiply() and square()
       
  2032             // which may use more efficient algorithms for large numbers.
       
  2033             BigInteger answer = ONE;
       
  2034 
       
  2035             int workingExponent = exponent;
       
  2036             // Perform exponentiation using repeated squaring trick
       
  2037             while (workingExponent != 0) {
       
  2038                 if ((workingExponent & 1)==1)
       
  2039                     answer = answer.multiply(partToSquare);
       
  2040 
       
  2041                 if ((workingExponent >>>= 1) != 0)
       
  2042                     partToSquare = partToSquare.square();
       
  2043             }
       
  2044             // Multiply back the (exponentiated) powers of two (quickly,
       
  2045             // by shifting left)
       
  2046             if (powersOfTwo > 0)
       
  2047                 answer = answer.shiftLeft(powersOfTwo*exponent);
       
  2048 
       
  2049             if (signum<0 && (exponent&1)==1)
       
  2050                 return answer.negate();
       
  2051             else
       
  2052                 return answer;
       
  2053         }
  1569     }
  2054     }
  1570 
  2055 
  1571     /**
  2056     /**
  1572      * Returns a BigInteger whose value is the greatest common divisor of
  2057      * Returns a BigInteger whose value is the greatest common divisor of
  1573      * {@code abs(this)} and {@code abs(val)}.  Returns 0 if
  2058      * {@code abs(this)} and {@code abs(val)}.  Returns 0 if
  2115     private BigInteger modPow2(BigInteger exponent, int p) {
  2600     private BigInteger modPow2(BigInteger exponent, int p) {
  2116         /*
  2601         /*
  2117          * Perform exponentiation using repeated squaring trick, chopping off
  2602          * Perform exponentiation using repeated squaring trick, chopping off
  2118          * high order bits as indicated by modulus.
  2603          * high order bits as indicated by modulus.
  2119          */
  2604          */
  2120         BigInteger result = valueOf(1);
  2605         BigInteger result = ONE;
  2121         BigInteger baseToPow2 = this.mod2(p);
  2606         BigInteger baseToPow2 = this.mod2(p);
  2122         int expOffset = 0;
  2607         int expOffset = 0;
  2123 
  2608 
  2124         int limit = exponent.bitLength();
  2609         int limit = exponent.bitLength();
  2125 
  2610 
  2848             buf.append(digitGroup[i]);
  3333             buf.append(digitGroup[i]);
  2849         }
  3334         }
  2850         return buf.toString();
  3335         return buf.toString();
  2851     }
  3336     }
  2852 
  3337 
       
  3338 
  2853     /* zero[i] is a string of i consecutive zeros. */
  3339     /* zero[i] is a string of i consecutive zeros. */
  2854     private static String zeros[] = new String[64];
  3340     private static String zeros[] = new String[64];
  2855     static {
  3341     static {
  2856         zeros[63] =
  3342         zeros[63] =
  2857             "000000000000000000000000000000000000000000000000000000000000000";
  3343             "000000000000000000000000000000000000000000000000000000000000000";
  3216     /**
  3702     /**
  3217      * Returns the index of the int that contains the first nonzero int in the
  3703      * Returns the index of the int that contains the first nonzero int in the
  3218      * little-endian binary representation of the magnitude (int 0 is the
  3704      * little-endian binary representation of the magnitude (int 0 is the
  3219      * least significant). If the magnitude is zero, return value is undefined.
  3705      * least significant). If the magnitude is zero, return value is undefined.
  3220      */
  3706      */
  3221      private int firstNonzeroIntNum() {
  3707     private int firstNonzeroIntNum() {
  3222          int fn = firstNonzeroIntNum - 2;
  3708         int fn = firstNonzeroIntNum - 2;
  3223          if (fn == -2) { // firstNonzeroIntNum not initialized yet
  3709         if (fn == -2) { // firstNonzeroIntNum not initialized yet
  3224              fn = 0;
  3710             fn = 0;
  3225 
  3711 
  3226              // Search for the first nonzero int
  3712             // Search for the first nonzero int
  3227              int i;
  3713             int i;
  3228              int mlen = mag.length;
  3714             int mlen = mag.length;
  3229              for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
  3715             for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
  3230                  ;
  3716                 ;
  3231              fn = mlen - i - 1;
  3717             fn = mlen - i - 1;
  3232              firstNonzeroIntNum = fn + 2; // offset by two to initialize
  3718             firstNonzeroIntNum = fn + 2; // offset by two to initialize
  3233          }
  3719         }
  3234          return fn;
  3720         return fn;
  3235      }
  3721     }
  3236 
  3722 
  3237     /** use serialVersionUID from JDK 1.1. for interoperability */
  3723     /** use serialVersionUID from JDK 1.1. for interoperability */
  3238     private static final long serialVersionUID = -8287574255936472291L;
  3724     private static final long serialVersionUID = -8287574255936472291L;
  3239 
  3725 
  3240     /**
  3726     /**