Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Coming from C++ to Java, the obvious unanswered question is why not operator overload. On the web some go about: "it's clearly obfuscated and complicate maintenance" but no one really elaborates that further (I completely disagree, actually). Other people pointed out that some objects do have an overload (like String operator +) but that is not extended to other objects nor is extensible to ...
It's Sunday, time for a round of code golf! Challenge Write the shortest source code by character count to determine if an input number is a "happy prime", "sad prime", "happy non-prime", or "sad non-prime." Input The input should be a integer that comes from a command line argument or stdin. Don't worry about handling big numbers, but do so if you can/want. Behavior would be undefined fo...
I'm trying to work with fractions in Java. I want to implement arithmetic functions. For this, I will first require a way to normalize the functions. I know I can't add 1/6 and 1/2 until I have a common denominator. I will have to add 1/6 and 3/6. A naive approach would have me add 2/12 and 6/12 and then reduce. How can I achieve a common denominator with the least performance penalty? W...
What is the most elegant way to implement this function: ArrayList generatePrimes(int n) This function generates the first n primes (edit: where n>1), so generatePrimes(5) will return an ArrayList with {2, 3, 5, 7, 11}. (I'm doing this in C#, but I'm happy with a Java implementation - or any other similar language for that matter (so not Haskell)). I do know how to write this function, b...
Dear ninjas / hackers / wizards, keywords: bignum, bigint, GMP, MPFR, decNumber, BigInteger, BigDecimal, java.math.BigInteger, java.math.BigDecimal, System.Numerics.BigInteger I'm looking for a good arbitrary precision math library in C or C++. Could you please give me some advices / suggestions? The primary requirements: It MUST handle arbitrarily big integers (my primary interest is on i...
In C++, I enjoyed having access to a 64 bit unsigned integer, via unsigned long long int, or via uint64_t. Now, in Java longs are 64 bits, I know. However, they are signed. Is there an unsigned long (long) available as a Java primitive? How do I use it?
I'm looking for a hash function that: Hashes textual strings well (e.g. few collisions) Is written in Java, and widely used Bonus: works on several fields (instead of me concatenating them and applying the hash on the concatenated string) Bonus: Has a 128-bit variant. Bonus: Not CPU intensive.
In several modern programming languages (including C++, Java, and C#), the language allows integer overflow to occur at runtime without raising any kind of error condition. For example, consider this (contrived) C# method, which does not account for the possibility of overflow/underflow. (For brevity, the method also doesn't handle the case where the specified list is a null reference.) //Re...
Summer is coming, and a group of friends and I are getting ready for it :) We decided to build a compile-time Arbitrary precision Unsigned Integers. We would like to provide a set of integers algorithms(functions) with the library. We have seen a number of requests for such a library(SoC2010, C++0x Standard Library wishlist). Also, a regular run-time bigint is requested usually with that, but ...
George Marsaglia has written an excellent random number generator that is extremely fast, simple, and has a much higher period than the Mersenne Twister. Here is the code with a description: good C random number generator I wanted to port the CMWC4096 code to Java, but it uses several unsigned datatypes so I am not sure how to do this properly. Here is the full C code: /* choose random initi...
You are given a list of n numbers L=. Each of them is either 0 or of the form +- 2^k, 0<=k<=30. Describe and implement an algorithm that returns the largest product of a CONTINUOUS SUBLIST p=a_i*a_i+1*...*a_j, 1 <= i <= j <= n. For example, for the input <8 0 -4 -2 0 1> it should return 8 (either 8 or (-4)*(-2)). You can use any standard programming language and can assume t...
Hugs> 94535^445 137632088232137705069605388766151562110489016400528215306972642477399980184684190324482770294348798270745496600945601673504187800060414350090853288746492038060516493211268703905952667210981892423492084444823161253257071865716023417728537773383010483404104907660991248823721960844599507286779843061493540321949588383504286280291798085677413475739078205220051293237566085804500358...
I need to generate arbitrarily large random integers in the range 0 (inclusive) to n (exclusive). My initial thought was to call nextDouble and multiply by n, but once n gets to be larger than 253, the results would no longer be uniformly distributed. BigInteger has the following constructor available: public BigInteger(int numBits, Random rnd) Constructs a randomly generated BigInteger...
I have made a program in Java that calculates powers of two, but it seems very inefficient. For smaller powers (2^4000, say), it does it in less than a second. However, I am looking at calculating 2^43112609, which is one greater than the largest known prime number. With over 12 million digits, it will take a very long time to run. Here's my code so far: import java.io.*; public class Power {...
How would i go about doing calculations with extremely large numbers in Java? i have tried long but that maxes out at 9223372036854775807, and when using an integer it does not save enough digits and therefore is not accurate enough for what i need. Is there anyway around this?
Was wondering how is it possible to generate 512 bit (155 decimal digits) prime number, last five decimal digits of which are specified/fixed (eg. ***28071) ?? The principles of generating simple primes without any specifications are quite understandable, but my case goes further. Any hints for, at least, where should I start? Java or C# is preferable. Thanks!
Assume my system as 32 bit machine. Considering this if I use long int for n>63 I will get my value as 0. How to solve it?
i want to multiply two 512 bit integers in java and store the result.suggest some method to do this.
How to add two numbers of any length in java? Say for example, in java long size is 64 bit. So the maximum range is -9223372036854775808 to 9223372036854775807. Am i right? So if we want to add a number which is greater than this like below, i got a error " Integer Number too large" long a = 9223372036854775807L; long b = 9223372036854775808L; In C, we can take those numbers as ...
I'm playing around and trying to write an implementation of RSA. The problem is that I'm stuck on generating the massive prime numbers that are involved in generating a key pair. Could someone point me to a fast way to generate huge primes/probable primes?
I am unsure about how to generate a random n digit integer in Java using the BigInteger class.
   /*
    * Portions Copyright 1996-2007 Sun Microsystems, Inc.  All Rights Reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code is free software; you can redistribute it and/or modify it
    * under the terms of the GNU General Public License version 2 only, as
    * published by the Free Software Foundation.  Sun designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Sun in the LICENSE file that accompanied this code.
   *
   * This code is distributed in the hope that it will be useful, but WITHOUT
   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   * version 2 for more details (a copy is included in the LICENSE file that
   * accompanied this code).
   *
   * You should have received a copy of the GNU General Public License version
   * 2 along with this work; if not, write to the Free Software Foundation,
   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   *
   * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   * CA 95054 USA or visit www.sun.com if you need additional information or
   * have any questions.
   */
  
  /*
   * Portions Copyright (c) 1995  Colin Plumb.  All rights reserved.
   */
  
  package java.math;
  
  import java.util.Random;
  import java.io.*;

Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types). BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java.lang.Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

Semantics of arithmetic operations exactly mimic those of Java's integer arithmetic operators, as defined in The Java Language Specification. For example, division by zero throws an ArithmeticException, and division of a negative by a positive yields a negative (or zero) remainder. All of the details in the Spec concerning overflow are ignored, as BigIntegers are made as large as necessary to accommodate the results of an operation.

Semantics of shift operations extend those of Java's shift operators to allow for negative shift distances. A right-shift with a negative shift distance results in a left shift, and vice-versa. The unsigned right shift operator (>>>) is omitted, as this operation makes little sense in combination with the "infinite word size" abstraction provided by this class.

Semantics of bitwise logical operations exactly mimic those of Java's bitwise integer operators. The binary operators (and, or, xor) implicitly perform sign extension on the shorter of the two operands prior to performing the operation.

Comparison operations perform signed integer comparisons, analogous to those performed by Java's relational and equality operators.

Modular arithmetic operations are provided to compute residues, perform exponentiation, and compute multiplicative inverses. These methods always return a non-negative result, between 0 and (modulus - 1), inclusive.

Bit operations operate on a single bit of the two's-complement representation of their operand. If necessary, the operand is sign- extended so that it contains the designated bit. None of the single-bit operations can produce a BigInteger with a different sign from the BigInteger being operated on, as they affect only a single bit, and the "infinite word size" abstraction provided by this class ensures that there are infinitely many "virtual sign bits" preceding each BigInteger.

For the sake of brevity and clarity, pseudo-code is used throughout the descriptions of BigInteger methods. The pseudo-code expression (i + j) is shorthand for "a BigInteger whose value is that of the BigInteger i plus that of the BigInteger j." The pseudo-code expression (i == j) is shorthand for "true if and only if the BigInteger i represents the same value as the BigInteger j." Other pseudo-code expressions are interpreted similarly.

All methods and constructors in this class throw NullPointerException when passed a null object reference for any input parameter.

