home *** CD-ROM | disk | FTP | other *** search
/ Apple Developer Connection Student Program / ADC Tools Sampler CD Disk 3 1999.iso / Metrowerks CodeWarrior / Java Support / Java_Source / Java2 / src / java / math / BigInteger.java < prev   
Encoding:
Java Source  |  1999-05-28  |  58.3 KB  |  1,737 lines  |  [TEXT/CWIE]

  1. /*
  2.  * @(#)BigInteger.java    1.23 98/10/27
  3.  *
  4.  * Copyright 1996-1998 by Sun Microsystems, Inc.,
  5.  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
  6.  * All rights reserved.
  7.  *
  8.  * This software is the confidential and proprietary information
  9.  * of Sun Microsystems, Inc. ("Confidential Information").  You
  10.  * shall not disclose such Confidential Information and shall use
  11.  * it only in accordance with the terms of the license agreement
  12.  * you entered into with Sun.
  13.  */
  14.  
  15. package java.math;
  16.  
  17. import java.util.Random;
  18.  
  19. /**
  20.  * Immutable arbitrary-precision integers.  All operations behave as if
  21.  * BigIntegers were represented in two's-complement notation (like Java's
  22.  * primitive integer types).  BigInteger provides analogues to all of Java's
  23.  * primitive integer operators, and all relevant methods from java.lang.Math.
  24.  * Additionally, BigInteger provides operations for modular arithmetic, GCD
  25.  * calculation, primality testing, prime generation, bit manipulation,
  26.  * and a few other miscellaneous operations.
  27.  * <p>
  28.  * Semantics of arithmetic operations exactly mimic those of Java's integer
  29.  * arithmetic operators, as defined in <i>The Java Language Specification</i>.
  30.  * For example, division by zero throws an <tt>ArithmeticException</tt>, and
  31.  * division of a negative by a positive yields a negative (or zero) remainder.
  32.  * All of the details in the Spec concerning overflow are ignored, as
  33.  * BigIntegers are made as large as necessary to accommodate the results of an
  34.  * operation.
  35.  * <p>
  36.  * Semantics of shift operations extend those of Java's shift operators
  37.  * to allow for negative shift distances.  A right-shift with a negative
  38.  * shift distance results in a left shift, and vice-versa.  The unsigned
  39.  * right shift operator (>>>) is omitted, as this operation makes
  40.  * little sense in combination with the "infinite word size" abstraction
  41.  * provided by this class.
  42.  * <p>
  43.  * Semantics of bitwise logical operations exactly mimic those of Java's
  44.  * bitwise integer operators.  The binary operators (<tt>and</tt>,
  45.  * <tt>or</tt>, <tt>xor</tt>) implicitly perform sign extension on the shorter
  46.  * of the two operands prior to performing the operation.
  47.  * <p>
  48.  * Comparison operations perform signed integer comparisons, analogous to
  49.  * those performed by Java's relational and equality operators.
  50.  * <p>
  51.  * Modular arithmetic operations are provided to compute residues, perform
  52.  * exponentiation, and compute multiplicative inverses.  These methods always
  53.  * return a non-negative result, between <tt>0</tt> and <tt>(modulus - 1)</tt>,
  54.  * inclusive.
  55.  * <p>
  56.  * Bit operations operate on a single bit of the two's-complement
  57.  * representation of their operand.  If necessary, the operand is sign-
  58.  * extended so that it contains the designated bit.  None of the single-bit
  59.  * operations can produce a BigInteger with a different sign from the
  60.  * BigInteger being operated on, as they affect only a single bit, and the
  61.  * "infinite word size" abstraction provided by this class ensures that there
  62.  * are infinitely many "virtual sign bits" preceding each BigInteger.
  63.  * <p>
  64.  * For the sake of brevity and clarity, pseudo-code is used throughout the
  65.  * descriptions of BigInteger methods.  The pseudo-code expression
  66.  * <tt>(i + j)</tt> is shorthand for "a BigInteger whose value is
  67.  * that of the BigInteger <tt>i</tt> plus that of the BigInteger <tt>j</tt>."
  68.  * The pseudo-code expression <tt>(i == j)</tt> is shorthand for
  69.  * "<tt>true</tt> if and only if the BigInteger <tt>i</tt> represents the same
  70.  * value as the the BigInteger <tt>j</tt>."  Other pseudo-code expressions are
  71.  * interpreted similarly. 
  72.  *
  73.  * @see     BigDecimal
  74.  * @version 1.23, 99/03/26
  75.  * @author  Josh Bloch
  76.  * @since JDK1.1
  77.  */
  78. public class BigInteger extends Number implements Comparable {
  79.     /**
  80.      * The signum of this BigInteger: -1 for negative, 0 for zero, or
  81.      * 1 for positive.  Note that the BigInteger zero <i>must</i> have
  82.      * a signum of 0.  This is necessary to ensures that there is exactly one
  83.      * representation for each BigInteger value.
  84.      *
  85.      * @serial
  86.      */
  87.     private int signum;
  88.  
  89.     /**
  90.      * The magnitude of this BigInteger, in <i>big-endian</i> byte-order: the
  91.      * zeroth element of this array is the most-significant byte of the
  92.      * magnitude.  The magnitude must be "minimal" in that the most-significant
  93.      * byte (<tt>magnitude[0]</tt>) must be non-zero.  This is necessary to
  94.      * ensure that there is exactly one representation for each BigInteger
  95.      * value.  Note that this implies that the BigInteger zero has a
  96.      * zero-length magnitude array.
  97.      *
  98.      * @serial
  99.      */
  100.     private byte[] magnitude;
  101.  
  102.  
  103.     // These "redundant fields" are initialized with recognizable nonsense
  104.     // values, and cached the first time they are needed (or never, if they
  105.     // aren't needed).
  106.  
  107.     /**
  108.      * The bitCount of this BigInteger, as returned by bitCount(), or -1
  109.      * (either value is acceptable).
  110.      *
  111.      * @serial
  112.      * @see #bitCount
  113.      */
  114.     private int bitCount =  -1;
  115.  
  116.     /**
  117.      * The bitLength of this BigInteger, as returned by bitLength(), or -1
  118.      * (either value is acceptable).
  119.      *
  120.      * @serial
  121.      * @see #bitLength
  122.      */
  123.     private int bitLength = -1;
  124.  
  125.     /**
  126.      * The lowest set bit of this BigInteger, as returned by getLowestSetBit(),
  127.      * or -2 (either value is acceptable).
  128.      *
  129.      * @serial
  130.      * @see #getLowestSetBit
  131.      */
  132.     private int lowestSetBit = -2;
  133.  
  134.     /**
  135.      * The byte-number of the lowest-order nonzero byte in the magnitude of
  136.      * this BigInteger, or -2 (either value is acceptable).  The least
  137.      * significant byte has byte-number 0, the next byte in order of
  138.      * increasing significance has byte-number 1, and so forth.
  139.      *
  140.      * @serial
  141.      */
  142.     private int firstNonzeroByteNum = -2;  // Only used for negative numbers
  143.  
  144.  
  145.     //Constructors
  146.  
  147.     /**
  148.      * Translates a byte array containing the two's-complement binary
  149.      * representation of a BigInteger into a BigInteger.  The input array is
  150.      * assumed to be in <i>big-endian</i> byte-order: the most significant
  151.      * byte is in the zeroth element.
  152.      *
  153.      * @param  val big-endian two's-complement binary representation of
  154.      *           BigInteger.
  155.      * @throws NumberFormatException <tt>val</tt> is zero bytes long.
  156.      */
  157.     public BigInteger(byte[] val) {
  158.     if (val.length == 0)
  159.         throw new NumberFormatException("Zero length BigInteger");
  160.  
  161.     if (val[0] < 0) {
  162.         magnitude = makePositive(val);
  163.         signum = -1;
  164.     } else {
  165.         magnitude = stripLeadingZeroBytes(val);
  166.         signum = (magnitude.length == 0 ? 0 : 1);
  167.     }
  168.     }
  169.  
  170.     /**
  171.      * Translates the sign-magnitude representation of a BigInteger into a
  172.      * BigInteger.  The sign is represented as an integer signum value: -1 for
  173.      * negative, 0 for zero, or 1 for positive.  The magnitude is a byte array
  174.      * in <i>big-endian</i> byte-order: the most significant byte is in the
  175.      * zeroth element.  A zero-length magnitude array is permissible, and will
  176.      * result in in a BigInteger value of 0, whether signum is -1, 0 or 1.
  177.      *
  178.      * @param  signum signum of the number (-1 for negative, 0 for zero, 1
  179.      *            for positive).
  180.      * @param  magnitude big-endian binary representation of the magnitude of
  181.      *            the number.
  182.      * @throws NumberFormatException <tt>signum</tt> is not one of the three
  183.      *           legal values (-1, 0, and 1), or <tt>signum</tt> is 0 and
  184.      *           <tt>magnitude</tt> contains one or more non-zero bytes.
  185.      */
  186.     public BigInteger(int signum, byte[] magnitude) {
  187.     this.magnitude = stripLeadingZeroBytes(magnitude);
  188.  
  189.     if (signum < -1 || signum > 1)
  190.         throw(new NumberFormatException("Invalid signum value"));
  191.  
  192.     if (this.magnitude.length==0) {
  193.         this.signum = 0;
  194.     } else {
  195.         if (signum == 0)
  196.         throw(new NumberFormatException("signum-magnitude mismatch"));
  197.         this.signum = signum;
  198.     }
  199.     }
  200.  
  201.     /**
  202.      * Translates the String representation of a BigInteger in the specified
  203.      * radix into a BigInteger.  The String representation consists of an
  204.      * optional minus sign followed by a sequence of one or more digits in the
  205.      * specified radix.  The character-to-digit mapping is provided by
  206.      * <tt>Character.digit</tt>.  The String may not contain any extraneous
  207.      * characters (whitespace, for example).
  208.      *
  209.      * @param val String representation of BigInteger.
  210.      * @param radix radix to be used in interpreting <tt>val</tt>.
  211.      * @throws NumberFormatException <tt>val</tt> is not a valid representation
  212.      *           of a BigInteger in the specified radix, or <tt>radix</tt> is
  213.      *           outside the range from <tt>Character.MIN_RADIX</tt> (2) to
  214.      *           <tt>Character.MAX_RADIX</tt> (36), inclusive.
  215.      * @see    Character#digit
  216.      */
  217.     public BigInteger(String val, int radix) {
  218.     int cursor = 0, numDigits;
  219.  
  220.     if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  221.         throw new NumberFormatException("Radix out of range");
  222.     if (val.length() == 0)
  223.         throw new NumberFormatException("Zero length BigInteger");
  224.  
  225.     // Check for leading minus sign
  226.     signum = 1;
  227.     if (val.charAt(0) == '-') {
  228.         if (val.length() == 1)
  229.         throw new NumberFormatException("Zero length BigInteger");
  230.         signum = -1;
  231.         cursor = 1;
  232.     }
  233.  
  234.         // Skip leading zeros and compute number of digits in magnitude
  235.     while (cursor<val.length() &&
  236.                Character.digit(val.charAt(cursor),radix) == 0)
  237.         cursor++;
  238.     if (cursor==val.length()) {
  239.         signum = 0;
  240.         magnitude = new byte[0];
  241.         return;
  242.     } else {
  243.         numDigits = val.length() - cursor;
  244.     }
  245.  
  246.     // Process first (potentially short) digit group, if necessary
  247.     int firstGroupLen = numDigits % digitsPerLong[radix];
  248.     if (firstGroupLen == 0)
  249.         firstGroupLen = digitsPerLong[radix];
  250.     String group = val.substring(cursor, cursor += firstGroupLen);
  251.     BigInteger tmp = valueOf(Long.parseLong(group, radix));
  252.  
  253.     // Process remaining digit groups
  254.     while (cursor < val.length()) {
  255.         group = val.substring(cursor, cursor += digitsPerLong[radix]);
  256.         long groupVal = Long.parseLong(group, radix);
  257.         if (groupVal <0)
  258.         throw new NumberFormatException("Illegal digit");
  259.         tmp = tmp.multiply(longRadix[radix]).add(valueOf(groupVal));
  260.     }
  261.  
  262.     magnitude = tmp.magnitude;
  263.     }
  264.  
  265.  
  266.     /**
  267.      * Translates the decimal String representation of a BigInteger into a
  268.      * BigInteger.  The String representation consists of an optional minus
  269.      * sign followed by a sequence of one or more decimal digits.  The
  270.      * character-to-digit mapping is provided by <tt>Character.digit</tt>.
  271.      * The String may not contain any extraneous characters (whitespace, for
  272.      * example).
  273.      *
  274.      * @param val decimal String representation of BigInteger.
  275.      * @throws NumberFormatException <tt>val</tt> is not a valid representation
  276.      *           of a BigInteger.
  277.      * @see    Character#digit
  278.      */
  279.     public BigInteger(String val) {
  280.     this(val, 10);
  281.     }
  282.  
  283.     /**
  284.      * Constructs a randomly generated BigInteger, uniformly distributed over
  285.      * the range <tt>0</tt> to <tt>(2<sup>numBits</sup> - 1)</tt>, inclusive.
  286.      * The uniformity of the distribution assumes that a fair source of random
  287.      * bits is provided in <tt>rnd</tt>.  Note that this constructor always
  288.      * constructs a non-negative BigInteger.
  289.      *
  290.      * @param  numBits maximum bitLength of the new BigInteger.
  291.      * @param  rnd source of randomness to be used in computing the new
  292.      *           BigInteger.
  293.      * @throws IllegalArgumentException <tt>numBits</tt> is negative.
  294.      * @see #bitLength
  295.      */
  296.     public BigInteger(int numBits, Random rnd) {
  297.     this(1, randomBits(numBits, rnd));
  298.     }
  299.  
  300.     private static byte[] randomBits(int numBits, Random rnd) {
  301.     if (numBits < 0)
  302.         throw new IllegalArgumentException("numBits must be non-negative");
  303.     int numBytes = (numBits+7)/8;
  304.     byte[] randomBits = new byte[numBytes];
  305.  
  306.     // Generate random bytes and mask out any excess bits
  307.     if (numBytes > 0) {
  308.         rnd.nextBytes(randomBits);
  309.         int excessBits = 8*numBytes - numBits;
  310.         randomBits[0] &= (1 << (8-excessBits)) - 1;
  311.     }
  312.     return randomBits;
  313.     }
  314.  
  315.     /**
  316.      * Constructs a randomly generated positive BigInteger that is probably
  317.      * prime, with the specified bitLength.
  318.      *
  319.      * @param  bitLength bitLength of the returned BigInteger.
  320.      * @param  certainty a measure of the uncertainty that the caller is
  321.      *         willing to tolerate.  The probability that the new BigInteger
  322.      *           represents a prime number will exceed
  323.      *           <tt>(1 - 1/2<sup>certainty</sup></tt>).  The execution time of
  324.      *           this constructor is proportional to the value of this parameter.
  325.      * @param  rnd source of random bits used to select candidates to be
  326.      *           tested for primality.
  327.      * @throws ArithmeticException <tt>bitLength < 2</tt>.
  328.      * @see    #bitLength
  329.      */
  330.     public BigInteger(int bitLength, int certainty, Random rnd) {
  331.     if (bitLength < 2)
  332.         throw new ArithmeticException("bitLength < 2");
  333.  
  334.     BigInteger p;
  335.     do {
  336.             // Select a candidate of exactly the right length.  Note that
  337.         // Plumb's generator doesn't handle bitLength<=16 properly.
  338.         do {
  339.         p = new BigInteger(bitLength-1, rnd).setBit(bitLength-1);
  340.         p = (bitLength <= 16
  341.              ? (bitLength > 2 ? p.setBit(0) : p)
  342.              : new BigInteger(plumbGeneratePrime(p.magnitude), 1));
  343.         } while (p.bitLength() != bitLength);
  344.     } while (!p.isProbablePrime(certainty));
  345.  
  346.     signum = 1;
  347.     magnitude = p.magnitude;
  348.     }
  349.  
  350.  
  351.     /**
  352.      * This private constructor differs from its public cousin
  353.      * with the arguments reversed in two ways: it assumes that its
  354.      * arguments are correct, and it doesn't copy the magnitude array.
  355.      */
  356.     private BigInteger(byte[] magnitude, int signum) {
  357.     this.signum = (magnitude.length==0 ? 0 : signum);
  358.     this.magnitude = magnitude;
  359.     }
  360.  
  361.  
  362.     //Static Factory Methods
  363.  
  364.     /**
  365.      * Returns a BigInteger whose value is equal to that of the specified
  366.      * long.  This "static factory method" is provided in preference to a
  367.      * (long) constructor because it allows for reuse of frequently used
  368.      * BigIntegers. 
  369.      *
  370.      * @param  val value of the BigInteger to return.
  371.      * @return a BigInteger with the specified value.
  372.      */
  373.     public static BigInteger valueOf(long val) {
  374.     // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
  375.     if (val == 0)
  376.         return ZERO;
  377.     if (val > 0 && val <= MAX_CONSTANT)
  378.         return posConst[(int) val];
  379.     else if (val < 0 && val >= -MAX_CONSTANT)
  380.         return negConst[(int) -val];
  381.  
  382.     // Dump two's complement binary into valArray
  383.     byte valArray[] = new byte[8];
  384.     for (int i=0; i<8; i++, val >>= 8)
  385.         valArray[7-i] = (byte)val;
  386.     return new BigInteger(valArray);
  387.     }
  388.  
  389.     /**
  390.      * Returns a BigInteger with the given two's complement representation.
  391.      * Assumes that the input array will not be modified (the returned
  392.      * BigInteger will reference the input array if feasible).
  393.      */
  394.     private static BigInteger valueOf(byte val[]) {
  395.     return (val[0]>0 ? new BigInteger(val, 1) : new BigInteger(val));
  396.     }
  397.  
  398.     // Constants
  399.  
  400.     /**
  401.      * Initialize static constant array when class is loaded.
  402.      */
  403.     private final static int MAX_CONSTANT = 16;
  404.     private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
  405.     private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
  406.     static {
  407.     for (int i = 1; i <= MAX_CONSTANT; i++) {
  408.         byte[] magnitude = new byte[1];
  409.         magnitude[0] = (byte) i;
  410.         posConst[i] = new BigInteger(magnitude,  1);
  411.         negConst[i] = new BigInteger(magnitude, -1);
  412.     }
  413.     }
  414.  
  415.     /**
  416.      * The BigInteger constant zero.
  417.      *
  418.      * @since   JDK1.2
  419.      */
  420.     public static final BigInteger ZERO = new BigInteger(new byte[0], 0);
  421.  
  422.     /**
  423.      * The BigInteger constant one.
  424.      *
  425.      * @since   JDK1.2
  426.      */
  427.     public static final BigInteger ONE = valueOf(1);
  428.  
  429.     /**
  430.      * The BigInteger constant two.  (Not exported.)
  431.      */
  432.     private static final BigInteger TWO = valueOf(2);
  433.  
  434.  
  435.     // Arithmetic Operations
  436.  
  437.     /**
  438.      * Returns a BigInteger whose value is <tt>(this + val)</tt>.
  439.      *
  440.      * @param  val value to be added to this BigInteger.
  441.      * @return <tt>this + val</tt>
  442.      */
  443.     public BigInteger add(BigInteger val) {
  444.     if (val.signum == 0)
  445.         return this;
  446.     else if (this.signum == 0)
  447.         return val;
  448.     else if (val.signum == signum)
  449.         return new BigInteger(plumbAdd(magnitude, val.magnitude), signum);
  450.     else if (this.signum < 0)
  451.         return plumbSubtract(val.magnitude, magnitude);
  452.     else  // val.signum < 0
  453.         return plumbSubtract(magnitude, val.magnitude);
  454.     }
  455.  
  456.     /**
  457.      * Returns a BigInteger whose value is <tt>(this - val)</tt>.
  458.      *
  459.      * @param  val value to be subtracted from this BigInteger.
  460.      * @return <tt>this - val</tt>
  461.      */
  462.     public BigInteger subtract(BigInteger val) {
  463.     return add(new BigInteger(val.magnitude, -val.signum));
  464.     }
  465.  
  466.     /**
  467.      * Returns a BigInteger whose value is <tt>(this * val)</tt>.
  468.      *
  469.      * @param  val value to be multiplied by this BigInteger.
  470.      * @return <tt>this * val</tt>
  471.      */
  472.     public BigInteger multiply(BigInteger val) {
  473.     if (val.signum == 0 || this.signum==0)
  474.         return ZERO;
  475.     else
  476.         return new BigInteger(plumbMultiply(magnitude, val.magnitude),
  477.                   signum * val.signum);
  478.     }
  479.  
  480.     /**
  481.      * Returns a BigInteger whose value is <tt>(this / val)</tt>.
  482.      *
  483.      * @param  val value by which this BigInteger is to be divided.
  484.      * @return <tt>this / val</tt>
  485.      * @throws ArithmeticException <tt>val==0</tt>
  486.      */
  487.     public BigInteger divide(BigInteger val) {
  488.     if (val.signum == 0)
  489.         throw new ArithmeticException("BigInteger divide by zero");
  490.     else if (this.signum == 0)
  491.         return ZERO;
  492.     else
  493.         return new BigInteger(plumbDivide(magnitude, val.magnitude),
  494.                   signum * val.signum);
  495.     }
  496.  
  497.     /**
  498.      * Returns a BigInteger whose value is <tt>(this % val)</tt>.
  499.      *
  500.      * @param  val value by which this BigInteger is to be divided, and the
  501.      *           remainder computed.
  502.      * @return <tt>this % val</tt>
  503.      * @throws ArithmeticException <tt>val==0</tt>
  504.      */
  505.     public BigInteger remainder(BigInteger val) {
  506.     if (val.signum == 0)
  507.         throw new ArithmeticException("BigInteger divide by zero");
  508.     else if (this.signum == 0)
  509.         return ZERO;
  510.     else if (this.magnitude.length < val.magnitude.length)
  511.         return this; // *** WORKAROUND FOR BUG IN R1.1 OF PLUMB'S PKG ***
  512.     else
  513.         return new BigInteger(plumbRemainder(magnitude,val.magnitude),
  514.                   signum);
  515.     }
  516.  
  517.     /**
  518.      * Returns an array of two BigIntegers containing <tt>(this / val)</tt>
  519.      * followed by <tt>(this % val)</tt>.
  520.      *
  521.      * @param  val value by which this BigInteger is to be divided, and the
  522.      *           remainder computed.
  523.      * @return an array of two BigIntegers: the quotient <tt>(this / val)</tt>
  524.      *           is the initial element, and the remainder <tt>(this % val)</tt>
  525.      *           is the final element.
  526.      * @throws ArithmeticException <tt>val==0</tt>
  527.      */
  528.     public BigInteger[] divideAndRemainder(BigInteger val) {
  529.     BigInteger result[] = new BigInteger[2];
  530.  
  531.     if (val.signum == 0) {
  532.         throw new ArithmeticException("BigInteger divide by zero");
  533.     } else if (this.signum == 0) {
  534.         result[0] = result[1] = ZERO;
  535.     } else if (this.magnitude.length < val.magnitude.length) {
  536.         // *** WORKAROUND FOR A BUG IN R1.1 OF PLUMB'S PACKAGE ***
  537.         result[0] = ZERO;
  538.         result[1] = this;
  539.     } else {
  540.         byte resultMagnitude[][] =
  541.         plumbDivideAndRemainder(magnitude, val.magnitude);
  542.         result[0] = new BigInteger(resultMagnitude[0], signum*val.signum);
  543.         result[1] = new BigInteger(resultMagnitude[1], signum);
  544.     }
  545.     return result;
  546.     }
  547.  
  548.     /**
  549.      * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>.
  550.      * Note that <tt>exponent</tt> is an integer rather than a BigInteger.
  551.      *
  552.      * @param  exponent exponent to which this BigInteger is to be raised.
  553.      * @return <tt>this<sup>exponent</sup></tt>
  554.      * @throws ArithmeticException <tt>exponent</tt> is negative.  (This would
  555.      *           cause the operation to yield a non-integer value.)
  556.      */
  557.     public BigInteger pow(int exponent) {
  558.     if (exponent < 0)
  559.         throw new ArithmeticException("Negative exponent");
  560.     if (signum==0)
  561.         return (exponent==0 ? ONE : this);
  562.  
  563.     /* Perform exponentiation using repeated squaring trick */
  564.     BigInteger result = valueOf(exponent<0 && (exponent&1)==1 ? -1 : 1);
  565.     BigInteger baseToPow2 = this;
  566.     while (exponent != 0) {
  567.         if ((exponent & 1)==1)
  568.         result = result.multiply(baseToPow2);
  569.         if ((exponent >>= 1) != 0)
  570.         baseToPow2 = new BigInteger(
  571.                     plumbSquare(baseToPow2.magnitude), 1);
  572.     }
  573.     return result;
  574.     }
  575.  
  576.     /**
  577.      * Returns a BigInteger whose value is the greatest common divisor of
  578.      * <tt>abs(this)</tt> and <tt>abs(val)</tt>.  Returns 0 if
  579.      * <tt>this==0 && val==0</tt>.
  580.      *
  581.      * @param  val value with with the GCD is to be computed.
  582.      * @return <tt>GCD(abs(this), abs(val))</tt>
  583.      */
  584.     public BigInteger gcd(BigInteger val) {
  585.     if (val.signum == 0)
  586.         return this.abs();
  587.     else if (this.signum == 0)
  588.         return val.abs();
  589.     else
  590.         return new BigInteger(plumbGcd(magnitude, val.magnitude), 1);
  591.     }
  592.  
  593.     /**
  594.      * Returns a BigInteger whose value is the absolute value of this
  595.      * BigInteger. 
  596.      *
  597.      * @return <tt>abs(this)</tt>
  598.      */
  599.     public BigInteger abs() {
  600.     return (signum >= 0 ? this : this.negate());
  601.     }
  602.  
  603.     /**
  604.      * Returns a BigInteger whose value is <tt>(-this)</tt>.
  605.      *
  606.      * @return <tt>-this</tt>
  607.      */
  608.     public BigInteger negate() {
  609.     return new BigInteger(this.magnitude, -this.signum);
  610.     }
  611.  
  612.     /**
  613.      * Returns the signum function of this BigInteger.
  614.      *
  615.      * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or
  616.      *           positive.
  617.      */
  618.     public int signum() {
  619.     return this.signum;
  620.     }
  621.  
  622.     // Modular Arithmetic Operations
  623.  
  624.     /**
  625.      * Returns a BigInteger whose value is <tt>(this mod m</tt>).  This method
  626.      * differs from <tt>remainder</tt> in that it always returns a
  627.      * <i>positive</i> BigInteger.
  628.      *
  629.      * @param  m the modulus.
  630.      * @return <tt>this mod m</tt>
  631.      * @throws ArithmeticException <tt>m <= 0</tt>
  632.      * @see    #remainder
  633.      */
  634.     public BigInteger mod(BigInteger m) {
  635.     if (m.signum <= 0)
  636.         throw new ArithmeticException("BigInteger: modulus not positive");
  637.  
  638.     BigInteger result = this.remainder(m);
  639.     return (result.signum >= 0 ? result : result.add(m));
  640.     }
  641.  
  642.     /**
  643.      * Returns a BigInteger whose value is
  644.      * <tt>(this<sup>exponent</sup> mod m)</tt>.  (Unlike <tt>pow</tt>, this
  645.      * method permits negative exponents.)
  646.      *
  647.      * @param  exponent the exponent.
  648.      * @param  m the modulus.
  649.      * @return <tt>this<sup>exponent</sup> mod m</tt>
  650.      * @throws ArithmeticException <tt>m <= 0</tt>
  651.      * @see    #modInverse
  652.      */
  653.     public BigInteger modPow(BigInteger exponent, BigInteger m) {
  654.     if (m.signum <= 0)
  655.         throw new ArithmeticException("BigInteger: modulus not positive");
  656.  
  657.     /* Workaround for a bug in Plumb: x^0 (y) dumps core for x != 0 */
  658.     if (exponent.signum == 0)
  659.         return ONE;
  660.  
  661.     boolean invertResult;
  662.     if ((invertResult = (exponent.signum < 0)))
  663.         exponent = exponent.negate();
  664.  
  665.     BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
  666.                ? this.mod(m) : this);
  667.     BigInteger result;
  668.     if (m.testBit(0)) { /* Odd modulus: just pass it on to Plumb */
  669.         result = new BigInteger
  670.          (plumbModPow(base.magnitude, exponent.magnitude, m.magnitude), 1);
  671.     } else {
  672.         /*
  673.          * Even modulus.  Plumb only supports odd, so tear it into
  674.          * "odd part" (m1) and power of two (m2), use Plumb to exponentiate
  675.          * mod m1, manually exponentiate mod m2, and use Chinese Remainder
  676.          * Theorem to combine results.
  677.          */
  678.  
  679.         /* Tear m apart into odd part (m1) and power of 2 (m2) */
  680.         int p = m.getLowestSetBit();      /* Max pow of 2 that divides m */
  681.         BigInteger m1 = m.shiftRight(p);  /* m/2**p */
  682.         BigInteger m2 = ONE.shiftLeft(p); /* 2**p */
  683.  
  684.             /* Caculate (base ** exponent) mod m1.
  685.              * Special-case mod 1 to prevent Plumb's pkg from blowing up. */
  686.             BigInteger a1 = (m1.equals(ONE) ? ZERO :
  687.                              new BigInteger(plumbModPow(base.magnitude,
  688.                                         exponent.magnitude, m1.magnitude), 1));
  689.  
  690.         /* Caculate (this ** exponent) mod m2 */
  691.         BigInteger a2 = base.modPow2(exponent, p);
  692.  
  693.         /* Combine results using Chinese Remainder Theorem */
  694.         BigInteger y1 = m2.modInverse(m1);
  695.         BigInteger y2 = m1.modInverse(m2);
  696.         result = a1.multiply(m2).multiply(y1).add
  697.              (a2.multiply(m1).multiply(y2)).mod(m);
  698.     }
  699.  
  700.     return (invertResult ? result.modInverse(m) : result);
  701.     }
  702.  
  703.     /**
  704.      * Returns a BigInteger whose value is (this ** exponent) mod (2**p)
  705.      */
  706.     private BigInteger modPow2(BigInteger exponent, int p) {
  707.     /*
  708.      * Perform exponentiation using repeated squaring trick, chopping off
  709.      * high order bits as indicated by modulus.
  710.      */
  711.     BigInteger result = valueOf(1);
  712.     BigInteger baseToPow2 = this.mod2(p);
  713.     while (exponent.signum != 0) {
  714.         if (exponent.testBit(0))
  715.         result = result.multiply(baseToPow2).mod2(p);
  716.         exponent = exponent.shiftRight(1);
  717.         if (exponent.signum != 0)
  718.         baseToPow2 = new BigInteger(
  719.                    plumbSquare(baseToPow2.magnitude), 1).mod2(p);
  720.     }
  721.     return result;
  722.     }
  723.  
  724.     /**
  725.      * Returns a BigInteger whose value is this mod(2**p).
  726.      * Assumes that this BigInteger >= 0 and p > 0.
  727.      */
  728.     private BigInteger mod2(int p) {
  729.     if (bitLength() <= p)
  730.         return this;
  731.  
  732.     /* Copy remaining bytes of magnitude */
  733.     int numBytes = (p+7)/8;
  734.     byte[] mag = new byte[numBytes];
  735.     for (int i=0; i<numBytes; i++)
  736.         mag[i] = magnitude[i + (magnitude.length - numBytes)];
  737.  
  738.     /* Mask out any excess bits */
  739.     int excessBits = 8*numBytes - p;
  740.     mag[0] &= (1 << (8-excessBits)) - 1;
  741.  
  742.     return (mag[0]==0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
  743.     }
  744.  
  745.     /**
  746.      * Returns a BigInteger whose value is <tt>(this<sup>-1</sup> mod m)</tt>.
  747.      *
  748.      * @param  m the modulus.
  749.      * @return <tt>this<sup>-1</sup> mod m</tt>.
  750.      * @throws ArithmeticException <tt> m <= 0</tt>, or this BigInteger
  751.      *           has no multiplicative inverse mod m (that is, this BigInteger
  752.      *           is not <i>relatively prime</i> to m).
  753.      */
  754.     public BigInteger modInverse(BigInteger m) {
  755.     if (m.signum != 1)
  756.         throw new ArithmeticException("BigInteger: modulus not positive");
  757.  
  758.     /* Calculate (this mod m) */
  759.     BigInteger modVal = this.remainder(m);
  760.     if (modVal.signum < 0)
  761.         modVal = modVal.add(m);
  762.     if (!modVal.gcd(m).equals(ONE))
  763.         throw new ArithmeticException("BigInteger not invertible");
  764.  
  765.     return new BigInteger(plumbModInverse(modVal.magnitude,m.magnitude),1);
  766.     }
  767.  
  768.  
  769.     // Shift Operations
  770.  
  771.     /**
  772.      * Returns a BigInteger whose value is <tt>(this << n)</tt>.
  773.      * The shift distance, <tt>n</tt>, may be negative, in which case
  774.      * this method performs a right shift.
  775.      * (Computes <tt>floor(this * 2<sup>n</sup>)</tt>.)
  776.      *
  777.      * @param  n shift distance, in bits.
  778.      * @return <tt>this << n</tt>
  779.      * @see #shiftRight
  780.      */
  781.     public BigInteger shiftLeft(int n) {
  782.     if (n==0)
  783.         return this;
  784.     if (n<0)
  785.         return shiftRight(-n);
  786.  
  787.     int nBytes = n/8;
  788.     int nBits = n%8;
  789.  
  790.     byte result[] = new byte[(bitLength()+n)/8+1];
  791.     if (nBits == 0) {
  792.         for (int i=nBytes; i<result.length; i++)
  793.         result[result.length-1-i] = getByte(i-nBytes);
  794.     } else {
  795.         for (int i=nBytes; i<result.length; i++)
  796.         result[result.length-1-i] = (byte)
  797.             ((getByte(i-nBytes) << nBits)
  798.             | (i==nBytes ? 0
  799.                : ((getByte(i-nBytes-1)&0xff) >> (8-nBits))));
  800.     }
  801.  
  802.     return valueOf(result);
  803.     }
  804.  
  805.     /**
  806.      * Returns a BigInteger whose value is <tt>(this >> n)</tt>.  Sign
  807.      * extension is performed.  The shift distance, <tt>n</tt>, may be
  808.      * negative, in which case this method performs a left shift.
  809.      * (Computes <tt>floor(this / 2<sup>n</sup>)</tt>.) 
  810.      *
  811.      * @param  n shift distance, in bits.
  812.      * @return <tt>this >> n</tt>
  813.      * @see #shiftLeft
  814.      */
  815.     public BigInteger shiftRight(int n) {
  816.     if (n==0)
  817.         return this;
  818.     if (n<0)
  819.         return shiftLeft(-n);
  820.     if (n >= bitLength())
  821.         return (signum<0 ? valueOf(-1) : ZERO);
  822.  
  823.     int nBytes = n/8;
  824.     int nBits = n%8;
  825.  
  826.     byte result[] = new byte[(bitLength-n)/8+1];
  827.     if (nBits == 0) {
  828.         for (int i=0; i<result.length; i++)
  829.         result[result.length-1-i] = getByte(nBytes+i);
  830.     } else {
  831.         for (int i=0; i<result.length; i++)
  832.         result[result.length-1-i] = (byte)
  833.         ((getByte(nBytes+i+1)<<8 | (getByte(nBytes+i)&0xff)) >> nBits);
  834.     }
  835.  
  836.     return valueOf(result);
  837.     }
  838.  
  839.  
  840.     // Bitwise Operations
  841.  
  842.     /**
  843.      * Returns a BigInteger whose value is <tt>(this & val)</tt>.  (This
  844.      * method returns a negative BigInteger if and only if this and val are
  845.      * both negative.)
  846.      *
  847.      * @param val value to be AND'ed with this BigInteger.
  848.      * @return <tt>this & val</tt>
  849.      */
  850.     public BigInteger and(BigInteger val) {
  851.     byte[] result = new byte[Math.max(byteLength(), val.byteLength())];
  852.     for (int i=0; i<result.length; i++)
  853.         result[i] = (byte) (getByte(result.length-i-1)
  854.                 & val.getByte(result.length-i-1));
  855.  
  856.     return valueOf(result);
  857.     }
  858.  
  859.     /**
  860.      * Returns a BigInteger whose value is <tt>(this | val)</tt>.  (This method
  861.      * returns a negative BigInteger if and only if either this or val is
  862.      * negative.) 
  863.      *
  864.      * @param val value to be OR'ed with this BigInteger.
  865.      * @return <tt>this | val</tt>
  866.      */
  867.     public BigInteger or(BigInteger val) {
  868.     byte[] result = new byte[Math.max(byteLength(), val.byteLength())];
  869.     for (int i=0; i<result.length; i++)
  870.         result[i] = (byte) (getByte(result.length-i-1)
  871.                 | val.getByte(result.length-i-1));
  872.  
  873.     return valueOf(result);
  874.     }
  875.  
  876.     /**
  877.      * Returns a BigInteger whose value is <tt>(this ^ val)</tt>.  (This method
  878.      * returns a negative BigInteger if and only if exactly one of this and
  879.      * val are negative.)
  880.      *
  881.      * @param val value to be XOR'ed with this BigInteger.
  882.      * @return <tt>this ^ val</tt>
  883.      */
  884.     public BigInteger xor(BigInteger val) {
  885.     byte[] result = new byte[Math.max(byteLength(), val.byteLength())];
  886.     for (int i=0; i<result.length; i++)
  887.         result[i] = (byte) (getByte(result.length-i-1)
  888.                 ^ val.getByte(result.length-i-1));
  889.  
  890.     return valueOf(result);
  891.     }
  892.  
  893.     /**
  894.      * Returns a BigInteger whose value is <tt>(~this)</tt>.  (This method
  895.      * returns a negative value if and only if this BigInteger is
  896.      * non-negative.)
  897.      *
  898.      * @return <tt>~this</tt>
  899.      */
  900.     public BigInteger not() {
  901.     byte[] result = new byte[byteLength()];
  902.     for (int i=0; i<result.length; i++)
  903.         result[i] = (byte) ~getByte(result.length-i-1);
  904.  
  905.     return valueOf(result);
  906.     }
  907.  
  908.     /**
  909.      * Returns a BigInteger whose value is <tt>(this & ~val)</tt>.  This
  910.      * method, which is equivalent to <tt>and(val.not())</tt>, is provided as
  911.      * a convenience for masking operations.  (This method returns a negative
  912.      * BigInteger if and only if <tt>this</tt> is negative and <tt>val</tt> is
  913.      * positive.)
  914.      *
  915.      * @param val value to be complemented and AND'ed with this BigInteger.
  916.      * @return <tt>this & ~val</tt>
  917.      */
  918.     public BigInteger andNot(BigInteger val) {
  919.     byte[] result = new byte[Math.max(byteLength(), val.byteLength())];
  920.     for (int i=0; i<result.length; i++)
  921.         result[i] = (byte) (getByte(result.length-i-1)
  922.                 & ~val.getByte(result.length-i-1));
  923.  
  924.     return valueOf(result);
  925.     }
  926.  
  927.  
  928.     // Single Bit Operations
  929.  
  930.     /**
  931.      * Returns <tt>true</tt> if and only if the designated bit is set.
  932.      * (Computes <tt>((this & (1<<n)) != 0)</tt>.)
  933.      *
  934.      * @param  n index of bit to test.
  935.      * @return <tt>true</tt> if and only if the designated bit is set.
  936.      * @throws ArithmeticException <tt>n</tt> is negative.
  937.      */
  938.     public boolean testBit(int n) {
  939.     if (n<0)
  940.         throw new ArithmeticException("Negative bit address");
  941.  
  942.     return (getByte(n/8) & (1 << (n%8))) != 0;
  943.     }
  944.  
  945.     /**
  946.      * Returns a BigInteger whose value is equivalent to this BigInteger
  947.      * with the designated bit set.  (Computes <tt>(this | (1<<n))</tt>.)
  948.      *
  949.      * @param  n index of bit to set.
  950.      * @return <tt>this | (1<<n)</tt>
  951.      * @throws ArithmeticException <tt>n</tt> is negative.
  952.      */
  953.     public BigInteger setBit(int n) {
  954.     if (n<0)
  955.         throw new ArithmeticException("Negative bit address");
  956.  
  957.     int byteNum = n/8;
  958.     byte[] result = new byte[Math.max(byteLength(), byteNum+2)];
  959.  
  960.     for (int i=0; i<result.length; i++)
  961.         result[result.length-i-1] = getByte(i);
  962.  
  963.     result[result.length-byteNum-1] |= (1 << (n%8));
  964.  
  965.     return valueOf(result);
  966.     }
  967.  
  968.     /**
  969.      * Returns a BigInteger whose value is equivalent to this BigInteger
  970.      * with the designated bit cleared.
  971.      * (Computes <tt>(this & ~(1<<n))</tt>.)
  972.      *
  973.      * @param  n index of bit to clear.
  974.      * @return <tt>this & ~(1<<n)</tt>
  975.      * @throws ArithmeticException <tt>n</tt> is negative.
  976.      */
  977.     public BigInteger clearBit(int n) {
  978.     if (n<0)
  979.         throw new ArithmeticException("Negative bit address");
  980.  
  981.     int byteNum = n/8;
  982.     byte[] result = new byte[Math.max(byteLength(), (n+1)/8+1)];
  983.  
  984.     for (int i=0; i<result.length; i++)
  985.         result[result.length-i-1] = getByte(i);
  986.  
  987.     result[result.length-byteNum-1] &= ~(1 << (n%8));
  988.  
  989.     return valueOf(result);
  990.     }
  991.  
  992.     /**
  993.      * Returns a BigInteger whose value is equivalent to this BigInteger
  994.      * with the designated bit flipped.
  995.      * (Computes <tt>(this ^ (1<<n))</tt>.)
  996.      *
  997.      * @param  n index of bit to flip.
  998.      * @return <tt>this ^ (1<<n)</tt>
  999.      * @throws ArithmeticException <tt>n</tt> is negative.
  1000.      */
  1001.     public BigInteger flipBit(int n) {
  1002.     if (n<0)
  1003.         throw new ArithmeticException("Negative bit address");
  1004.  
  1005.     int byteNum = n/8;
  1006.     byte[] result = new byte[Math.max(byteLength(), byteNum+2)];
  1007.  
  1008.     for (int i=0; i<result.length; i++)
  1009.         result[result.length-i-1] = getByte(i);
  1010.  
  1011.     result[result.length-byteNum-1] ^= (1 << (n%8));
  1012.  
  1013.     return valueOf(result);
  1014.     }
  1015.  
  1016.     /**
  1017.      * Returns the index of the rightmost (lowest-order) one bit in this
  1018.      * BigInteger (the number of zero bits to the right of the rightmost
  1019.      * one bit).  Returns -1 if this BigInteger contains no one bits.
  1020.      * (Computes <tt>(this==0? -1 : log<sub>2</sub>(this & -this))</tt>.)
  1021.      *
  1022.      * @return index of the rightmost one bit in this BigInteger.
  1023.      */
  1024.     public int getLowestSetBit() {
  1025.     /*
  1026.      * Initialize lowestSetBit field the first time this method is
  1027.      * executed. This method depends on the atomicity of int modifies;
  1028.      * without this guarantee, it would have to be synchronized.
  1029.      */
  1030.     if (lowestSetBit == -2) {
  1031.         if (signum == 0) {
  1032.         lowestSetBit = -1;
  1033.         } else {
  1034.         /* Search for lowest order nonzero byte */
  1035.         int i;
  1036.         byte b;
  1037.         for (i=0; (b = getByte(i))==0; i++)
  1038.             ;
  1039.         lowestSetBit = 8*i + trailingZeroCnt[b & 0xFF];
  1040.         }
  1041.     }
  1042.     return lowestSetBit;
  1043.     }
  1044.  
  1045.  
  1046.     // Miscellaneous Bit Operations
  1047.  
  1048.     /**
  1049.      * Returns the number of bits in the minimal two's-complement
  1050.      * representation of this BigInteger, <i>excluding</i> a sign bit.
  1051.      * For positive BigIntegers, this is equivalent to the number of bits in
  1052.      * the ordinary binary representation.  (Computes
  1053.      * <tt>(ceil(log<sub>2</sub>(this < 0 ? -this : this+1)))</tt>.)
  1054.      *
  1055.      * @return number of bits in the minimal two's-complement
  1056.      *         representation of this BigInteger, <i>excluding</i> a sign bit.
  1057.      */
  1058.     public int bitLength() {
  1059.     /*
  1060.      * Initialize bitLength field the first time this method is executed.
  1061.      * This method depends on the atomicity of int modifies; without
  1062.      * this guarantee, it would have to be synchronized.
  1063.      */
  1064.     if (bitLength == -1) {
  1065.         if (signum == 0) {
  1066.         bitLength = 0;
  1067.         } else {
  1068.         /* Calculate the bit length of the magnitude */
  1069.         int magBitLength = 8*(magnitude.length-1)
  1070.                        + bitLen[magnitude[0] & 0xff];
  1071.  
  1072.         if (signum < 0) {
  1073.             /* Check if magnitude is a power of two */
  1074.             boolean pow2 = (bitCnt[magnitude[0]&0xff] == 1);
  1075.             for(int i=1; i<magnitude.length && pow2; i++)
  1076.             pow2 = (magnitude[i]==0);
  1077.  
  1078.             bitLength = (pow2 ? magBitLength-1 : magBitLength);
  1079.         } else {
  1080.             bitLength = magBitLength;
  1081.         }
  1082.         }
  1083.     }
  1084.     return bitLength;
  1085.     }
  1086.  
  1087.     /*
  1088.      * bitLen[i] is the number of bits in the binary representation of i.
  1089.      */
  1090.     private final static byte bitLen[] = {
  1091.     0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  1092.     5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  1093.     6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  1094.     6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  1095.     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  1096.     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  1097.     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  1098.     7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  1099.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  1100.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  1101.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  1102.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  1103.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  1104.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  1105.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  1106.     8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8};
  1107.  
  1108.     /**
  1109.      * Returns the number of bits in the two's complement representation
  1110.      * of this BigInteger that differ from its sign bit.  This method is
  1111.      * useful when implementing bit-vector style sets atop BigIntegers.
  1112.      *
  1113.      * @return number of bits in the two's complement representation
  1114.      *         of this BigInteger that differ from its sign bit.
  1115.      */
  1116.     public int bitCount() {
  1117.     /*
  1118.      * Initialize bitCount field the first time this method is executed.
  1119.      * This method depends on the atomicity of int modifies; without
  1120.      * this guarantee, it would have to be synchronized.
  1121.      */
  1122.     if (bitCount == -1) {
  1123.         /* Count the bits in the magnitude */
  1124.         int magBitCount = 0;
  1125.         for (int i=0; i<magnitude.length; i++)
  1126.         magBitCount += bitCnt[magnitude[i] & 0xff];
  1127.  
  1128.         if (signum < 0) {
  1129.         /* Count the trailing zeros in the magnitude */
  1130.         int magTrailingZeroCount = 0, j;
  1131.         for (j=magnitude.length-1; magnitude[j]==0; j--)
  1132.             magTrailingZeroCount += 8;
  1133.         magTrailingZeroCount += trailingZeroCnt[magnitude[j] & 0xff];
  1134.  
  1135.         bitCount = magBitCount + magTrailingZeroCount - 1;
  1136.         } else {
  1137.         bitCount = magBitCount;
  1138.         }
  1139.     }
  1140.     return bitCount;
  1141.     }
  1142.  
  1143.     /*
  1144.      * bitCnt[i] is the number of 1 bits in the binary representation of i.
  1145.      */
  1146.     private final static byte bitCnt[] = {
  1147.     0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
  1148.     1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  1149.     1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  1150.     2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1151.     1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  1152.     2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1153.     2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1154.     3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  1155.     1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  1156.     2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1157.     2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1158.     3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  1159.     2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1160.     3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  1161.     3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  1162.     4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
  1163.  
  1164.     /*
  1165.      * trailingZeroCnt[i] is the number of trailing zero bits in the binary
  1166.      * representaion of i.
  1167.      */
  1168.     private final static byte trailingZeroCnt[] = {
  1169.     8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1170.     4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1171.     5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1172.     4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1173.     6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1174.     4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1175.     5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1176.     4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1177.     7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1178.     4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1179.     5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1180.     4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1181.     6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1182.     4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1183.     5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1184.     4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
  1185.  
  1186.  
  1187.  
  1188.     // Primality Testing
  1189.  
  1190.     /**
  1191.      * Returns <tt>true</tt> if this BigInteger is probably prime,
  1192.      * <tt>false</tt> if it's definitely composite.
  1193.      *
  1194.      * @param  certainty a measure of the uncertainty that the caller is
  1195.      *           willing to tolerate: if the call returns <tt>true</tt>
  1196.      *           the probability that this BigInteger is prime exceeds
  1197.      *           <tt>(1 - 1/2<sup>certainty</sup>)</tt>.  The execution time of
  1198.      *            this method is proportional to the value of this parameter.
  1199.      * @return <tt>true</tt> if this BigInteger is probably prime,
  1200.      *            <tt>false</tt> if it's definitely composite.
  1201.      */
  1202.     public boolean isProbablePrime(int certainty) {
  1203.     /*
  1204.      * This test is taken from the DSA spec.
  1205.      */
  1206.     int n = (certainty+1)/2;
  1207.     if (n <= 0)
  1208.         return true;
  1209.     BigInteger w = this.abs();
  1210.     if (w.equals(TWO))
  1211.         return true;
  1212.     if (!w.testBit(0) || w.equals(ONE))
  1213.         return false;
  1214.  
  1215.     // Find a and m such that m is odd and w == 1 + 2**a * m
  1216.     BigInteger m = w.subtract(ONE);
  1217.     int a = m.getLowestSetBit();
  1218.     m = m.shiftRight(a);
  1219.  
  1220.     // Do the tests
  1221.         Random rnd = new Random();
  1222.     for(int i=0; i<n; i++) {
  1223.         /* Generate a uniform random on (1, w) */
  1224.         BigInteger b;
  1225.         do {
  1226.         b = new BigInteger(w.bitLength(), rnd);
  1227.         } while (b.compareTo(ONE) <= 0 || b.compareTo(w) >= 0);
  1228.  
  1229.         int j = 0;
  1230.         BigInteger z = b.modPow(m, w);
  1231.         while(!((j==0 && z.equals(ONE)) || z.equals(w.subtract(ONE)))) {
  1232.         if (j>0 && z.equals(ONE) || ++j==a)
  1233.             return false;
  1234.         z = z.modPow(TWO, w);
  1235.         }
  1236.     }
  1237.     return true;
  1238.     }
  1239.  
  1240.     // Comparison Operations
  1241.  
  1242.     /**
  1243.      * Compares this BigInteger with the specified BigInteger.  This method is
  1244.      * provided in preference to individual methods for each of the six
  1245.      * boolean comparison operators (<, ==, >, >=, !=, <=).  The
  1246.      * suggested idiom for performing these comparisons is:
  1247.      * <tt>(x.compareTo(y)</tt> <<i>op</i>> <tt>0)</tt>,
  1248.      * where <<i>op</i>> is one of the six comparison operators.
  1249.      *
  1250.      * @param  val BigInteger to which this BigInteger is to be compared.
  1251.      * @return -1, 0 or 1 as this BigInteger is numerically less than, equal
  1252.      *         to, or greater than <tt>val</tt>.
  1253.      */
  1254.     public int compareTo(BigInteger val) {
  1255.     return (signum==val.signum
  1256.         ? signum*byteArrayCmp(magnitude, val.magnitude)
  1257.         : (signum>val.signum ? 1 : -1));
  1258.     }
  1259.  
  1260.     /**
  1261.      * Compares this BigInteger with the specified Object.  If the Object is a
  1262.      * BigInteger, this method behaves like <tt>compareTo(BigInteger)</tt>.
  1263.      * Otherwise, it throws a <tt>ClassCastException</tt> (as BigIntegers are
  1264.      * comparable only to other BigIntegers).
  1265.      *
  1266.      * @param   o Object to which this BigInteger is to be compared.
  1267.      * @return  a negative number, zero, or a positive number as this
  1268.      *        BigInteger is numerically less than, equal to, or greater
  1269.      *        than <tt>o</tt>, which must be a BigInteger.
  1270.      * @throws  ClassCastException <tt>o</tt> is not a BigInteger.
  1271.      * @see     #compareTo(java.math.BigInteger)
  1272.      * @see     Comparable
  1273.      * @since   JDK1.2
  1274.      */
  1275.     public int compareTo(Object o) {
  1276.     return compareTo((BigInteger)o);
  1277.     }
  1278.  
  1279.     /*
  1280.      * Returns -1, 0 or +1 as big-endian unsigned byte array arg1 is
  1281.      * less than, equal to, or greater than arg2.
  1282.      */
  1283.     private static int byteArrayCmp(byte[] arg1, byte[] arg2) {
  1284.     if (arg1.length < arg2.length)
  1285.         return -1;
  1286.     if (arg1.length > arg2.length)
  1287.         return 1;
  1288.  
  1289.     /* Argument lengths are equal; compare the values */
  1290.     for (int i=0; i<arg1.length; i++) {
  1291.         int b1 = arg1[i] & 0xff;
  1292.         int b2 = arg2[i] & 0xff;
  1293.         if (b1 < b2)
  1294.         return -1;
  1295.         if (b1 > b2)
  1296.         return 1;
  1297.     }
  1298.     return 0;
  1299.     }
  1300.  
  1301.     /**
  1302.      * Compares this BigInteger with the specified Object for equality.
  1303.      *
  1304.      * @param  o Object to which this BigInteger is to be compared.
  1305.      * @return <tt>true</tt> if and only if the specified Object is a
  1306.      *           BigInteger whose value is numerically equal to this BigInteger.
  1307.      */
  1308.     public boolean equals(Object x) {
  1309.     // This test is just an optimization, which may or may not help
  1310.     if (x == this)
  1311.         return true;
  1312.  
  1313.     if (!(x instanceof BigInteger))
  1314.         return false;
  1315.     BigInteger xInt = (BigInteger) x;
  1316.  
  1317.     if (xInt.signum != signum || xInt.magnitude.length != magnitude.length)
  1318.         return false;
  1319.  
  1320.     for (int i=0; i<magnitude.length; i++)
  1321.         if (xInt.magnitude[i] != magnitude[i])
  1322.         return false;
  1323.  
  1324.     return true;
  1325.     }
  1326.  
  1327.     /**
  1328.      * Returns the minimum of this BigInteger and <tt>val</tt>.
  1329.      *
  1330.      * @param  val value with with the minimum is to be computed.
  1331.      * @return the BigInteger whose value is the lesser of this BigInteger and 
  1332.      *           <tt>val</tt>.  If they are equal, either may be returned.
  1333.      */
  1334.     public BigInteger min(BigInteger val) {
  1335.     return (compareTo(val)<0 ? this : val);
  1336.     }
  1337.  
  1338.     /**
  1339.      * Returns the maximum of this BigInteger and <tt>val</tt>.
  1340.      *
  1341.      * @param  val value with with the maximum is to be computed.
  1342.      * @return the BigInteger whose value is the greater of this and
  1343.      *         <tt>val</tt>.  If they are equal, either may be returned.
  1344.      */
  1345.     public BigInteger max(BigInteger val) {
  1346.     return (compareTo(val)>0 ? this : val);
  1347.     }
  1348.  
  1349.  
  1350.     // Hash Function
  1351.  
  1352.     /**
  1353.      * Returns the hash code for this BigInteger.
  1354.      *
  1355.      * @return hash code for this BigInteger.
  1356.      */
  1357.     public int hashCode() {
  1358.     int hashCode = 0;
  1359.  
  1360.     for (int i=0; i<magnitude.length; i++)
  1361.         hashCode = 31*hashCode + (magnitude[i] & 0xff);
  1362.  
  1363.     return hashCode * signum;
  1364.     }
  1365.  
  1366.     // Format Converters
  1367.  
  1368.     /**
  1369.      * Returns the String representation of this BigInteger in the given radix.
  1370.      * If the radix is outside the range from <tt>Character.MIN_RADIX</tt> (2)
  1371.      * to <tt>Character.MAX_RADIX</tt> (36) inclusive, it will default to 10
  1372.      * (as is the case for <tt>Integer.toString</tt>).  The digit-to-character
  1373.      * mapping provided by <tt>Character.forDigit</tt> is used, and a minus
  1374.      * sign is prepended if appropriate.  (This representation is compatible
  1375.      * with the (String, int) constructor.)
  1376.      *
  1377.      * @param  radix  radix of the String representation.
  1378.      * @return String representation of this BigInteger in the given radix.
  1379.      * @see    Integer#toString
  1380.      * @see    Character#forDigit
  1381.      * @see    #BigInteger(java.lang.String, int)
  1382.      */
  1383.     public String toString(int radix) {
  1384.     if (signum == 0)
  1385.         return "0";
  1386.     if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  1387.         radix = 10;
  1388.  
  1389.     /* Compute upper bound on number of digit groups and allocate space */
  1390.     int maxNumDigitGroups = (magnitude.length + 6)/7;
  1391.     String digitGroup[] = new String[maxNumDigitGroups];
  1392.  
  1393.     /* Translate number to string, a digit group at a time */
  1394.     BigInteger tmp = this.abs();
  1395.     int numGroups = 0;
  1396.     while (tmp.signum != 0) {
  1397.         BigInteger b[] = tmp.divideAndRemainder(longRadix[radix]);
  1398.         digitGroup[numGroups++] = Long.toString(b[1].longValue(), radix);
  1399.         tmp = b[0];
  1400.     }
  1401.  
  1402.     /* Put sign (if any) and first digit group into result buffer */
  1403.     StringBuffer buf = new StringBuffer(numGroups*digitsPerLong[radix]+1);
  1404.     if (signum<0)
  1405.         buf.append('-');
  1406.     buf.append(digitGroup[numGroups-1]);
  1407.  
  1408.     /* Append remaining digit groups padded with leading zeros */
  1409.     for (int i=numGroups-2; i>=0; i--) {
  1410.         /* Prepend (any) leading zeros for this digit group */
  1411.         int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
  1412.         if (numLeadingZeros != 0)
  1413.         buf.append(zeros[numLeadingZeros]);
  1414.         buf.append(digitGroup[i]);
  1415.     }
  1416.  
  1417.     return buf.toString();
  1418.     }
  1419.  
  1420.     /* zero[i] is a string of i consecutive zeros. */
  1421.     private static String zeros[] = new String[64];
  1422.     static {
  1423.     zeros[63] =
  1424.         "000000000000000000000000000000000000000000000000000000000000000";
  1425.     for (int i=0; i<63; i++)
  1426.         zeros[i] = zeros[63].substring(0, i);
  1427.     }
  1428.  
  1429.     /**
  1430.      * Returns the decimal String representation of this BigInteger.  The
  1431.      * digit-to-character mapping provided by <tt>Character.forDigit</tt> is
  1432.      * used, and a minus sign is prepended if appropriate.  (This
  1433.      * representation is compatible with the (String) constructor, and allows
  1434.      * for String concatenation with Java's + operator.)
  1435.      *
  1436.      * @return decimal String representation of this BigInteger.
  1437.      * @see    Character#forDigit
  1438.      * @see    #BigInteger(java.lang.String)
  1439.      */
  1440.     public String toString() {
  1441.     return toString(10);
  1442.     }
  1443.  
  1444.     /**
  1445.      * Returns a byte array containing the two's-complement representation of
  1446.      * this BigInteger.  The byte array will be in <i>big-endian</i>
  1447.      * byte-order: the most significant byte is in the zeroth element.  The
  1448.      * array will contain the minimum number of bytes required to represent
  1449.      * this BigInteger, including at least one sign bit,  which is
  1450.      * <tt>(ceil((this.bitLength() + 1)/8))</tt>.  (This representation is
  1451.      * compatible with the (byte[]) constructor.) 
  1452.      *
  1453.      * @return a byte array containing the two's-complement representation of
  1454.      *           this BigInteger.
  1455.      * @see    #BigInteger(byte[])
  1456.      */
  1457.     public byte[] toByteArray() {
  1458.     byte[] result = new byte[byteLength()];
  1459.     for(int i=0; i<result.length; i++)
  1460.         result[i] = getByte(result.length-i-1);
  1461.  
  1462.     return result;
  1463.     }
  1464.  
  1465.     /**
  1466.      * Converts this BigInteger to an int.  Standard <i>narrowing primitive
  1467.      * conversion</i> as defined in <i>The Java Language Specification</i>:
  1468.      * if this BigInteger is too big to fit in an int, only the low-order
  1469.      * 32 bits are returned.
  1470.      *
  1471.      * @return this BigInteger converted to an int.
  1472.      */
  1473.     public int intValue() {
  1474.     int result = 0;
  1475.  
  1476.     for (int i=3; i>=0; i--)
  1477.         result = (result << 8) + (getByte(i) & 0xff);
  1478.     return result;
  1479.     }
  1480.  
  1481.     /**
  1482.      * Converts this BigInteger to a long.  Standard <i>narrowing primitive
  1483.      * conversion</i> as defined in <i>The Java Language Specification</i>:
  1484.      * if this BigInteger is too big to fit in a long, only the low-order
  1485.      * 64 bits are returned.
  1486.      *
  1487.      * @return this BigInteger converted to a long.
  1488.      */
  1489.     public long longValue() {
  1490.     long result = 0;
  1491.  
  1492.     for (int i=7; i>=0; i--)
  1493.         result = (result << 8) + (getByte(i) & 0xff);
  1494.     return result;
  1495.     }
  1496.  
  1497.     /**
  1498.      * Converts this BigInteger to a float.  Similar to the double-to-float
  1499.      * <i>narrowing primitive conversion</i> defined in <i>The Java Language
  1500.      * Specification</i>: if this BigInteger has too great a magnitude to
  1501.      * represent as a float, it will be converted to infinity or negative
  1502.      * infinity, as appropriate.
  1503.      *
  1504.      * @return this BigInteger converted to a float.
  1505.      */
  1506.     public float floatValue() {
  1507.     // Somewhat inefficient, but guaranteed to work.
  1508.     return Float.valueOf(this.toString()).floatValue();
  1509.     }
  1510.  
  1511.     /**
  1512.      * Converts this BigInteger to a double.  Similar to the double-to-float
  1513.      * <i>narrowing primitive conversion</i> defined in <i>The Java Language
  1514.      * Specification</i>: if this BigInteger has too great a magnitude to
  1515.      * represent as a double, it will be converted to infinity or negative
  1516.      * infinity, as appropriate.
  1517.      *
  1518.      * @return this BigInteger converted to a double.
  1519.      */
  1520.     public double doubleValue() {
  1521.     // Somewhat inefficient, but guaranteed to work.
  1522.     return Double.valueOf(this.toString()).doubleValue();
  1523.     }
  1524.  
  1525.     static {
  1526.     java.security.AccessController.doPrivileged(
  1527.           new sun.security.action.LoadLibraryAction("math"));
  1528.     plumbInit();
  1529.     }
  1530.  
  1531.  
  1532.     /**
  1533.      * Returns a copy of the input array stripped of any leading zero bytes.
  1534.      */
  1535.     static private byte[] stripLeadingZeroBytes(byte a[]) {
  1536.     int keep;
  1537.  
  1538.     /* Find first nonzero byte */
  1539.     for (keep=0; keep<a.length && a[keep]==0; keep++)
  1540.         ;
  1541.  
  1542.     /* Allocate new array and copy relevant part of input array */
  1543.     byte result[] = new byte[a.length - keep];
  1544.     for (int i = keep; i<a.length; i++)
  1545.         result[i - keep] = a[i];
  1546.  
  1547.     return result;
  1548.     }
  1549.  
  1550.     /**
  1551.      * Takes an array a representing a negative 2's-complement number and
  1552.      * returns the minimal (no leading zero bytes) unsigned whose value is -a.
  1553.      */
  1554.     static private byte[] makePositive(byte a[]) {
  1555.     int keep, j;
  1556.  
  1557.     /* Find first non-sign (0xff) byte of input */
  1558.     for (keep=0; keep<a.length && a[keep]==-1; keep++)
  1559.         ;
  1560.  
  1561.     /* Allocate output array.  If all non-sign bytes are 0x00, we must
  1562.      * allocate space for one extra output byte. */
  1563.     for (j=keep; j<a.length && a[j]==0; j++)
  1564.         ;
  1565.     int extraByte = (j==a.length ? 1 : 0);
  1566.     byte result[] = new byte[a.length - keep + extraByte];
  1567.  
  1568.     /* Copy one's complement of input into into output, leaving extra
  1569.      * byte (if it exists) == 0x00 */
  1570.     for (int i = keep; i<a.length; i++)
  1571.         result[i - keep + extraByte] = (byte) ~a[i];
  1572.  
  1573.     /* Add one to one's complement to generate two's complement */
  1574.     for (int i=result.length-1; ++result[i]==0; i--)
  1575.         ;
  1576.  
  1577.     return result;
  1578.     }
  1579.  
  1580.     /*
  1581.      * The following two arrays are used for fast String conversions.  Both
  1582.      * are indexed by radix.  The first is the number of digits of the given
  1583.      * radix that can fit in a Java long without "going negative", i.e., the
  1584.      * highest integer n such that radix**n < 2**63.  The second is the
  1585.      * "long radix" that tears each number into "long digits", each of which
  1586.      * consists of the number of digits in the corresponding element in
  1587.      * digitsPerLong (longRadix[i] = i**digitPerLong[i]).  Both arrays have
  1588.      * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
  1589.      * used.
  1590.      */
  1591.  
  1592.     private static int digitsPerLong[] = {0, 0,
  1593.     62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
  1594.     14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
  1595.  
  1596.     private static BigInteger longRadix[] = {null, null,
  1597.         valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
  1598.     valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
  1599.     valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
  1600.         valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
  1601.     valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
  1602.     valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
  1603.     valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
  1604.     valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
  1605.     valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
  1606.     valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
  1607.     valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
  1608.     valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
  1609.     valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
  1610.     valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
  1611.     valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
  1612.     valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
  1613.     valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
  1614.     valueOf(0x41c21cb8e1000000L)};
  1615.  
  1616.  
  1617.     /**
  1618.      * These routines provide access to the two's complement representation
  1619.      * of BigIntegers.
  1620.      */
  1621.  
  1622.     /**
  1623.      * Returns the length of the two's complement representation in bytes,
  1624.      * including space for at least one sign bit,
  1625.      */
  1626.     private int byteLength() {
  1627.     return bitLength()/8 + 1;
  1628.     }
  1629.  
  1630.     /* Returns sign bit */
  1631.     private int signBit() {
  1632.     return (signum < 0 ? 1 : 0);
  1633.     }
  1634.  
  1635.     /* Returns a byte of sign bits */
  1636.     private byte signByte() {
  1637.     return (byte) (signum < 0 ? -1 : 0);
  1638.     }
  1639.  
  1640.     /**
  1641.      * Returns the specified byte of the little-endian two's complement
  1642.      * representation (byte 0 is the LSB).  The byte number can be arbitrarily
  1643.      * high (values are logically preceded by infinitely many sign bytes).
  1644.      */
  1645.     private byte getByte(int n) {
  1646.     if (n >= magnitude.length)
  1647.         return signByte();
  1648.  
  1649.     byte magByte = magnitude[magnitude.length-n-1];
  1650.  
  1651.     return (byte) (signum >= 0 ? magByte :
  1652.                (n <= firstNonzeroByteNum() ? -magByte : ~magByte));
  1653.     }
  1654.  
  1655.     /**
  1656.      * Returns the index of the first nonzero byte in the little-endian
  1657.      * binary representation of the magnitude (byte 0 is the LSB).  If
  1658.      * the magnitude is zero, return value is undefined.
  1659.      */
  1660.  
  1661.      private int firstNonzeroByteNum() {
  1662.     /*
  1663.      * Initialize firstNonzeroByteNum field the first time this method is
  1664.      * executed. This method depends on the atomicity of int modifies;
  1665.      * without this guarantee, it would have to be synchronized.
  1666.      */
  1667.     if (firstNonzeroByteNum == -2) {
  1668.         /* Search for the first nonzero byte */
  1669.         int i;
  1670.         for (i=magnitude.length-1; i>=0 && magnitude[i]==0; i--)
  1671.         ;
  1672.         firstNonzeroByteNum = magnitude.length-i-1;
  1673.     }
  1674.     return firstNonzeroByteNum;
  1675.     }
  1676.  
  1677.  
  1678.     /**
  1679.      * Native method wrappers for Colin Plumb's big positive integer package.
  1680.      * Each of these wrappers (except for plumbInit) behaves as follows:
  1681.      *
  1682.      *     1) Translate input arguments from java byte arrays into plumbNums.
  1683.      *
  1684.      *  2) Perform the requested computation.
  1685.      *
  1686.      *  3) Translate result(s) into Java byte array(s).  (The subtract
  1687.      *       operation translates its result into a BigInteger, as its result
  1688.      *       is, effectively, signed.)
  1689.      *
  1690.      *    4) Deallocate all of the plumbNums.
  1691.      *
  1692.      *  5) Return the resulting Java array(s) (or, in the case of subtract,
  1693.      *       BigInteger).
  1694.      */
  1695.  
  1696.     private static native void plumbInit();
  1697.     private static native byte[] plumbAdd(byte[] a, byte[] b);
  1698.     private static native BigInteger plumbSubtract(byte[] a, byte[] b);
  1699.     private static native byte[] plumbMultiply(byte[] a, byte[] b);
  1700.     private static native byte[] plumbDivide(byte[] a, byte[] b);
  1701.     private static native byte[] plumbRemainder(byte[] a, byte[] b);
  1702.     private static native byte[][] plumbDivideAndRemainder(byte[] a, byte[] b);
  1703.     private static native byte[] plumbGcd(byte[] a, byte[] b);
  1704.     private static native byte[] plumbModPow(byte[] a, byte[] b, byte[] m);
  1705.     private static native byte[] plumbModInverse(byte[] a, byte[] m);
  1706.     private static native byte[] plumbSquare(byte[] a);
  1707.     private static native byte[] plumbGeneratePrime(byte[] a);
  1708.  
  1709.     /** use serialVersionUID from JDK 1.1. for interoperability */
  1710.     private static final long serialVersionUID = -8287574255936472291L;
  1711.  
  1712.     /**
  1713.      * Reconstitute the <tt>BigInteger</tt> instance from a stream (that is,
  1714.      * deserialize it).
  1715.      */
  1716.     private synchronized void readObject(java.io.ObjectInputStream s)
  1717.         throws java.io.IOException, ClassNotFoundException {
  1718.         // Read in all fields
  1719.     s.defaultReadObject();
  1720.  
  1721.         // Defensively copy magnitude to ensure immutability
  1722.         magnitude = (byte[]) magnitude.clone();
  1723.  
  1724.         // Validate signum
  1725.     if (signum < -1 || signum > 1)
  1726.         throw new java.io.StreamCorruptedException(
  1727.                         "BigInteger: Invalid signum value");
  1728.     if ((magnitude.length==0) != (signum==0))
  1729.         throw new java.io.StreamCorruptedException(
  1730.                         "BigInteger: signum-magnitude mismatch");
  1731.  
  1732.         // Set "cached computation" fields to their initial values
  1733.         bitCount = bitLength = -1;
  1734.         lowestSetBit = firstNonzeroByteNum = -2;
  1735.     }
  1736. }
  1737.