Author(s):
Josh Bloch
Michael McCloskey
Since:
JDK1.1
See also:
BigDecimal
  
  
  public class BigInteger extends Number implements Comparable<BigInteger> {
    
The signum of this BigInteger: -1 for negative, 0 for zero, or 1 for positive. Note that the BigInteger zero must have a signum of 0. This is necessary to ensures that there is exactly one representation for each BigInteger value.

Serial:
 
     int signum;

    
The magnitude of this BigInteger, in big-endian order: the zeroth element of this array is the most-significant int of the magnitude. The magnitude must be "minimal" in that the most-significant int (mag[0]) must be non-zero. This is necessary to ensure that there is exactly one representation for each BigInteger value. Note that this implies that the BigInteger zero has a zero-length mag array.
 
     int[] mag;
 
     // These "redundant fields" are initialized with recognizable nonsense
     // values, and cached the first time they are needed (or never, if they
     // aren't needed).
 
    
The bitCount of this BigInteger, as returned by bitCount(), or -1 (either value is acceptable).

See also:
bitCount
Serial:
 
     private int bitCount =  -1;

    
The bitLength of this BigInteger, as returned by bitLength(), or -1 (either value is acceptable).

See also:
bitLength()
Serial:
 
     private int bitLength = -1;

    
The lowest set bit of this BigInteger, as returned by getLowestSetBit(), or -2 (either value is acceptable).

See also:
getLowestSetBit()
Serial:
 
     private int lowestSetBit = -2;

    
The index of the lowest-order byte in the magnitude of this BigInteger that contains a nonzero byte, or -2 (either value is acceptable). The least significant byte has int-number 0, the next byte in order of increasing significance has byte-number 1, and so forth.

Serial:
 
     private int firstNonzeroByteNum = -2;

    
The index of the lowest-order int in the magnitude of this BigInteger that contains a nonzero int, or -2 (either value is acceptable). The least significant int has int-number 0, the next int in order of increasing significance has int-number 1, and so forth.
 
     private int firstNonzeroIntNum = -2;

    
This mask is used to obtain the value of an int as if it were unsigned.
 
     private final static long LONG_MASK = 0xffffffffL;
 
     //Constructors
 
    
Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger. The input array is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element.

Parameters:
val big-endian two's-complement binary representation of BigInteger.
Throws:
java.lang.NumberFormatException val is zero bytes long.
 
     public BigInteger(byte[] val) {
         if (val.length == 0)
             throw new NumberFormatException("Zero length BigInteger");
 
         if (val[0] < 0) {
              = makePositive(val);
              = -1;
         } else {
              = stripLeadingZeroBytes(val);
              = (. == 0 ? 0 : 1);
         }
     }

    
This private constructor translates an int array containing the two's-complement binary representation of a BigInteger into a BigInteger. The input array is assumed to be in big-endian int-order: the most significant int is in the zeroth element.
 
     private BigInteger(int[] val) {
         if (val.length == 0)
             throw new NumberFormatException("Zero length BigInteger");
 
         if (val[0] < 0) {
              = makePositive(val);
              = -1;
         } else {
              = trustedStripLeadingZeroInts(val);
              = (. == 0 ? 0 : 1);
         }
     }

    
Translates the sign-magnitude representation of a BigInteger into a BigInteger. The sign is represented as an integer signum value: -1 for negative, 0 for zero, or 1 for positive. The magnitude is a byte array in big-endian byte-order: the most significant byte is in the zeroth element. A zero-length magnitude array is permissible, and will result in a BigInteger value of 0, whether signum is -1, 0 or 1.

Parameters:
signum signum of the number (-1 for negative, 0 for zero, 1 for positive).
magnitude big-endian binary representation of the magnitude of the number.
Throws:
java.lang.NumberFormatException signum is not one of the three legal values (-1, 0, and 1), or signum is 0 and magnitude contains one or more non-zero bytes.
 
     public BigInteger(int signumbyte[] magnitude) {
         this. = stripLeadingZeroBytes(magnitude);
 
         if (signum < -1 || signum > 1)
             throw(new NumberFormatException("Invalid signum value"));
 
         if (this..length==0) {
             this. = 0;
         } else {
             if (signum == 0)
                 throw(new NumberFormatException("signum-magnitude mismatch"));
             this. = signum;
         }
     }

    
A constructor for internal use that translates the sign-magnitude representation of a BigInteger into a BigInteger. It checks the arguments and copies the magnitude so this constructor would be safe for external use.
 
     private BigInteger(int signumint[] magnitude) {
         this. = stripLeadingZeroInts(magnitude);
 
         if (signum < -1 || signum > 1)
             throw(new NumberFormatException("Invalid signum value"));
 
         if (this..length==0) {
             this. = 0;
         } else {
             if (signum == 0)
                 throw(new NumberFormatException("signum-magnitude mismatch"));
             this. = signum;
         }
     }

    
Translates the String representation of a BigInteger in the specified radix into a BigInteger. The String representation consists of an optional minus followed by a sequence of one or more digits in the specified radix. The character-to-digit mapping is provided by Character.digit. The String may not contain any extraneous characters (whitespace, for example).

Parameters:
val String representation of BigInteger.
radix radix to be used in interpreting val.
Throws:
java.lang.NumberFormatException val is not a valid representation of a BigInteger in the specified radix, or radix is outside the range from java.lang.Character.MIN_RADIX to java.lang.Character.MAX_RADIX, inclusive.
See also:
java.lang.Character.digit(char,int)
 
     public BigInteger(String valint radix) {
         int cursor = 0, numDigits;
         int len = val.length();
 
         if (radix < . || radix > .)
             throw new NumberFormatException("Radix out of range");
         if (val.length() == 0)
             throw new NumberFormatException("Zero length BigInteger");
 
         // Check for at most one leading sign
          = 1;
         int index = val.lastIndexOf('-');
         if (index != -1) {
             if (index == 0 ) {
                 if (val.length() == 1)
                     throw new NumberFormatException("Zero length BigInteger");
                  = -1;
                 cursor = 1;
             } else {
                 throw new NumberFormatException("Illegal embedded sign character");
             }
         }
 
         // Skip leading zeros and compute number of digits in magnitude
         while (cursor < len &&
                Character.digit(val.charAt(cursor), radix) == 0)
             cursor++;
         if (cursor == len) {
              = 0;
              = .;
             return;
         } else {
             numDigits = len - cursor;
         }
 
         // Pre-allocate array of expected size. May be too large but can
         // never be too small. Typically exact.
         int numBits = (int)(((numDigits * [radix]) >>> 10) + 1);
         int numWords = (numBits + 31) /32;
          = new int[numWords];
 
         // Process first (potentially short) digit group
         int firstGroupLen = numDigits % [radix];
         if (firstGroupLen == 0)
             firstGroupLen = [radix];
         String group = val.substring(cursorcursor += firstGroupLen);
         [. - 1] = Integer.parseInt(groupradix);
         if ([. - 1] < 0)
             throw new NumberFormatException("Illegal digit");
 
         // Process remaining digit groups
         int superRadix = [radix];
         int groupVal = 0;
         while (cursor < val.length()) {
             group = val.substring(cursorcursor += [radix]);
             groupVal = Integer.parseInt(groupradix);
             if (groupVal < 0)
                 throw new NumberFormatException("Illegal digit");
             destructiveMulAdd(superRadixgroupVal);
         }
         // Required for cases where the array was overallocated.
          = trustedStripLeadingZeroInts();
     }
 
     // Constructs a new BigInteger using a char array with radix=10
     BigInteger(char[] val) {
         int cursor = 0, numDigits;
         int len = val.length;
 
         // Check for leading minus sign
          = 1;
         if (val[0] == '-') {
             if (len == 1)
                 throw new NumberFormatException("Zero length BigInteger");
              = -1;
             cursor = 1;
         }
 
         // Skip leading zeros and compute number of digits in magnitude
         while (cursor < len && Character.digit(val[cursor], 10) == 0)
             cursor++;
         if (cursor == len) {
              = 0;
              = .;
             return;
         } else {
             numDigits = len - cursor;
         }
 
         // Pre-allocate array of expected size
         int numWords;
         if (len < 10) {
             numWords = 1;
         } else {
             int numBits = (int)(((numDigits * [10]) >>> 10) + 1);
             numWords = (numBits + 31) /32;
         }
          = new int[numWords];
 
         // Process first (potentially short) digit group
         int firstGroupLen = numDigits % [10];
         if (firstGroupLen == 0)
             firstGroupLen = [10];
         [.-1] = parseInt(valcursor,  cursor += firstGroupLen);
 
         // Process remaining digit groups
         while (cursor < len) {
             int groupVal = parseInt(valcursorcursor += [10]);
             destructiveMulAdd([10], groupVal);
         }
          = trustedStripLeadingZeroInts();
     }
 
     // Create an integer with the digits between the two indexes
     // Assumes start < end. The result may be negative, but it
     // is to be treated as an unsigned value.
     private int parseInt(char[] sourceint startint end) {
         int result = Character.digit(source[start++], 10);
         if (result == -1)
             throw new NumberFormatException(new String(source));
 
         for (int index = startindex<endindex++) {
             int nextVal = Character.digit(source[index], 10);
             if (nextVal == -1)
                 throw new NumberFormatException(new String(source));
             result = 10*result + nextVal;
         }
 
         return result;
     }
 
     // bitsPerDigit in the given radix times 1024
     // Rounded up to avoid underallocation.
     private static long bitsPerDigit[] = { 0, 0,
         1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
         3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
         4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
                                            5253, 5295};
 
     // Multiply x array times word y in place, and add word z
     private static void destructiveMulAdd(int[] xint yint z) {
         // Perform the multiplication word by word
         long ylong = y & ;
         long zlong = z & ;
         int len = x.length;
 
         long product = 0;
         long carry = 0;
         for (int i = len-1; i >= 0; i--) {
             product = ylong * (x[i] & ) + carry;
             x[i] = (int)product;
             carry = product >>> 32;
         }
 
         // Perform the addition
         long sum = (x[len-1] & ) + zlong;
         x[len-1] = (int)sum;
         carry = sum >>> 32;
         for (int i = len-2; i >= 0; i--) {
             sum = (x[i] & ) + carry;
             x[i] = (int)sum;
             carry = sum >>> 32;
         }
     }

    
Translates the decimal String representation of a BigInteger into a BigInteger. The String representation consists of an optional minus sign followed by a sequence of one or more decimal digits. The character-to-digit mapping is provided by Character.digit. The String may not contain any extraneous characters (whitespace, for example).

Parameters:
val decimal String representation of BigInteger.
Throws:
java.lang.NumberFormatException val is not a valid representation of a BigInteger.
See also:
java.lang.Character.digit(char,int)
 
     public BigInteger(String val) {
         this(val, 10);
     }

    
Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2numBits - 1), inclusive. The uniformity of the distribution assumes that a fair source of random bits is provided in rnd. Note that this constructor always constructs a non-negative BigInteger.

Parameters:
numBits maximum bitLength of the new BigInteger.
rnd source of randomness to be used in computing the new BigInteger.
Throws:
java.lang.IllegalArgumentException numBits is negative.
See also:
bitLength()
 
     public BigInteger(int numBitsRandom rnd) {
         this(1, randomBits(numBitsrnd));
     }
 
     private static byte[] randomBits(int numBitsRandom rnd) {
         if (numBits < 0)
             throw new IllegalArgumentException("numBits must be non-negative");
         int numBytes = (int)(((long)numBits+7)/8); // avoid overflow
         byte[] randomBits = new byte[numBytes];
 
         // Generate random bytes and mask out any excess bits
         if (numBytes > 0) {
             rnd.nextBytes(randomBits);
             int excessBits = 8*numBytes - numBits;
             randomBits[0] &= (1 << (8-excessBits)) - 1;
         }
         return randomBits;
     }

    
Constructs a randomly generated positive BigInteger that is probably prime, with the specified bitLength.

It is recommended that the probablePrime method be used in preference to this constructor unless there is a compelling need to specify a certainty.

Parameters:
bitLength bitLength of the returned BigInteger.
certainty a measure of the uncertainty that the caller is willing to tolerate. The probability that the new BigInteger represents a prime number will exceed (1 - 1/2certainty). The execution time of this constructor is proportional to the value of this parameter.
rnd source of random bits used to select candidates to be tested for primality.
Throws:
java.lang.ArithmeticException bitLength < 2.
See also:
bitLength()
 
     public BigInteger(int bitLengthint certaintyRandom rnd) {
         BigInteger prime;
 
         if (bitLength < 2)
             throw new ArithmeticException("bitLength < 2");
         // The cutoff of 95 was chosen empirically for best performance
         prime = (bitLength < 95 ? smallPrime(bitLengthcertaintyrnd)
                                 : largePrime(bitLengthcertaintyrnd));
          = 1;
          = prime.mag;
     }
 
     // Minimum size in bits that the requested prime number has
     // before we use the large prime number generating algorithms
     private static final int SMALL_PRIME_THRESHOLD = 95;
 
     // Certainty required to meet the spec of probablePrime
     private static final int DEFAULT_PRIME_CERTAINTY = 100;

    
Returns a positive BigInteger that is probably prime, with the specified bitLength. The probability that a BigInteger returned by this method is composite does not exceed 2-100.

Parameters:
bitLength bitLength of the returned BigInteger.
rnd source of random bits used to select candidates to be tested for primality.
Returns:
a BigInteger of bitLength bits that is probably prime
Throws:
java.lang.ArithmeticException bitLength < 2.
Since:
1.4
See also:
bitLength()
 
     public static BigInteger probablePrime(int bitLengthRandom rnd) {
         if (bitLength < 2)
             throw new ArithmeticException("bitLength < 2");
 
         // The cutoff of 95 was chosen empirically for best performance
         return (bitLength <  ?
                 smallPrime(bitLengthrnd) :
                 largePrime(bitLengthrnd));
     }

    
Find a random number of the specified bitLength that is probably prime. This method is used for smaller primes, its performance degrades on larger bitlengths. This method assumes bitLength > 1.
 
     private static BigInteger smallPrime(int bitLengthint certaintyRandom rnd) {
         int magLen = (bitLength + 31) >>> 5;
         int temp[] = new int[magLen];
         int highBit = 1 << ((bitLength+31) & 0x1f);  // High bit of high int
         int highMask = (highBit << 1) - 1;  // Bits to keep in high int
 
         while(true) {
             // Construct a candidate
             for (int i=0; i<magLeni++)
                 temp[i] = rnd.nextInt();
             temp[0] = (temp[0] & highMask) | highBit;  // Ensure exact length
             if (bitLength > 2)
                 temp[magLen-1] |= 1;  // Make odd if bitlen > 2
 
             BigInteger p = new BigInteger(temp, 1);
 
             // Do cheap "pre-test" if applicable
             if (bitLength > 6) {
                 long r = p.remainder().longValue();
                 if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
                     (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
                     (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
                     continue// Candidate is composite; try another
             }
 
             // All candidates of bitLength 2 and 3 are prime by this point
             if (bitLength < 4)
                 return p;
 
             // Do expensive test if we survive pre-test (or it's inapplicable)
             if (p.primeToCertainty(certaintyrnd))
                 return p;
         }
     }
 
     private static final BigInteger SMALL_PRIME_PRODUCT
                        = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);

    
Find a random number of the specified bitLength that is probably prime. This method is more appropriate for larger bitlengths since it uses a sieve to eliminate most composites before using a more expensive test.
 
     private static BigInteger largePrime(int bitLengthint certaintyRandom rnd) {
         BigInteger p;
         p = new BigInteger(bitLengthrnd).setBit(bitLength-1);
         p.mag[p.mag.length-1] &= 0xfffffffe;
 
         // Use a sieve length likely to contain the next prime number
         int searchLen = (bitLength / 20) * 64;
         BitSieve searchSieve = new BitSieve(psearchLen);
         BigInteger candidate = searchSieve.retrieve(pcertaintyrnd);
 
         while ((candidate == null) || (candidate.bitLength() != bitLength)) {
             p = p.add(BigInteger.valueOf(2*searchLen));
             if (p.bitLength() != bitLength)
                 p = new BigInteger(bitLengthrnd).setBit(bitLength-1);
             p.mag[p.mag.length-1] &= 0xfffffffe;
             searchSieve = new BitSieve(psearchLen);
             candidate = searchSieve.retrieve(pcertaintyrnd);
         }
         return candidate;
     }

   
Returns the first integer greater than this BigInteger that is probably prime. The probability that the number returned by this method is composite does not exceed 2-100. This method will never skip over a prime when searching: if it returns p, there is no prime q such that this < q < p.

Returns:
the first integer greater than this BigInteger that is probably prime.
Throws:
java.lang.ArithmeticException this < 0.
Since:
1.5
 
     public BigInteger nextProbablePrime() {
         if (this. < 0)
             throw new ArithmeticException("start < 0: " + this);
 
         // Handle trivial cases
         if ((this. == 0) || this.equals())
             return ;
 
         BigInteger result = this.add();
 
         // Fastpath for small numbers
         if (result.bitLength() < ) {
 
             // Ensure an odd number
             if (!result.testBit(0))
                 result = result.add();
 
             while(true) {
                 // Do cheap "pre-test" if applicable
                 if (result.bitLength() > 6) {
                     long r = result.remainder().longValue();
                     if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
                         (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
                         (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {
                         result = result.add();
                         continue// Candidate is composite; try another
                     }
                 }
 
                 // All candidates of bitLength 2 and 3 are prime by this point
                 if (result.bitLength() < 4)
                     return result;
 
                 // The expensive test
                 if (result.primeToCertainty(null))
                     return result;
 
                 result = result.add();
             }
         }
 
         // Start at previous even number
         if (result.testBit(0))
             result = result.subtract();
 
         // Looking for the next large prime
         int searchLen = (result.bitLength() / 20) * 64;
 
         while(true) {
            BitSieve searchSieve = new BitSieve(resultsearchLen);
            BigInteger candidate = searchSieve.retrieve(result,
                                                  null);
            if (candidate != null)
                return candidate;
            result = result.add(BigInteger.valueOf(2 * searchLen));
         }
     }

    
Returns true if this BigInteger is probably prime, false if it's definitely composite. This method assumes bitLength > 2.

Parameters:
certainty a measure of the uncertainty that the caller is willing to tolerate: if the call returns true the probability that this BigInteger is prime exceeds (1 - 1/2<sup>certainty</sup>). The execution time of this method is proportional to the value of this parameter.
Returns:
true if this BigInteger is probably prime, false if it's definitely composite.
 
     boolean primeToCertainty(int certaintyRandom random) {
         int rounds = 0;
         int n = (Math.min(certainty.-1)+1)/2;
 
         // The relationship between the certainty and the number of rounds
         // we perform is given in the draft standard ANSI X9.80, "PRIME
         // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
         int sizeInBits = this.bitLength();
         if (sizeInBits < 100) {
             rounds = 50;
             rounds = n < rounds ? n : rounds;
             return passesMillerRabin(roundsrandom);
         }
 
         if (sizeInBits < 256) {
             rounds = 27;
         } else if (sizeInBits < 512) {
             rounds = 15;
         } else if (sizeInBits < 768) {
             rounds = 8;
         } else if (sizeInBits < 1024) {
             rounds = 4;
         } else {
             rounds = 2;
         }
         rounds = n < rounds ? n : rounds;
 
         return passesMillerRabin(roundsrandom) && passesLucasLehmer();
     }

    
Returns true iff this BigInteger is a Lucas-Lehmer probable prime. The following assumptions are made: This BigInteger is a positive, odd number.
 
     private boolean passesLucasLehmer() {
         BigInteger thisPlusOne = this.add();
 
         // Step 1
         int d = 5;
         while (jacobiSymbol(dthis) != -1) {
             // 5, -7, 9, -11, ...
             d = (d<0) ? Math.abs(d)+2 : -(d+2);
         }
 
         // Step 2
         BigInteger u = lucasLehmerSequence(dthisPlusOnethis);
 
         // Step 3
         return u.mod(this).equals();
     }

    
Computes Jacobi(p,n). Assumes n positive, odd, n>=3.
 
     private static int jacobiSymbol(int pBigInteger n) {
         if (p == 0)
             return 0;
 
         // Algorithm and comments adapted from Colin Plumb's C library.
         int j = 1;
         int u = n.mag[n.mag.length-1];
 
         // Make p positive
         if (p < 0) {
             p = -p;
             int n8 = u & 7;
             if ((n8 == 3) || (n8 == 7))
                 j = -j// 3 (011) or 7 (111) mod 8
         }
 
         // Get rid of factors of 2 in p
         while ((p & 3) == 0)
             p >>= 2;
         if ((p & 1) == 0) {
             p >>= 1;
             if (((u ^ (u>>1)) & 2) != 0)
                 j = -j// 3 (011) or 5 (101) mod 8
         }
         if (p == 1)
             return j;
         // Then, apply quadratic reciprocity
         if ((p & u & 2) != 0)   // p = u = 3 (mod 4)?
             j = -j;
         // And reduce u mod p
         u = n.mod(BigInteger.valueOf(p)).intValue();
 
         // Now compute Jacobi(u,p), u < p
         while (u != 0) {
             while ((u & 3) == 0)
                 u >>= 2;
             if ((u & 1) == 0) {
                 u >>= 1;
                 if (((p ^ (p>>1)) & 2) != 0)
                     j = -j;     // 3 (011) or 5 (101) mod 8
             }
             if (u == 1)
                 return j;
             // Now both u and p are odd, so use quadratic reciprocity
             assert (u < p);
             int t = uu = pp = t;
             if ((u & p & 2) != 0) // u = p = 3 (mod 4)?
                 j = -j;
             // Now u >= p, so it can be reduced
             u %= p;
         }
         return 0;
     }
 
     private static BigInteger lucasLehmerSequence(int zBigInteger kBigInteger n) {
         BigInteger d = BigInteger.valueOf(z);
         BigInteger u = BigInteger u2;
         BigInteger v = BigInteger v2;
 
         for (int i=k.bitLength()-2; i>=0; i--) {
             u2 = u.multiply(v).mod(n);
 
             v2 = v.square().add(d.multiply(u.square())).mod(n);
             if (v2.testBit(0)) {
                 v2 = n.subtract(v2);
                 v2.signum = - v2.signum;
             }
             v2 = v2.shiftRight(1);
 
             u = u2v = v2;
             if (k.testBit(i)) {
                 u2 = u.add(v).mod(n);
                 if (u2.testBit(0)) {
                     u2 = n.subtract(u2);
                     u2.signum = - u2.signum;
                 }
                 u2 = u2.shiftRight(1);
 
                 v2 = v.add(d.multiply(u)).mod(n);
                 if (v2.testBit(0)) {
                     v2 = n.subtract(v2);
                     v2.signum = - v2.signum;
                 }
                 v2 = v2.shiftRight(1);
 
                 u = u2v = v2;
             }
         }
         return u;
     }
 
     private static volatile Random staticRandom;
 
     private static Random getSecureRandom() {
         if ( == null) {
              = new java.security.SecureRandom();
         }
         return ;
     }

    
Returns true iff this BigInteger passes the specified number of Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS 186-2). The following assumptions are made: This BigInteger is a positive, odd number greater than 2. iterations<=50.
 
     private boolean passesMillerRabin(int iterationsRandom rnd) {
         // Find a and m such that m is odd and this == 1 + 2**a * m
         BigInteger thisMinusOne = this.subtract();
         BigInteger m = thisMinusOne;
         int a = m.getLowestSetBit();
         m = m.shiftRight(a);
 
         // Do the tests
         if (rnd == null) {
             rnd = getSecureRandom();
         }
         for (int i=0; i<iterationsi++) {
             // Generate a uniform random on (1, this)
             BigInteger b;
             do {
                 b = new BigInteger(this.bitLength(), rnd);
             } while (b.compareTo() <= 0 || b.compareTo(this) >= 0);
 
             int j = 0;
             BigInteger z = b.modPow(mthis);
             while(!((j==0 && z.equals()) || z.equals(thisMinusOne))) {
                 if (j>0 && z.equals() || ++j==a)
                     return false;
                 z = z.modPow(this);
             }
         }
         return true;
     }

    
This private constructor differs from its public cousin with the arguments reversed in two ways: it assumes that its arguments are correct, and it doesn't copy the magnitude array.
 
     private BigInteger(int[] magnitudeint signum) {
         this. = (magnitude.length==0 ? 0 : signum);
         this. = magnitude;
     }

    
This private constructor is for internal use and assumes that its arguments are correct.
 
     private BigInteger(byte[] magnitudeint signum) {
         this. = (magnitude.length==0 ? 0 : signum);
         this. = stripLeadingZeroBytes(magnitude);
     }

    
This private constructor is for internal use in converting from a MutableBigInteger object into a BigInteger.
 
     BigInteger(MutableBigInteger valint sign) {
         if (val.offset > 0 || val.value.length != val.intLen) {
              = new int[val.intLen];
             for(int i=0; i<val.intLeni++)
                 [i] = val.value[val.offset+i];
         } else {
              = val.value;
         }
 
         this. = (val.intLen == 0) ? 0 : sign;
     }
 
     //Static Factory Methods
 
    
Returns a BigInteger whose value is equal to that of the specified long. This "static factory method" is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers.

Parameters:
val value of the BigInteger to return.
Returns:
a BigInteger with the specified value.
 
     public static BigInteger valueOf(long val) {
         // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
         if (val == 0)
             return ;
         if (val > 0 && val <= )
             return [(intval];
         else if (val < 0 && val >= -)
             return [(int) -val];
 
         return new BigInteger(val);
     }

    
Constructs a BigInteger with the specified value, which may not be zero.
 
     private BigInteger(long val) {
         if (val < 0) {
              = -1;
             val = -val;
         } else {
              = 1;
         }
 
         int highWord = (int)(val >>> 32);
         if (highWord==0) {
              = new int[1];
             [0] = (int)val;
         } else {
              = new int[2];
             [0] = highWord;
             [1] = (int)val;
         }
     }

    
Returns a BigInteger with the given two's complement representation. Assumes that the input array will not be modified (the returned BigInteger will reference the input array if feasible).
 
     private static BigInteger valueOf(int val[]) {
        return (val[0]>0 ? new BigInteger(val, 1) : new BigInteger(val));
    }
    // Constants

    
Initialize static constant array when class is loaded.
    private final static int MAX_CONSTANT = 16;
    private static BigInteger posConst[] = new BigInteger[+1];
    private static BigInteger negConst[] = new BigInteger[+1];
    static {
        for (int i = 1; i <= i++) {
            int[] magnitude = new int[1];
            magnitude[0] = i;
            [i] = new BigInteger(magnitude,  1);
            [i] = new BigInteger(magnitude, -1);
        }
    }

    
The BigInteger constant zero.

Since:
1.2
    public static final BigInteger ZERO = new BigInteger(new int[0], 0);

    
The BigInteger constant one.

Since:
1.2
    public static final BigInteger ONE = valueOf(1);

    
The BigInteger constant two. (Not exported.)
    private static final BigInteger TWO = valueOf(2);

    
The BigInteger constant ten.

Since:
1.5
    public static final BigInteger TEN = valueOf(10);
    // Arithmetic Operations

    
Returns a BigInteger whose value is (this + val).

Parameters:
val value to be added to this BigInteger.
Returns:
this + val
    public BigInteger add(BigInteger val) {
        int[] resultMag;
        if (val.signum == 0)
            return this;
        if ( == 0)
            return val;
        if (val.signum == )
            return new BigInteger(add(val.mag), );
        int cmp = intArrayCmp(val.mag);
        if (cmp==0)
            return ;
        resultMag = (cmp>0 ? subtract(val.mag)
                           : subtract(val.mag));
        resultMag = trustedStripLeadingZeroInts(resultMag);
        return new BigInteger(resultMagcmp*);
    }

    
Adds the contents of the int arrays x and y. This method allocates a new int array to hold the answer and returns a reference to that array.
    private static int[] add(int[] xint[] y) {
        // If x is shorter, swap the two arrays
        if (x.length < y.length) {
            int[] tmp = x;
            x = y;
            y = tmp;
        }
        int xIndex = x.length;
        int yIndex = y.length;
        int result[] = new int[xIndex];
        long sum = 0;
        // Add common parts of both numbers
        while(yIndex > 0) {
            sum = (x[--xIndex] & ) +
                  (y[--yIndex] & ) + (sum >>> 32);
            result[xIndex] = (int)sum;
        }
        // Copy remainder of longer number while carry propagation is required
        boolean carry = (sum >>> 32 != 0);
        while (xIndex > 0 && carry)
            carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
        // Copy remainder of longer number
        while (xIndex > 0)
            result[--xIndex] = x[xIndex];
        // Grow result if necessary
        if (carry) {
            int newLen = result.length + 1;
            int temp[] = new int[newLen];
            for (int i = 1; i<newLeni++)
                temp[i] = result[i-1];
            temp[0] = 0x01;
            result = temp;
        }
        return result;
    }

    
Returns a BigInteger whose value is (this - val).

Parameters:
val value to be subtracted from this BigInteger.
Returns:
this - val
    public BigInteger subtract(BigInteger val) {
        int[] resultMag;
        if (val.signum == 0)
            return this;
        if ( == 0)
            return val.negate();
        if (val.signum != )
            return new BigInteger(add(val.mag), );
        int cmp = intArrayCmp(val.mag);
        if (cmp==0)
            return ;
        resultMag = (cmp>0 ? subtract(val.mag)
                           : subtract(val.mag));
        resultMag = trustedStripLeadingZeroInts(resultMag);
        return new BigInteger(resultMagcmp*);
    }

    
Subtracts the contents of the second int arrays (little) from the first (big). The first int array (big) must represent a larger number than the second. This method allocates the space necessary to hold the answer.
    private static int[] subtract(int[] bigint[] little) {
        int bigIndex = big.length;
        int result[] = new int[bigIndex];
        int littleIndex = little.length;
        long difference = 0;
        // Subtract common parts of both numbers
        while(littleIndex > 0) {
            difference = (big[--bigIndex] & ) -
                         (little[--littleIndex] & ) +
                         (difference >> 32);
            result[bigIndex] = (int)difference;
        }
        // Subtract remainder of longer number while borrow propagates
        boolean borrow = (difference >> 32 != 0);
        while (bigIndex > 0 && borrow)
            borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
        // Copy remainder of longer number
        while (bigIndex > 0)
            result[--bigIndex] = big[bigIndex];
        return result;
    }

    
Returns a BigInteger whose value is (this * val).

Parameters:
val value to be multiplied by this BigInteger.
Returns:
this * val
    public BigInteger multiply(BigInteger val) {
        if (val.signum == 0 ||  == 0)
            return ;
        int[] result = multiplyToLen(.,
                                     val.magval.mag.lengthnull);
        result = trustedStripLeadingZeroInts(result);
        return new BigInteger(result*val.signum);
    }

    
Multiplies int arrays x and y to the specified lengths and places the result into z.
    private int[] multiplyToLen(int[] xint xlenint[] yint ylenint[] z) {
        int xstart = xlen - 1;
        int ystart = ylen - 1;
        if (z == null || z.length < (xlenylen))
            z = new int[xlen+ylen];
        long carry = 0;
        for (int j=ystartk=ystart+1+xstartj>=0; j--, k--) {
            long product = (y[j] & ) *
                           (x[xstart] & ) + carry;
            z[k] = (int)product;
            carry = product >>> 32;
        }
        z[xstart] = (int)carry;
        for (int i = xstart-1; i >= 0; i--) {
            carry = 0;
            for (int j=ystartk=ystart+1+ij>=0; j--, k--) {
                long product = (y[j] & ) *
                               (x[i] & ) +
                               (z[k] & ) + carry;
                z[k] = (int)product;
                carry = product >>> 32;
            }
            z[i] = (int)carry;
        }
        return z;
    }

    
Returns a BigInteger whose value is (this<sup>2</sup>).

Returns:
this<sup>2</sup>
    private BigInteger square() {
        if ( == 0)
            return ;
        int[] z = squareToLen(.null);
        return new BigInteger(trustedStripLeadingZeroInts(z), 1);
    }

    
Squares the contents of the int array x. The result is placed into the int array z. The contents of x are not changed.
    private static final int[] squareToLen(int[] xint lenint[] z) {
        /*
         * The algorithm used here is adapted from Colin Plumb's C library.
         * Technique: Consider the partial products in the multiplication
         * of "abcde" by itself:
         *
         *               a  b  c  d  e
         *            *  a  b  c  d  e
         *          ==================
         *              ae be ce de ee
         *           ad bd cd dd de
         *        ac bc cc cd ce
         *     ab bb bc bd be
         *  aa ab ac ad ae
         *
         * Note that everything above the main diagonal:
         *              ae be ce de = (abcd) * e
         *           ad bd cd       = (abc) * d
         *        ac bc             = (ab) * c
         *     ab                   = (a) * b
         *
         * is a copy of everything below the main diagonal:
         *                       de
         *                 cd ce
         *           bc bd be
         *     ab ac ad ae
         *
         * Thus, the sum is 2 * (off the diagonal) + diagonal.
         *
         * This is accumulated beginning with the diagonal (which
         * consist of the squares of the digits of the input), which is then
         * divided by two, the off-diagonal added, and multiplied by two
         * again.  The low bit is simply a copy of the low bit of the
         * input, so it doesn't need special care.
         */
        int zlen = len << 1;
        if (z == null || z.length < zlen)
            z = new int[zlen];
        // Store the squares, right shifted one bit (i.e., divided by 2)
        int lastProductLowWord = 0;
        for (int j=0, i=0; j<lenj++) {
            long piece = (x[j] & );
            long product = piece * piece;
            z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);
            z[i++] = (int)(product >>> 1);
            lastProductLowWord = (int)product;
        }
        // Add in off-diagonal sums
        for (int i=lenoffset=1; i>0; i--, offset+=2) {
            int t = x[i-1];
            t = mulAdd(zxoffseti-1, t);
            addOne(zoffset-1, it);
        }
        // Shift back up and set low bit
        primitiveLeftShift(zzlen, 1);
        z[zlen-1] |= x[len-1] & 1;
        return z;
    }

    
Returns a BigInteger whose value is (this / val).

Parameters:
val value by which this BigInteger is to be divided.
Returns:
this / val
Throws:
java.lang.ArithmeticException val==0
    public BigInteger divide(BigInteger val) {
        MutableBigInteger q = new MutableBigInteger(),
                          r = new MutableBigInteger(),
                          a = new MutableBigInteger(this.),
                          b = new MutableBigInteger(val.mag);
        a.divide(bqr);
        return new BigInteger(qthis. * val.signum);
    }

    
Returns an array of two BigIntegers containing (this / val) followed by (this % val).

Parameters:
val value by which this BigInteger is to be divided, and the remainder computed.
Returns:
an array of two BigIntegers: the quotient (this / val) is the initial element, and the remainder (this % val) is the final element.
Throws:
java.lang.ArithmeticException val==0
    public BigInteger[] divideAndRemainder(BigInteger val) {
        BigInteger[] result = new BigInteger[2];
        MutableBigInteger q = new MutableBigInteger(),
                          r = new MutableBigInteger(),
                          a = new MutableBigInteger(this.),
                          b = new MutableBigInteger(val.mag);
        a.divide(bqr);
        result[0] = new BigInteger(qthis. * val.signum);
        result[1] = new BigInteger(rthis.);
        return result;
    }

    
Returns a BigInteger whose value is (this % val).

Parameters:
val value by which this BigInteger is to be divided, and the remainder computed.
Returns:
this % val
Throws:
java.lang.ArithmeticException val==0
    public BigInteger remainder(BigInteger val) {
        MutableBigInteger q = new MutableBigInteger(),
                          r = new MutableBigInteger(),
                          a = new MutableBigInteger(this.),
                          b = new MutableBigInteger(val.mag);
        a.divide(bqr);
        return new BigInteger(rthis.);
    }

    
Returns a BigInteger whose value is (thisexponent). Note that exponent is an integer rather than a BigInteger.

Parameters:
exponent exponent to which this BigInteger is to be raised.
Returns:
thisexponent
Throws:
java.lang.ArithmeticException exponent is negative. (This would cause the operation to yield a non-integer value.)
    public BigInteger pow(int exponent) {
        if (exponent < 0)
            throw new ArithmeticException("Negative exponent");
        if (==0)
            return (exponent==0 ?  : this);
        // Perform exponentiation using repeated squaring trick
        int newSign = (<0 && (exponent&1)==1 ? -1 : 1);
        int[] baseToPow2 = this.;
        int[] result = {1};
        while (exponent != 0) {
            if ((exponent & 1)==1) {
                result = multiplyToLen(resultresult.length,
                                       baseToPow2baseToPow2.lengthnull);
                result = trustedStripLeadingZeroInts(result);
            }
            if ((exponent >>>= 1) != 0) {
                baseToPow2 = squareToLen(baseToPow2baseToPow2.lengthnull);
                baseToPow2 = trustedStripLeadingZeroInts(baseToPow2);
            }
        }
        return new BigInteger(resultnewSign);
    }

    
Returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val). Returns 0 if this==0 && val==0.

Parameters:
val value with which the GCD is to be computed.
Returns:
GCD(abs(this), abs(val))
    public BigInteger gcd(BigInteger val) {
        if (val.signum == 0)
            return this.abs();
        else if (this. == 0)
            return val.abs();
        MutableBigInteger a = new MutableBigInteger(this);
        MutableBigInteger b = new MutableBigInteger(val);
        MutableBigInteger result = a.hybridGCD(b);
        return new BigInteger(result, 1);
    }

    
Left shift int array a up to len by n bits. Returns the array that results from the shift since space may have to be reallocated.
    private static int[] leftShift(int[] aint lenint n) {
        int nInts = n >>> 5;
        int nBits = n&0x1F;
        int bitsInHighWord = bitLen(a[0]);
        // If shift can be done without recopy, do so
        if (n <= (32-bitsInHighWord)) {
            primitiveLeftShift(alennBits);
            return a;
        } else { // Array must be resized
            if (nBits <= (32-bitsInHighWord)) {
                int result[] = new int[nInts+len];
                for (int i=0; i<leni++)
                    result[i] = a[i];
                primitiveLeftShift(resultresult.lengthnBits);
                return result;
            } else {
                int result[] = new int[nInts+len+1];
                for (int i=0; i<leni++)
                    result[i] = a[i];
                primitiveRightShift(resultresult.length, 32 - nBits);
                return result;
            }
        }
    }
    // shifts a up to len right n bits assumes no leading zeros, 0<n<32
    static void primitiveRightShift(int[] aint lenint n) {
        int n2 = 32 - n;
        for (int i=len-1, c=a[i]; i>0; i--) {
            int b = c;
            c = a[i-1];
            a[i] = (c << n2) | (b >>> n);
        }
        a[0] >>>= n;
    }
    // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
    static void primitiveLeftShift(int[] aint lenint n) {
        if (len == 0 || n == 0)
            return;
        int n2 = 32 - n;
        for (int i=0, c=a[i], m=i+len-1; i<mi++) {
            int b = c;
            c = a[i+1];
            a[i] = (b << n) | (c >>> n2);
        }
        a[len-1] <<= n;
    }

    
Calculate bitlength of contents of the first len elements an int array, assuming there are no leading zero ints.
    private static int bitLength(int[] valint len) {
        if (len==0)
            return 0;
        return ((len-1)<<5) + bitLen(val[0]);
    }

    
Returns a BigInteger whose value is the absolute value of this BigInteger.

Returns:
abs(this)
    public BigInteger abs() {
        return ( >= 0 ? this : this.negate());
    }

    
Returns a BigInteger whose value is (-this).

Returns:
-this
    public BigInteger negate() {
        return new BigInteger(this., -this.);
    }

    
Returns the signum function of this BigInteger.

Returns:
-1, 0 or 1 as the value of this BigInteger is negative, zero or positive.
    public int signum() {
        return this.;
    }
    // Modular Arithmetic Operations

    
Returns a BigInteger whose value is (this mod m). This method differs from remainder in that it always returns a non-negative BigInteger.

Parameters:
m the modulus.
Returns:
this mod m
Throws:
java.lang.ArithmeticException m <= 0
See also:
remainder(java.math.BigInteger)
    public BigInteger mod(BigInteger m) {
        if (m.signum <= 0)
            throw new ArithmeticException("BigInteger: modulus not positive");
        BigInteger result = this.remainder(m);
        return (result.signum >= 0 ? result : result.add(m));
    }

    
Returns a BigInteger whose value is (thisexponent mod m). (Unlike pow, this method permits negative exponents.)

Parameters:
exponent the exponent.
m the modulus.
Returns:
thisexponent mod m
Throws:
java.lang.ArithmeticException m <= 0
See also:
modInverse(java.math.BigInteger)
    public BigInteger modPow(BigInteger exponentBigInteger m) {
        if (m.signum <= 0)
            throw new ArithmeticException("BigInteger: modulus not positive");
        // Trivial cases
        if (exponent.signum == 0)
            return (m.equals() ?  : );
        if (this.equals())
            return (m.equals() ?  : );
        if (this.equals() && exponent.signum >= 0)
            return ;
        if (this.equals([1]) && (!exponent.testBit(0)))
            return (m.equals() ?  : );
        boolean invertResult;
        if ((invertResult = (exponent.signum < 0)))
            exponent = exponent.negate();
        BigInteger base = (this. < 0 || this.compareTo(m) >= 0
                           ? this.mod(m) : this);
        BigInteger result;
        if (m.testBit(0)) { // odd modulus
            result = base.oddModPow(exponentm);
        } else {
            /*
             * Even modulus.  Tear it into an "odd part" (m1) and power of two
             * (m2), exponentiate mod m1, manually exponentiate mod m2, and
             * use Chinese Remainder Theorem to combine results.
             */
            // Tear m apart into odd part (m1) and power of 2 (m2)
            int p = m.getLowestSetBit();   // Max pow of 2 that divides m
            BigInteger m1 = m.shiftRight(p);  // m/2**p
            BigInteger m2 = .shiftLeft(p); // 2**p
            // Calculate new base from m1
            BigInteger base2 = (this. < 0 || this.compareTo(m1) >= 0
                                ? this.mod(m1) : this);
            // Caculate (base ** exponent) mod m1.
            BigInteger a1 = (m1.equals() ?  :
                             base2.oddModPow(exponentm1));
            // Calculate (this ** exponent) mod m2
            BigInteger a2 = base.modPow2(exponentp);
            // Combine results using Chinese Remainder Theorem
            BigInteger y1 = m2.modInverse(m1);
            BigInteger y2 = m1.modInverse(m2);
            result = a1.multiply(m2).multiply(y1).add
                     (a2.multiply(m1).multiply(y2)).mod(m);
        }
        return (invertResult ? result.modInverse(m) : result);
    }
    static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,
                                                .}; // Sentinel

    
Returns a BigInteger whose value is x to the power of y mod z. Assumes: z is odd && x < z.
    private BigInteger oddModPow(BigInteger yBigInteger z) {
    /*
     * The algorithm is adapted from Colin Plumb's C library.
     *
     * The window algorithm:
     * The idea is to keep a running product of b1 = n^(high-order bits of exp)
     * and then keep appending exponent bits to it.  The following patterns
     * apply to a 3-bit window (k = 3):
     * To append   0: square
     * To append   1: square, multiply by n^1
     * To append  10: square, multiply by n^1, square
     * To append  11: square, square, multiply by n^3
     * To append 100: square, multiply by n^1, square, square
     * To append 101: square, square, square, multiply by n^5
     * To append 110: square, square, multiply by n^3, square
     * To append 111: square, square, square, multiply by n^7
     *
     * Since each pattern involves only one multiply, the longer the pattern
     * the better, except that a 0 (no multiplies) can be appended directly.
     * We precompute a table of odd powers of n, up to 2^k, and can then
     * multiply k bits of exponent at a time.  Actually, assuming random
     * exponents, there is on average one zero bit between needs to
     * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
     * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so
     * you have to do one multiply per k+1 bits of exponent.
     *
     * The loop walks down the exponent, squaring the result buffer as
     * it goes.  There is a wbits+1 bit lookahead buffer, buf, that is
     * filled with the upcoming exponent bits.  (What is read after the
     * end of the exponent is unimportant, but it is filled with zero here.)
     * When the most-significant bit of this buffer becomes set, i.e.
     * (buf & tblmask) != 0, we have to decide what pattern to multiply
     * by, and when to do it.  We decide, remember to do it in future
     * after a suitable number of squarings have passed (e.g. a pattern
     * of "100" in the buffer requires that we multiply by n^1 immediately;
     * a pattern of "110" calls for multiplying by n^3 after one more
     * squaring), clear the buffer, and continue.
     *
     * When we start, there is one more optimization: the result buffer
     * is implcitly one, so squaring it or multiplying by it can be
     * optimized away.  Further, if we start with a pattern like "100"
     * in the lookahead window, rather than placing n into the buffer
     * and then starting to square it, we have already computed n^2
     * to compute the odd-powers table, so we can place that into
     * the buffer and save a squaring.
     *
     * This means that if you have a k-bit window, to compute n^z,
     * where z is the high k bits of the exponent, 1/2 of the time
     * it requires no squarings.  1/4 of the time, it requires 1
     * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.
     * And the remaining 1/2^(k-1) of the time, the top k bits are a
     * 1 followed by k-1 0 bits, so it again only requires k-2
     * squarings, not k-1.  The average of these is 1.  Add that
     * to the one squaring we have to do to compute the table,
     * and you'll see that a k-bit window saves k-2 squarings
     * as well as reducing the multiplies.  (It actually doesn't
     * hurt in the case k = 1, either.)
     */
        // Special case for exponent of one
        if (y.equals())
            return this;
        // Special case for base of zero
        if (==0)
            return ;
        int[] base = .clone();
        int[] exp = y.mag;
        int[] mod = z.mag;
        int modLen = mod.length;
        // Select an appropriate window size
        int wbits = 0;
        int ebits = bitLength(expexp.length);
        // if exponent is 65537 (0x10001), use minimum window size
        if ((ebits != 17) || (exp[0] != 65537)) {
            while (ebits > [wbits]) {
                wbits++;
            }
        }
        // Calculate appropriate table size
        int tblmask = 1 << wbits;
        // Allocate table for precomputed odd powers of base in Montgomery form
        int[][] table = new int[tblmask][];
        for (int i=0; i<tblmaski++)
            table[i] = new int[modLen];
        // Compute the modular inverse
        int inv = -MutableBigInteger.inverseMod32(mod[modLen-1]);
        // Convert base to Montgomery form
        int[] a = leftShift(basebase.lengthmodLen << 5);
        MutableBigInteger q = new MutableBigInteger(),
                          r = new MutableBigInteger(),
                          a2 = new MutableBigInteger(a),
                          b2 = new MutableBigInteger(mod);
        a2.divide(b2qr);
        table[0] = r.toIntArray();
        // Pad table[0] with leading zeros so its length is at least modLen
        if (table[0].length < modLen) {
           int offset = modLen - table[0].length;
           int[] t2 = new int[modLen];
           for (int i=0; i<table[0].lengthi++)
               t2[i+offset] = table[0][i];
           table[0] = t2;
        }
        // Set b to the square of the base
        int[] b = squareToLen(table[0], modLennull);
        b = montReduce(bmodmodLeninv);
        // Set t to high half of b
        int[] t = new int[modLen];
        for(int i=0; i<modLeni++)
            t[i] = b[i];
        // Fill in the table with odd powers of the base
        for (int i=1; i<tblmaski++) {
            int[] prod = multiplyToLen(tmodLentable[i-1], modLennull);
            table[i] = montReduce(prodmodmodLeninv);
        }
        // Pre load the window that slides over the exponent
        int bitpos = 1 << ((ebits-1) & (32-1));
        int buf = 0;
        int elen = exp.length;
        int eIndex = 0;
        for (int i = 0; i <= wbitsi++) {
            buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);
            bitpos >>>= 1;
            if (bitpos == 0) {
                eIndex++;
                bitpos = 1 << (32-1);
                elen--;
            }
        }
        int multpos = ebits;
        // The first iteration, which is hoisted out of the main loop
        ebits--;
        boolean isone = true;
        multpos = ebits - wbits;
        while ((buf & 1) == 0) {
            buf >>>= 1;
            multpos++;
        }
        int[] mult = table[buf >>> 1];
        buf = 0;
        if (multpos == ebits)
            isone = false;
        // The main loop
        while(true) {
            ebits--;
            // Advance the window
            buf <<= 1;
            if (elen != 0) {
                buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
                bitpos >>>= 1;
                if (bitpos == 0) {
                    eIndex++;
                    bitpos = 1 << (32-1);
                    elen--;
                }
            }
            // Examine the window for pending multiplies
            if ((buf & tblmask) != 0) {
                multpos = ebits - wbits;
                while ((buf & 1) == 0) {
                    buf >>>= 1;
                    multpos++;
                }
                mult = table[buf >>> 1];
                buf = 0;
            }
            // Perform multiply
            if (ebits == multpos) {
                if (isone) {
                    b = mult.clone();
                    isone = false;
                } else {
                    t = b;
                    a = multiplyToLen(tmodLenmultmodLena);
                    a = montReduce(amodmodLeninv);
                    t = aa = bb = t;
                }
            }
            // Check if done
            if (ebits == 0)
                break;
            // Square the input
            if (!isone) {
                t = b;
                a = squareToLen(tmodLena);
                a = montReduce(amodmodLeninv);
                t = aa = bb = t;
            }
        }
        // Convert result out of Montgomery form and return
        int[] t2 = new int[2*modLen];
        for(int i=0; i<modLeni++)
            t2[i+modLen] = b[i];
        b = montReduce(t2modmodLeninv);
        t2 = new int[modLen];
        for(int i=0; i<modLeni++)
            t2[i] = b[i];
        return new BigInteger(1, t2);
    }

    
Montgomery reduce n, modulo mod. This reduces modulo mod and divides by 2^(32*mlen). Adapted from Colin Plumb's C library.
    private static int[] montReduce(int[] nint[] modint mlenint inv) {
        int c=0;
        int len = mlen;
        int offset=0;
        do {
            int nEnd = n[n.length-1-offset];
            int carry = mulAdd(nmodoffsetmleninv * nEnd);
            c += addOne(noffsetmlencarry);
            offset++;
        } while(--len > 0);
        while(c>0)
            c += subN(nmodmlen);
        while (intArrayCmpToLen(nmodmlen) >= 0)
            subN(nmodmlen);
        return n;
    }
    /*
     * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,
     * equal to, or greater than arg2 up to length len.
     */
    private static int intArrayCmpToLen(int[] arg1int[] arg2int len) {
        for (int i=0; i<leni++) {
            long b1 = arg1[i] & ;
            long b2 = arg2[i] & ;
            if (b1 < b2)
                return -1;
            if (b1 > b2)
                return 1;
        }
        return 0;
    }

    
Subtracts two numbers of same length, returning borrow.
    private static int subN(int[] aint[] bint len) {
        long sum = 0;
        while(--len >= 0) {
            sum = (a[len] & ) -
                 (b[len] & ) + (sum >> 32);
            a[len] = (int)sum;
        }
        return (int)(sum >> 32);
    }

    
Multiply an array by one word k and add to result, return the carry
    static int mulAdd(int[] outint[] inint offsetint lenint k) {
        long kLong = k & ;
        long carry = 0;
        offset = out.length-offset - 1;
        for (int j=len-1; j >= 0; j--) {
            long product = (in[j] & ) * kLong +
                           (out[offset] & ) + carry;
            out[offset--] = (int)product;
            carry = product >>> 32;
        }
        return (int)carry;
    }

    
Add one word to the number a mlen words into a. Return the resulting carry.
    static int addOne(int[] aint offsetint mlenint carry) {
        offset = a.length-1-mlen-offset;
        long t = (a[offset] & ) + (carry & );
        a[offset] = (int)t;
        if ((t >>> 32) == 0)
            return 0;
        while (--mlen >= 0) {
            if (--offset < 0) { // Carry out of number
                return 1;
            } else {
                a[offset]++;
                if (a[offset] != 0)
                    return 0;
            }
        }
        return 1;
    }

    
Returns a BigInteger whose value is (this ** exponent) mod (2**p)
    private BigInteger modPow2(BigInteger exponentint p) {
        /*
         * Perform exponentiation using repeated squaring trick, chopping off
         * high order bits as indicated by modulus.
         */
        BigInteger result = valueOf(1);
        BigInteger baseToPow2 = this.mod2(p);
        int expOffset = 0;
        int limit = exponent.bitLength();
        if (this.testBit(0))
           limit = (p-1) < limit ? (p-1) : limit;
        while (expOffset < limit) {
            if (exponent.testBit(expOffset))
                result = result.multiply(baseToPow2).mod2(p);
            expOffset++;
            if (expOffset < limit)
                baseToPow2 = baseToPow2.square().mod2(p);
        }
        return result;
    }

    
Returns a BigInteger whose value is this mod(2**p). Assumes that this BigInteger >= 0 and p > 0.
    private BigInteger mod2(int p) {
        if (bitLength() <= p)
            return this;
        // Copy remaining ints of mag
        int numInts = (p+31)/32;
        int[] mag = new int[numInts];
        for (int i=0; i<numIntsi++)
            mag[i] = this.[i + (this..length - numInts)];
        // Mask out any excess bits
        int excessBits = (numInts << 5) - p;
        mag[0] &= (1L << (32-excessBits)) - 1;
        return (mag[0]==0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
    }

    
Returns a BigInteger whose value is (this-1 mod m).

Parameters:
m the modulus.
Returns:
this-1 mod m.
Throws:
java.lang.ArithmeticException m <= 0, or this BigInteger has no multiplicative inverse mod m (that is, this BigInteger is not relatively prime to m).
    public BigInteger modInverse(BigInteger m) {
        if (m.signum != 1)
            throw new ArithmeticException("BigInteger: modulus not positive");
        if (m.equals())
            return ;
        // Calculate (this mod m)
        BigInteger modVal = this;
        if ( < 0 || (intArrayCmp(m.mag) >= 0))
            modVal = this.mod(m);
        if (modVal.equals())
            return ;
        MutableBigInteger a = new MutableBigInteger(modVal);
        MutableBigInteger b = new MutableBigInteger(m);
        MutableBigInteger result = a.mutableModInverse(b);
        return new BigInteger(result, 1);
    }
    // Shift Operations

    
Returns a BigInteger whose value is (this << n). The shift distance, n, may be negative, in which case this method performs a right shift. (Computes floor(this * 2n).)

Parameters:
n shift distance, in bits.
Returns:
this << n
See also:
shiftRight(int)
    public BigInteger shiftLeft(int n) {
        if ( == 0)
            return ;
        if (n==0)
            return this;
        if (n<0)
            return shiftRight(-n);
        int nInts = n >>> 5;
        int nBits = n & 0x1f;
        int magLen = .;
        int newMag[] = null;
        if (nBits == 0) {
            newMag = new int[magLen + nInts];
            for (int i=0; i<magLeni++)
                newMag[i] = [i];
        } else {
            int i = 0;
            int nBits2 = 32 - nBits;
            int highBits = [0] >>> nBits2;
            if (highBits != 0) {
                newMag = new int[magLen + nInts + 1];
                newMag[i++] = highBits;
            } else {
                newMag = new int[magLen + nInts];
            }
            int j=0;
            while (j < magLen-1)
                newMag[i++] = [j++] << nBits | [j] >>> nBits2;
            newMag[i] = [j] << nBits;
        }
        return new BigInteger(newMag);
    }

    
Returns a BigInteger whose value is (this >> n). Sign extension is performed. The shift distance, n, may be negative, in which case this method performs a left shift. (Computes floor(this / 2n).)

Parameters:
n shift distance, in bits.
Returns:
this >> n
See also:
shiftLeft(int)
    public BigInteger shiftRight(int n) {
        if (n==0)
            return this;
        if (n<0)
            return shiftLeft(-n);
        int nInts = n >>> 5;
        int nBits = n & 0x1f;
        int magLen = .;
        int newMag[] = null;
        // Special case: entire contents shifted off the end
        if (nInts >= magLen)
            return ( >= 0 ?  : [1]);
        if (nBits == 0) {
            int newMagLen = magLen - nInts;
            newMag = new int[newMagLen];
            for (int i=0; i<newMagLeni++)
                newMag[i] = [i];
        } else {
            int i = 0;
            int highBits = [0] >>> nBits;
            if (highBits != 0) {
                newMag = new int[magLen - nInts];
                newMag[i++] = highBits;
            } else {
                newMag = new int[magLen - nInts -1];
            }
            int nBits2 = 32 - nBits;
            int j=0;
            while (j < magLen - nInts - 1)
                newMag[i++] = ([j++] << nBits2) | ([j] >>> nBits);
        }
        if ( < 0) {
            // Find out whether any one-bits were shifted off the end.
            boolean onesLost = false;
            for (int i=magLen-1, j=magLen-nIntsi>=j && !onesLosti--)
                onesLost = ([i] != 0);
            if (!onesLost && nBits != 0)
                onesLost = ([magLen - nInts - 1] << (32 - nBits) != 0);
            if (onesLost)
                newMag = javaIncrement(newMag);
        }
        return new BigInteger(newMag);
    }
    int[] javaIncrement(int[] val) {
        int lastSum = 0;
        for (int i=val.length-1;  i >= 0 && lastSum == 0; i--)
            lastSum = (val[i] += 1);
        if (lastSum == 0) {
            val = new int[val.length+1];
            val[0] = 1;
        }
        return val;
    }
    // Bitwise Operations

    
Returns a BigInteger whose value is (this & val). (This method returns a negative BigInteger if and only if this and val are both negative.)

Parameters:
val value to be AND'ed with this BigInteger.
Returns:
this & val
    public BigInteger and(BigInteger val) {
        int[] result = new int[Math.max(intLength(), val.intLength())];
        for (int i=0; i<result.lengthi++)
            result[i] = (getInt(result.length-i-1)
                         & val.getInt(result.length-i-1));
        return valueOf(result);
    }

    
Returns a BigInteger whose value is (this | val). (This method returns a negative BigInteger if and only if either this or val is negative.)

Parameters:
val value to be OR'ed with this BigInteger.
Returns:
this | val
    public BigInteger or(BigInteger val) {
        int[] result = new int[Math.max(intLength(), val.intLength())];
        for (int i=0; i<result.lengthi++)
            result[i] = (getInt(result.length-i-1)
                         | val.getInt(result.length-i-1));
        return valueOf(result);
    }

    
Returns a BigInteger whose value is (this ^ val). (This method returns a negative BigInteger if and only if exactly one of this and val are negative.)

Parameters:
val value to be XOR'ed with this BigInteger.
Returns:
this ^ val
    public BigInteger xor(BigInteger val) {
        int[] result = new int[Math.max(intLength(), val.intLength())];
        for (int i=0; i<result.lengthi++)
            result[i] = (getInt(result.length-i-1)
                         ^ val.getInt(result.length-i-1));
        return valueOf(result);
    }

    
Returns a BigInteger whose value is (~this). (This method returns a negative value if and only if this BigInteger is non-negative.)

Returns:
~this
    public BigInteger not() {
        int[] result = new int[intLength()];
        for (int i=0; i<result.lengthi++)
            result[i] = ~getInt(result.length-i-1);
        return valueOf(result);
    }

    
Returns a BigInteger whose value is (this & ~val). This method, which is equivalent to and(val.not()), is provided as a convenience for masking operations. (This method returns a negative BigInteger if and only if this is negative and val is positive.)

Parameters:
val value to be complemented and AND'ed with this BigInteger.
Returns:
this & ~val
    public BigInteger andNot(BigInteger val) {
        int[] result = new int[Math.max(intLength(), val.intLength())];
        for (int i=0; i<result.lengthi++)
            result[i] = (getInt(result.length-i-1)
                         & ~val.getInt(result.length-i-1));
        return valueOf(result);
    }
    // Single Bit Operations

    
Returns true if and only if the designated bit is set. (Computes ((this & (1<<n)) != 0).)

Parameters:
n index of bit to test.
Returns:
true if and only if the designated bit is set.
Throws:
java.lang.ArithmeticException n is negative.
    public boolean testBit(int n) {
        if (n<0)
            throw new ArithmeticException("Negative bit address");
        return (getInt(n/32) & (1 << (n%32))) != 0;
    }

    
Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit set. (Computes (this | (1<<n)).)

Parameters:
n index of bit to set.
Returns:
this | (1<<n)
Throws:
java.lang.ArithmeticException n is negative.
    public BigInteger setBit(int n) {
        if (n<0)
            throw new ArithmeticException("Negative bit address");
        int intNum = n/32;
        int[] result = new int[Math.max(intLength(), intNum+2)];
        for (int i=0; i<result.lengthi++)
            result[result.length-i-1] = getInt(i);
        result[result.length-intNum-1] |= (1 << (n%32));
        return valueOf(result);
    }

    
Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit cleared. (Computes (this & ~(1<<n)).)

Parameters:
n index of bit to clear.
Returns:
this & ~(1<<n)
Throws:
java.lang.ArithmeticException n is negative.
    public BigInteger clearBit(int n) {
        if (n<0)
            throw new ArithmeticException("Negative bit address");
        int intNum = n/32;
        int[] result = new int[Math.max(intLength(), (n+1)/32+1)];
        for (int i=0; i<result.lengthi++)
            result[result.length-i-1] = getInt(i);
        result[result.length-intNum-1] &= ~(1 << (n%32));
        return valueOf(result);
    }

    
Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit flipped. (Computes (this ^ (1<<n)).)

Parameters:
n index of bit to flip.
Returns:
this ^ (1<<n)
Throws:
java.lang.ArithmeticException n is negative.
    public BigInteger flipBit(int n) {
        if (n<0)
            throw new ArithmeticException("Negative bit address");
        int intNum = n/32;
        int[] result = new int[Math.max(intLength(), intNum+2)];
        for (int i=0; i<result.lengthi++)
            result[result.length-i-1] = getInt(i);
        result[result.length-intNum-1] ^= (1 << (n%32));
        return valueOf(result);
    }

    
Returns the index of the rightmost (lowest-order) one bit in this BigInteger (the number of zero bits to the right of the rightmost one bit). Returns -1 if this BigInteger contains no one bits. (Computes (this==0? -1 : log2(this & -this)).)

Returns:
index of the rightmost one bit in this BigInteger.
    public int getLowestSetBit() {
        /*
         * Initialize lowestSetBit field the first time this method is
         * executed. This method depends on the atomicity of int modifies;
         * without this guarantee, it would have to be synchronized.
         */
        if ( == -2) {
            if ( == 0) {
                 = -1;
            } else {
                // Search for lowest order nonzero int
                int i,b;
                for (i=0; (b = getInt(i))==0; i++)
                    ;
                 = (i << 5) + trailingZeroCnt(b);
            }
        }
        return ;
    }
    // Miscellaneous Bit Operations

    
Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit. For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. (Computes (ceil(log2(this < 0 ? -this : this+1))).)

Returns:
number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.
    public int bitLength() {
        /*
         * Initialize bitLength field the first time this method is executed.
         * This method depends on the atomicity of int modifies; without
         * this guarantee, it would have to be synchronized.
         */
        if ( == -1) {
            if ( == 0) {
                 = 0;
            } else {
                // Calculate the bit length of the magnitude
                int magBitLength = ((.-1) << 5) + bitLen([0]);
                if ( < 0) {
                    // Check if magnitude is a power of two
                    boolean pow2 = (bitCnt([0]) == 1);
                    for(int i=1; i<. && pow2i++)
                        pow2 = ([i]==0);
                     = (pow2 ? magBitLength-1 : magBitLength);
                } else {
                     = magBitLength;
                }
            }
        }
        return ;
    }

    
bitLen(val) is the number of bits in val.
    static int bitLen(int w) {
        // Binary search - decision tree (5 tests, rarely 6)
        return
         (w < 1<<15 ?
          (w < 1<<7 ?
           (w < 1<<3 ?
            (w < 1<<1 ? (w < 1<<0 ? (w<0 ? 32 : 0) : 1) : (w < 1<<2 ? 2 : 3)) :
            (w < 1<<5 ? (w < 1<<4 ? 4 : 5) : (w < 1<<6 ? 6 : 7))) :
           (w < 1<<11 ?
            (w < 1<<9 ? (w < 1<<8 ? 8 : 9) : (w < 1<<10 ? 10 : 11)) :
            (w < 1<<13 ? (w < 1<<12 ? 12 : 13) : (w < 1<<14 ? 14 : 15)))) :
          (w < 1<<23 ?
           (w < 1<<19 ?
            (w < 1<<17 ? (w < 1<<16 ? 16 : 17) : (w < 1<<18 ? 18 : 19)) :
            (w < 1<<21 ? (w < 1<<20 ? 20 : 21) : (w < 1<<22 ? 22 : 23))) :
           (w < 1<<27 ?
            (w < 1<<25 ? (w < 1<<24 ? 24 : 25) : (w < 1<<26 ? 26 : 27)) :
            (w < 1<<29 ? (w < 1<<28 ? 28 : 29) : (w < 1<<30 ? 30 : 31)))));
    }
    /*
     * trailingZeroTable[i] is the number of trailing zero bits in the binary
     * representation of i.
     */
    final static byte trailingZeroTable[] = {
      -25, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
        4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};

    
Returns the number of bits in the two's complement representation of this BigInteger that differ from its sign bit. This method is useful when implementing bit-vector style sets atop BigIntegers.

Returns:
number of bits in the two's complement representation of this BigInteger that differ from its sign bit.
    public int bitCount() {
        /*
         * Initialize bitCount field the first time this method is executed.
         * This method depends on the atomicity of int modifies; without
         * this guarantee, it would have to be synchronized.
         */
        if ( == -1) {
            // Count the bits in the magnitude
            int magBitCount = 0;
            for (int i=0; i<.i++)
                magBitCount += bitCnt([i]);
            if ( < 0) {
                // Count the trailing zeros in the magnitude
                int magTrailingZeroCount = 0, j;
                for (j=.-1; [j]==0; j--)
                    magTrailingZeroCount += 32;
                magTrailingZeroCount +=
                            trailingZeroCnt([j]);
                 = magBitCount + magTrailingZeroCount - 1;
            } else {
                 = magBitCount;
            }
        }
        return ;
    }
    static int bitCnt(int val) {
        val -= (0xaaaaaaaa & val) >>> 1;
        val = (val & 0x33333333) + ((val >>> 2) & 0x33333333);
        val = val + (val >>> 4) & 0x0f0f0f0f;
        val += val >>> 8;
        val += val >>> 16;
        return val & 0xff;
    }
    static int trailingZeroCnt(int val) {
        // Loop unrolled for performance
        int byteVal = val & 0xff;
        if (byteVal != 0)
            return [byteVal];
        byteVal = (val >>> 8) & 0xff;
        if (byteVal != 0)
            return [byteVal] + 8;
        byteVal = (val >>> 16) & 0xff;
        if (byteVal != 0)
            return [byteVal] + 16;
        byteVal = (val >>> 24) & 0xff;
        return [byteVal] + 24;
    }
    // Primality Testing

    
Returns true if this BigInteger is probably prime, false if it's definitely composite. If certainty is <= 0, true is returned.

Parameters:
certainty a measure of the uncertainty that the caller is willing to tolerate: if the call returns true the probability that this BigInteger is prime exceeds (1 - 1/2certainty). The execution time of this method is proportional to the value of this parameter.
Returns:
true if this BigInteger is probably prime, false if it's definitely composite.
    public boolean isProbablePrime(int certainty) {
        if (certainty <= 0)
            return true;
        BigInteger w = this.abs();
        if (w.equals())
            return true;
        if (!w.testBit(0) || w.equals())
            return false;
        return w.primeToCertainty(certaintynull);
    }
    // Comparison Operations

    
Compares this BigInteger with the specified BigInteger. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.

Parameters:
val BigInteger to which this BigInteger is to be compared.
Returns:
-1, 0 or 1 as this BigInteger is numerically less than, equal to, or greater than val.
    public int compareTo(BigInteger val) {
        return (==val.signum
                ? *intArrayCmp(val.mag)
                : (>val.signum ? 1 : -1));
    }
    /*
     * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is
     * less than, equal to, or greater than arg2.
     */
    private static int intArrayCmp(int[] arg1int[] arg2) {
        if (arg1.length < arg2.length)
            return -1;
        if (arg1.length > arg2.length)
            return 1;
        // Argument lengths are equal; compare the values
        for (int i=0; i<arg1.lengthi++) {
            long b1 = arg1[i] & ;
            long b2 = arg2[i] & ;
            if (b1 < b2)
                return -1;
            if (b1 > b2)
                return 1;
        }
        return 0;
    }

    
Compares this BigInteger with the specified Object for equality.

Parameters:
x Object to which this BigInteger is to be compared.
Returns:
true if and only if the specified Object is a BigInteger whose value is numerically equal to this BigInteger.
    public boolean equals(Object x) {
        // This test is just an optimization, which may or may not help
        if (x == this)
            return true;
        if (!(x instanceof BigInteger))
            return false;
        BigInteger xInt = (BigIntegerx;
        if (xInt.signum !=  || xInt.mag.length != .)
            return false;
        for (int i=0; i<.i++)
            if (xInt.mag[i] != [i])
                return false;
        return true;
    }

    
Returns the minimum of this BigInteger and val.

Parameters:
val value with which the minimum is to be computed.
Returns:
the BigInteger whose value is the lesser of this BigInteger and val. If they are equal, either may be returned.
    public BigInteger min(BigInteger val) {
        return (compareTo(val)<0 ? this : val);
    }

    
Returns the maximum of this BigInteger and val.

Parameters:
val value with which the maximum is to be computed.
Returns:
the BigInteger whose value is the greater of this and val. If they are equal, either may be returned.
    public BigInteger max(BigInteger val) {
        return (compareTo(val)>0 ? this : val);
    }
    // Hash Function

    
Returns the hash code for this BigInteger.

Returns:
hash code for this BigInteger.
    public int hashCode() {
        int hashCode = 0;
        for (int i=0; i<.i++)
            hashCode = (int)(31*hashCode + ([i] & ));
        return hashCode * ;
    }

    
Returns the String representation of this BigInteger in the given radix. If the radix is outside the range from java.lang.Character.MIN_RADIX to java.lang.Character.MAX_RADIX inclusive, it will default to 10 (as is the case for Integer.toString). The digit-to-character mapping provided by Character.forDigit is used, and a minus sign is prepended if appropriate. (This representation is compatible with the (String, int) constructor.)

Parameters:
radix radix of the String representation.
Returns:
String representation of this BigInteger in the given radix.
See also:
java.lang.Integer.toString()
java.lang.Character.forDigit(int,int)
BigInteger(java.lang.String,int)
    public String toString(int radix) {
        if ( == 0)
            return "0";
        if (radix < . || radix > .)
            radix = 10;
        // Compute upper bound on number of digit groups and allocate space
        int maxNumDigitGroups = (4*. + 6)/7;
        String digitGroup[] = new String[maxNumDigitGroups];
        // Translate number to string, a digit group at a time
        BigInteger tmp = this.abs();
        int numGroups = 0;
        while (tmp.signum != 0) {
            BigInteger d = [radix];
            MutableBigInteger q = new MutableBigInteger(),
                              r = new MutableBigInteger(),
                              a = new MutableBigInteger(tmp.mag),
                              b = new MutableBigInteger(d.mag);
            a.divide(bqr);
            BigInteger q2 = new BigInteger(qtmp.signum * d.signum);
            BigInteger r2 = new BigInteger(rtmp.signum * d.signum);
            digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
            tmp = q2;
        }
        // Put sign (if any) and first digit group into result buffer
        StringBuilder buf = new StringBuilder(numGroups*[radix]+1);
        if (<0)
            buf.append('-');
        buf.append(digitGroup[numGroups-1]);
        // Append remaining digit groups padded with leading zeros
        for (int i=numGroups-2; i>=0; i--) {
            // Prepend (any) leading zeros for this digit group
            int numLeadingZeros = [radix]-digitGroup[i].length();
            if (numLeadingZeros != 0)
                buf.append([numLeadingZeros]);
            buf.append(digitGroup[i]);
        }
        return buf.toString();
    }
    /* zero[i] is a string of i consecutive zeros. */
    private static String zeros[] = new String[64];
    static {
        [63] =
            "000000000000000000000000000000000000000000000000000000000000000";
        for (int i=0; i<63; i++)
            [i] = [63].substring(0, i);
    }

    
Returns the decimal String representation of this BigInteger. The digit-to-character mapping provided by Character.forDigit is used, and a minus sign is prepended if appropriate. (This representation is compatible with the (String) constructor, and allows for String concatenation with Java's + operator.)

Returns:
decimal String representation of this BigInteger.
See also:
java.lang.Character.forDigit(int,int)
BigInteger(java.lang.String)
    public String toString() {
        return toString(10);
    }

    
Returns a byte array containing the two's-complement representation of this BigInteger. The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit, which is (ceil((this.bitLength() + 1)/8)). (This representation is compatible with the (byte[]) constructor.)

Returns:
a byte array containing the two's-complement representation of this BigInteger.
See also:
BigInteger(byte[])
    public byte[] toByteArray() {
        int byteLen = bitLength()/8 + 1;
        byte[] byteArray = new byte[byteLen];
        for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i>=0; i--) {
            if (bytesCopied == 4) {
                nextInt = getInt(intIndex++);
                bytesCopied = 1;
            } else {
                nextInt >>>= 8;
                bytesCopied++;
            }
            byteArray[i] = (byte)nextInt;
        }
        return byteArray;
    }

    
Converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int as defined in the Java Language Specification: if this BigInteger is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.

Returns:
this BigInteger converted to an int.
    public int intValue() {
        int result = 0;
        result = getInt(0);
        return result;
    }

    
Converts this BigInteger to a long. This conversion is analogous to a narrowing primitive conversion from long to int as defined in the Java Language Specification: if this BigInteger is too big to fit in a long, only the low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.

Returns:
this BigInteger converted to a long.
    public long longValue() {
        long result = 0;
        for (int i=1; i>=0; i--)
            result = (result << 32) + (getInt(i) & );
        return result;
    }

    
Converts this BigInteger to a float. This conversion is similar to the narrowing primitive conversion from double to float defined in the Java Language Specification: if this BigInteger has too great a magnitude to represent as a float, it will be converted to java.lang.Float.NEGATIVE_INFINITY or java.lang.Float.POSITIVE_INFINITY as appropriate. Note that even when the return value is finite, this conversion can lose information about the precision of the BigInteger value.

Returns:
this BigInteger converted to a float.
    public float floatValue() {
        // Somewhat inefficient, but guaranteed to work.
        return Float.parseFloat(this.toString());
    }

    
Converts this BigInteger to a double. This conversion is similar to the narrowing primitive conversion from double to float defined in the Java Language Specification: if this BigInteger has too great a magnitude to represent as a double, it will be converted to java.lang.Double.NEGATIVE_INFINITY or java.lang.Double.POSITIVE_INFINITY as appropriate. Note that even when the return value is finite, this conversion can lose information about the precision of the BigInteger value.

Returns:
this BigInteger converted to a double.
    public double doubleValue() {
        // Somewhat inefficient, but guaranteed to work.
        return Double.parseDouble(this.toString());
    }

    
Returns a copy of the input array stripped of any leading zero bytes.
    private static int[] stripLeadingZeroInts(int val[]) {
        int byteLength = val.length;
        int keep;
        // Find first nonzero byte
        for (keep=0; keep<val.length && val[keep]==0; keep++)
            ;
        int result[] = new int[val.length - keep];
        for(int i=0; i<val.length - keepi++)
            result[i] = val[keep+i];
        return result;
    }

    
Returns the input array stripped of any leading zero bytes. Since the source is trusted the copying may be skipped.
    private static int[] trustedStripLeadingZeroInts(int val[]) {
        int byteLength = val.length;
        int keep;
        // Find first nonzero byte
        for (keep=0; keep<val.length && val[keep]==0; keep++)
            ;
        // Only perform copy if necessary
        if (keep > 0) {
            int result[] = new int[val.length - keep];
            for(int i=0; i<val.length - keepi++)
               result[i] = val[keep+i];
            return result;
        }
        return val;
    }

    
Returns a copy of the input array stripped of any leading zero bytes.
    private static int[] stripLeadingZeroBytes(byte a[]) {
        int byteLength = a.length;
        int keep;
        // Find first nonzero byte
        for (keep=0; keep<a.length && a[keep]==0; keep++)
            ;
        // Allocate new array and copy relevant part of input array
        int intLength = ((byteLength - keep) + 3)/4;
        int[] result = new int[intLength];
        int b = byteLength - 1;
        for (int i = intLength-1; i >= 0; i--) {
            result[i] = a[b--] & 0xff;
            int bytesRemaining = b - keep + 1;
            int bytesToTransfer = Math.min(3, bytesRemaining);
            for (int j=8; j <= 8*bytesToTransferj += 8)
                result[i] |= ((a[b--] & 0xff) << j);
        }
        return result;
    }

    
Takes an array a representing a negative 2's-complement number and returns the minimal (no leading zero bytes) unsigned whose value is -a.
    private static int[] makePositive(byte a[]) {
        int keepk;
        int byteLength = a.length;
        // Find first non-sign (0xff) byte of input
        for (keep=0; keep<byteLength && a[keep]==-1; keep++)
            ;
        /* Allocate output array.  If all non-sign bytes are 0x00, we must
         * allocate space for one extra output byte. */
        for (k=keepk<byteLength && a[k]==0; k++)
            ;
        int extraByte = (k==byteLength) ? 1 : 0;
        int intLength = ((byteLength - keep + extraByte) + 3)/4;
        int result[] = new int[intLength];
        /* Copy one's complement of input into output, leaving extra
         * byte (if it exists) == 0x00 */
        int b = byteLength - 1;
        for (int i = intLength-1; i >= 0; i--) {
            result[i] = a[b--] & 0xff;
            int numBytesToTransfer = Math.min(3, b-keep+1);
            if (numBytesToTransfer < 0)
                numBytesToTransfer = 0;
            for (int j=8; j <= 8*numBytesToTransferj += 8)
                result[i] |= ((a[b--] & 0xff) << j);
            // Mask indicates which bits must be complemented
            int mask = -1 >>> (8*(3-numBytesToTransfer));
            result[i] = ~result[i] & mask;
        }
        // Add one to one's complement to generate two's complement
        for (int i=result.length-1; i>=0; i--) {
            result[i] = (int)((result[i] & ) + 1);
            if (result[i] != 0)
                break;
        }
        return result;
    }

    
Takes an array a representing a negative 2's-complement number and returns the minimal (no leading zero ints) unsigned whose value is -a.
    private static int[] makePositive(int a[]) {
        int keepj;
        // Find first non-sign (0xffffffff) int of input
        for (keep=0; keep<a.length && a[keep]==-1; keep++)
            ;
        /* Allocate output array.  If all non-sign ints are 0x00, we must
         * allocate space for one extra output int. */
        for (j=keepj<a.length && a[j]==0; j++)
            ;
        int extraInt = (j==a.length ? 1 : 0);
        int result[] = new int[a.length - keep + extraInt];
        /* Copy one's complement of input into output, leaving extra
         * int (if it exists) == 0x00 */
        for (int i = keepi<a.lengthi++)
            result[i - keep + extraInt] = ~a[i];
        // Add one to one's complement to generate two's complement
        for (int i=result.length-1; ++result[i]==0; i--)
            ;
        return result;
    }
    /*
     * The following two arrays are used for fast String conversions.  Both
     * are indexed by radix.  The first is the number of digits of the given
     * radix that can fit in a Java long without "going negative", i.e., the
     * highest integer n such that radix**n < 2**63.  The second is the
     * "long radix" that tears each number into "long digits", each of which
     * consists of the number of digits in the corresponding element in
     * digitsPerLong (longRadix[i] = i**digitPerLong[i]).  Both arrays have
     * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
     * used.
     */
    private static int digitsPerLong[] = {0, 0,
        62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
        14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
    private static BigInteger longRadix[] = {nullnull,
        valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
        valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
        valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
        valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
        valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
        valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
        valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
        valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
        valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
        valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
        valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
        valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
        valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
        valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
        valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
        valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
        valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
        valueOf(0x41c21cb8e1000000L)};
    /*
     * These two arrays are the integer analogue of above.
     */
    private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11,
        11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
        6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};
    private static int intRadix[] = {0, 0,
        0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
        0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
        0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f,  0x10000000,
        0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
        0x6c20a40,  0x8d2d931,  0xb640000,  0xe8d4a51,  0x1269ae40,
        0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
        0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
    };

    
These routines provide access to the two's complement representation of BigIntegers.


    
Returns the length of the two's complement representation in ints, including space for at least one sign bit.
    private int intLength() {
        return bitLength()/32 + 1;
    }
    /* Returns sign bit */
    private int signBit() {
        return  < 0 ? 1 : 0;
    }
    /* Returns an int of sign bits */
    private int signInt() {
        return  < 0 ? -1 : 0;
    }

    
Returns the specified int of the little-endian two's complement representation (int 0 is the least significant). The int number can be arbitrarily high (values are logically preceded by infinitely many sign ints).
    private int getInt(int n) {
        if (n < 0)
            return 0;
        if (n >= .)
            return signInt();
        int magInt = [.-n-1];
        return ( >= 0 ? magInt :
                (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
    }

    
Returns the index of the int that contains the first nonzero int in the little-endian binary representation of the magnitude (int 0 is the least significant). If the magnitude is zero, return value is undefined.
     private int firstNonzeroIntNum() {
        /*
         * Initialize firstNonzeroIntNum field the first time this method is
         * executed. This method depends on the atomicity of int modifies;
         * without this guarantee, it would have to be synchronized.
         */
        if ( == -2) {
            // Search for the first nonzero int
            int i;
            for (i=.-1; i>=0 && [i]==0; i--)
                ;
             = .-i-1;
        }
        return ;
    }

    
use serialVersionUID from JDK 1.1. for interoperability
    private static final long serialVersionUID = -8287574255936472291L;

    
Serializable fields for BigInteger.

SerialField:
signum int signum of this BigInteger.
SerialField:
magnitude int[] magnitude array of this BigInteger.
SerialField:
bitCount int number of bits in this BigInteger
SerialField:
bitLength int the number of bits in the minimal two's-complement representation of this BigInteger
SerialField:
lowestSetBit int lowest set bit in the twos complement representation
    private static final ObjectStreamField[] serialPersistentFields = {
        new ObjectStreamField("signum".),
        new ObjectStreamField("magnitude"byte[].class),
        new ObjectStreamField("bitCount".),
        new ObjectStreamField("bitLength".),
        new ObjectStreamField("firstNonzeroByteNum".),
        new ObjectStreamField("lowestSetBit".)
        };

    
Reconstitute the BigInteger instance from a stream (that is, deserialize it). The magnitude is read in as an array of bytes for historical reasons, but it is converted to an array of ints and the byte array is discarded.
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException {
        /*
         * In order to maintain compatibility with previous serialized forms,
         * the magnitude of a BigInteger is serialized as an array of bytes.
         * The magnitude field is used as a temporary store for the byte array
         * that is deserialized. The cached computation fields should be
         * transient but are serialized for compatibility reasons.
         */
        // prepare to read the alternate persistent fields
        ObjectInputStream.GetField fields = s.readFields();
        // Read the alternate persistent fields that we care about
         = fields.get("signum", -2);
        byte[] magnitude = (byte[])fields.get("magnitude"null);
        // Validate signum
        if ( < -1 ||  > 1) {
            String message = "BigInteger: Invalid signum value";
            if (fields.defaulted("signum"))
                message = "BigInteger: Signum not present in stream";
            throw new java.io.StreamCorruptedException(message);
        }
        if ((magnitude.length==0) != (==0)) {
            String message = "BigInteger: signum-magnitude mismatch";
            if (fields.defaulted("magnitude"))
                message = "BigInteger: Magnitude not present in stream";
            throw new java.io.StreamCorruptedException(message);
        }
        // Set "cached computation" fields to their initial values
         =  = -1;
        // Calculate mag field from magnitude and discard magnitude
         = stripLeadingZeroBytes(magnitude);
    }

    
Save the BigInteger instance to a stream. The magnitude of a BigInteger is serialized as a byte array for historical reasons.

SerialData:
two necessary fields are written as well as obsolete fields for compatibility with older versions.
    private void writeObject(ObjectOutputStream sthrows IOException {
        // set the values of the Serializable fields
        ObjectOutputStream.PutField fields = s.putFields();
        fields.put("signum");
        fields.put("magnitude"magSerializedForm());
        fields.put("bitCount", -1);
        fields.put("bitLength", -1);
        fields.put("lowestSetBit", -2);
        fields.put("firstNonzeroByteNum", -2);
        // save them
        s.writeFields();
}

    
Returns the mag array as an array of bytes.
    private byte[] magSerializedForm() {
        int bitLen = (. == 0 ? 0 :
                      ((. - 1) << 5) + bitLen([0]));
        int byteLen = (bitLen + 7)/8;
        byte[] result = new byte[byteLen];
        for (int i=byteLen-1, bytesCopied=4, intIndex=.-1, nextInt=0;
             i>=0; i--) {
            if (bytesCopied == 4) {
                nextInt = [intIndex--];
                bytesCopied = 1;
            } else {
                nextInt >>>= 8;
                bytesCopied++;
            }
            result[i] = (byte)nextInt;
        }
        return result;
    }
New to GrepCode? Check out our FAQ X