1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18// BEGIN android-note
19// Since the original Harmony Code of the BigInteger class was strongly modified,
20// in order to use the more efficient OpenSSL BIGNUM implementation,
21// no android-modification-tags were placed, at all.
22// END android-note
23
24package java.math;
25
26import java.io.IOException;
27import java.io.ObjectInputStream;
28import java.io.ObjectOutputStream;
29import java.io.Serializable;
30import java.util.Random;
31
32/**
33 * An immutable signed integer of arbitrary magnitude.
34 *
35 * <h3>Fast Cryptography</h3>
36 * This implementation is efficient for operations traditionally used in
37 * cryptography, such as the generation of large prime numbers and computation
38 * of the modular inverse.
39 *
40 * <h3>Slow Two's Complement Bitwise Operations</h3>
41 * This API includes operations for bitwise operations in two's complement
42 * representation. Two's complement is not the internal representation used by
43 * this implementation, so such methods may be inefficient. Use {@link
44 * java.util.BitSet} for high-performance bitwise operations on
45 * arbitrarily-large sequences of bits.
46 */
47public class BigInteger extends Number
48        implements Comparable<BigInteger>, Serializable {
49
50    /** This is the serialVersionUID used by the sun implementation. */
51    private static final long serialVersionUID = -8287574255936472291L;
52
53    private transient BigInt bigInt;
54
55    private transient boolean nativeIsValid = false;
56
57    private transient boolean javaIsValid = false;
58
59    /** The magnitude of this in the little-endian representation. */
60    transient int[] digits;
61
62    /**
63     * The length of this in measured in ints. Can be less than
64     * digits.length().
65     */
66    transient int numberLength;
67
68    /** The sign of this. */
69    transient int sign;
70
71    /** The {@code BigInteger} constant 0. */
72    public static final BigInteger ZERO = new BigInteger(0, 0);
73
74    /** The {@code BigInteger} constant 1. */
75    public static final BigInteger ONE = new BigInteger(1, 1);
76
77    /** The {@code BigInteger} constant 10. */
78    public static final BigInteger TEN = new BigInteger(1, 10);
79
80    /** The {@code BigInteger} constant -1. */
81    static final BigInteger MINUS_ONE = new BigInteger(-1, 1);
82
83    /** All the {@code BigInteger} numbers in the range [0,10] are cached. */
84    static final BigInteger[] SMALL_VALUES = { ZERO, ONE, new BigInteger(1, 2),
85            new BigInteger(1, 3), new BigInteger(1, 4), new BigInteger(1, 5),
86            new BigInteger(1, 6), new BigInteger(1, 7), new BigInteger(1, 8),
87            new BigInteger(1, 9), TEN };
88
89    private transient int firstNonzeroDigit = -2;
90
91    /** sign field, used for serialization. */
92    private int signum;
93
94    /** absolute value field, used for serialization */
95    private byte[] magnitude;
96
97    /** Cache for the hash code. */
98    private transient int hashCode = 0;
99
100    BigInteger(BigInt bigInt) {
101        if (bigInt == null || bigInt.getNativeBIGNUM() == 0) {
102            throw new AssertionError();
103        }
104        setBigInt(bigInt);
105    }
106
107    BigInteger(int sign, long value) {
108        BigInt bigInt = new BigInt();
109        bigInt.putULongInt(value, (sign < 0));
110        setBigInt(bigInt);
111    }
112
113    /**
114     * Constructs a number without creating new space. This construct should be
115     * used only if the three fields of representation are known.
116     *
117     * @param sign the sign of the number.
118     * @param numberLength the length of the internal array.
119     * @param digits a reference of some array created before.
120     */
121    BigInteger(int sign, int numberLength, int[] digits) {
122        setJavaRepresentation(sign, numberLength, digits);
123    }
124
125    /**
126     * Constructs a random non-negative {@code BigInteger} instance in the range
127     * {@code [0, pow(2, numBits)-1]}.
128     *
129     * @param numBits maximum length of the new {@code BigInteger} in bits.
130     * @param random is the random number generator to be used.
131     * @throws IllegalArgumentException if {@code numBits} < 0.
132     */
133    public BigInteger(int numBits, Random random) {
134        if (numBits < 0) {
135            throw new IllegalArgumentException("numBits < 0: " + numBits);
136        }
137        if (numBits == 0) {
138            setJavaRepresentation(0, 1, new int[] { 0 });
139        } else {
140            int sign = 1;
141            int numberLength = (numBits + 31) >> 5;
142            int[] digits = new int[numberLength];
143            for (int i = 0; i < numberLength; i++) {
144                digits[i] = random.nextInt();
145            }
146            // Using only the necessary bits
147            digits[numberLength - 1] >>>= (-numBits) & 31;
148            setJavaRepresentation(sign, numberLength, digits);
149        }
150        javaIsValid = true;
151    }
152
153    /**
154     * Constructs a random {@code BigInteger} instance in the range {@code [0,
155     * pow(2, bitLength)-1]} which is probably prime. The probability that the
156     * returned {@code BigInteger} is prime is beyond
157     * {@code 1 - 1/pow(2, certainty)}.
158     *
159     * <p><b>Implementation Note:</b> the {@code Random} argument is ignored.
160     * This implementation uses OpenSSL's {@code bn_rand} as a source of
161     * cryptographically strong pseudo-random numbers.
162     *
163     * @param bitLength length of the new {@code BigInteger} in bits.
164     * @param certainty tolerated primality uncertainty.
165     * @throws ArithmeticException if {@code bitLength < 2}.
166     * @see <a href="http://www.openssl.org/docs/crypto/BN_rand.html">
167     *      Specification of random generator used from OpenSSL library</a>
168     */
169    public BigInteger(int bitLength, int certainty, Random unused) {
170        if (bitLength < 2) {
171            throw new ArithmeticException("bitLength < 2: " + bitLength);
172        }
173        setBigInt(BigInt.generatePrimeDefault(bitLength));
174    }
175
176    /**
177     * Constructs a new {@code BigInteger} by parsing {@code value}. The string
178     * representation consists of an optional plus or minus sign followed by a
179     * non-empty sequence of decimal digits. Digits are interpreted as if by
180     * {@code Character.digit(char,10)}.
181     *
182     * @param value string representation of the new {@code BigInteger}.
183     * @throws NullPointerException if {@code value == null}.
184     * @throws NumberFormatException if {@code value} is not a valid
185     *     representation of a {@code BigInteger}.
186     */
187    public BigInteger(String value) {
188        BigInt bigInt = new BigInt();
189        bigInt.putDecString(value);
190        setBigInt(bigInt);
191    }
192
193    /**
194     * Constructs a new {@code BigInteger} instance by parsing {@code value}.
195     * The string representation consists of an optional plus or minus sign
196     * followed by a non-empty sequence of digits in the specified radix. Digits
197     * are interpreted as if by {@code Character.digit(char, radix)}.
198     *
199     * @param value string representation of the new {@code BigInteger}.
200     * @param radix the base to be used for the conversion.
201     * @throws NullPointerException if {@code value == null}.
202     * @throws NumberFormatException if {@code value} is not a valid
203     *     representation of a {@code BigInteger} or if {@code radix <
204     *     Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}.
205     */
206    public BigInteger(String value, int radix) {
207        if (value == null) {
208            throw new NullPointerException("value == null");
209        }
210        if (radix == 10) {
211            BigInt bigInt = new BigInt();
212            bigInt.putDecString(value);
213            setBigInt(bigInt);
214        } else if (radix == 16) {
215            BigInt bigInt = new BigInt();
216            bigInt.putHexString(value);
217            setBigInt(bigInt);
218        } else {
219            if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
220                throw new NumberFormatException("bad radix: " + radix);
221            }
222            if (value.isEmpty()) {
223                throw new NumberFormatException("value.isEmpty()");
224            }
225            BigInteger.parseFromString(this, value, radix);
226        }
227    }
228
229    /**
230     * Constructs a new {@code BigInteger} instance with the given sign and
231     * magnitude.
232     *
233     * @param signum sign of the new {@code BigInteger} (-1 for negative, 0 for
234     *     zero, 1 for positive).
235     * @param magnitude magnitude of the new {@code BigInteger} with the most
236     *     significant byte first.
237     * @throws NullPointerException if {@code magnitude == null}.
238     * @throws NumberFormatException if the sign is not one of -1, 0, 1 or if
239     *     the sign is zero and the magnitude contains non-zero entries.
240     */
241    public BigInteger(int signum, byte[] magnitude) {
242        if (magnitude == null) {
243            throw new NullPointerException("magnitude == null");
244        }
245        if (signum < -1 || signum > 1) {
246            throw new NumberFormatException("bad signum: " + signum);
247        }
248        if (signum == 0) {
249            for (byte element : magnitude) {
250                if (element != 0) {
251                    throw new NumberFormatException("signum-magnitude mismatch");
252                }
253            }
254        }
255        BigInt bigInt = new BigInt();
256        bigInt.putBigEndian(magnitude, signum < 0);
257        setBigInt(bigInt);
258    }
259
260    /**
261     * Constructs a new {@code BigInteger} from the given two's complement
262     * representation. The most significant byte is the entry at index 0. The
263     * most significant bit of this entry determines the sign of the new {@code
264     * BigInteger} instance. The array must be nonempty.
265     *
266     * @param value two's complement representation of the new {@code
267     *     BigInteger}.
268     * @throws NullPointerException if {@code value == null}.
269     * @throws NumberFormatException if the length of {@code value} is zero.
270     */
271    public BigInteger(byte[] value) {
272        if (value.length == 0) {
273            throw new NumberFormatException("value.length == 0");
274        }
275        BigInt bigInt = new BigInt();
276        bigInt.putBigEndianTwosComplement(value);
277        setBigInt(bigInt);
278    }
279
280    /**
281     * Returns the internal native representation of this big integer, computing
282     * it if necessary.
283     */
284    BigInt getBigInt() {
285        if (nativeIsValid) {
286            return bigInt;
287        }
288
289        synchronized (this) {
290            if (nativeIsValid) {
291                return bigInt;
292            }
293            BigInt bigInt = new BigInt();
294            bigInt.putLittleEndianInts(digits, (sign < 0));
295            setBigInt(bigInt);
296            return bigInt;
297        }
298    }
299
300    private void setBigInt(BigInt bigInt) {
301        this.bigInt = bigInt;
302        this.nativeIsValid = true;
303    }
304
305    private void setJavaRepresentation(int sign, int numberLength, int[] digits) {
306        // decrement numberLength to drop leading zeroes...
307        while (numberLength > 0 && digits[--numberLength] == 0) {
308            ;
309        }
310        // ... and then increment it back because we always drop one too many
311        if (digits[numberLength++] == 0) {
312            sign = 0;
313        }
314        this.sign = sign;
315        this.digits = digits;
316        this.numberLength = numberLength;
317        this.javaIsValid = true;
318    }
319
320    void prepareJavaRepresentation() {
321        if (javaIsValid) {
322            return;
323        }
324
325        synchronized (this) {
326            if (javaIsValid) {
327                return;
328            }
329            int sign = bigInt.sign();
330            int[] digits = (sign != 0) ? bigInt.littleEndianIntsMagnitude() : new int[] { 0 };
331            setJavaRepresentation(sign, digits.length, digits);
332        }
333    }
334
335    /** Returns a {@code BigInteger} whose value is equal to {@code value}. */
336    public static BigInteger valueOf(long value) {
337        if (value < 0) {
338            if (value != -1) {
339                return new BigInteger(-1, -value);
340            }
341            return MINUS_ONE;
342        } else if (value < SMALL_VALUES.length) {
343            return SMALL_VALUES[(int) value];
344        } else {// (value > 10)
345            return new BigInteger(1, value);
346        }
347    }
348
349    /**
350     * Returns the two's complement representation of this {@code BigInteger} in
351     * a byte array.
352     */
353    public byte[] toByteArray() {
354        return twosComplement();
355    }
356
357    /**
358     * Returns a {@code BigInteger} whose value is the absolute value of {@code
359     * this}.
360     */
361    public BigInteger abs() {
362        BigInt bigInt = getBigInt();
363        if (bigInt.sign() >= 0) {
364            return this;
365        }
366        BigInt a = bigInt.copy();
367        a.setSign(1);
368        return new BigInteger(a);
369    }
370
371    /**
372     * Returns a {@code BigInteger} whose value is the {@code -this}.
373     */
374    public BigInteger negate() {
375        BigInt bigInt = getBigInt();
376        int sign = bigInt.sign();
377        if (sign == 0) {
378            return this;
379        }
380        BigInt a = bigInt.copy();
381        a.setSign(-sign);
382        return new BigInteger(a);
383    }
384
385    /**
386     * Returns a {@code BigInteger} whose value is {@code this + value}.
387     */
388    public BigInteger add(BigInteger value) {
389        BigInt lhs = getBigInt();
390        BigInt rhs = value.getBigInt();
391        if (rhs.sign() == 0) {
392            return this;
393        }
394        if (lhs.sign() == 0) {
395            return value;
396        }
397        return new BigInteger(BigInt.addition(lhs, rhs));
398    }
399
400    /**
401     * Returns a {@code BigInteger} whose value is {@code this - value}.
402     */
403    public BigInteger subtract(BigInteger value) {
404        BigInt lhs = getBigInt();
405        BigInt rhs = value.getBigInt();
406        if (rhs.sign() == 0) {
407            return this;
408        }
409        return new BigInteger(BigInt.subtraction(lhs, rhs));
410    }
411
412    /**
413     * Returns the sign of this {@code BigInteger}.
414     *
415     * @return {@code -1} if {@code this < 0}, {@code 0} if {@code this == 0},
416     *     {@code 1} if {@code this > 0}.
417     */
418    public int signum() {
419        if (javaIsValid) {
420            return sign;
421        }
422        return getBigInt().sign();
423    }
424
425    /**
426     * Returns a {@code BigInteger} whose value is {@code this >> n}. For
427     * negative arguments, the result is also negative. The shift distance may
428     * be negative which means that {@code this} is shifted left.
429     *
430     * <p><b>Implementation Note:</b> Usage of this method on negative values is
431     * not recommended as the current implementation is not efficient.
432     *
433     * @param n shift distance
434     * @return {@code this >> n} if {@code n >= 0}; {@code this << (-n)}
435     *     otherwise
436     */
437    public BigInteger shiftRight(int n) {
438        return shiftLeft(-n);
439    }
440
441    /**
442     * Returns a {@code BigInteger} whose value is {@code this << n}. The
443     * result is equivalent to {@code this * pow(2, n)} if n >= 0. The shift
444     * distance may be negative which means that {@code this} is shifted right.
445     * The result then corresponds to {@code floor(this / pow(2, -n))}.
446     *
447     * <p><b>Implementation Note:</b> Usage of this method on negative values is
448     * not recommended as the current implementation is not efficient.
449     *
450     * @param n shift distance.
451     * @return {@code this << n} if {@code n >= 0}; {@code this >> (-n)}.
452     *     otherwise
453     */
454    public BigInteger shiftLeft(int n) {
455        if (n == 0) {
456            return this;
457        }
458        int sign = signum();
459        if (sign == 0) {
460            return this;
461        }
462        if ((sign > 0) || (n >= 0)) {
463            return new BigInteger(BigInt.shift(getBigInt(), n));
464        } else {
465            // Negative numbers faking 2's complement:
466            // Not worth optimizing this:
467            // Sticking to Harmony Java implementation.
468            return BitLevel.shiftRight(this, -n);
469        }
470    }
471
472    BigInteger shiftLeftOneBit() {
473        return (signum() == 0) ? this : BitLevel.shiftLeftOneBit(this);
474    }
475
476    /**
477     * Returns the length of the value's two's complement representation without
478     * leading zeros for positive numbers / without leading ones for negative
479     * values.
480     *
481     * <p>The two's complement representation of {@code this} will be at least
482     * {@code bitLength() + 1} bits long.
483     *
484     * <p>The value will fit into an {@code int} if {@code bitLength() < 32} or
485     * into a {@code long} if {@code bitLength() < 64}.
486     *
487     * @return the length of the minimal two's complement representation for
488     *     {@code this} without the sign bit.
489     */
490    public int bitLength() {
491        // Optimization to avoid unnecessary duplicate representation:
492        if (!nativeIsValid && javaIsValid) {
493            return BitLevel.bitLength(this);
494        }
495        return getBigInt().bitLength();
496    }
497
498    /**
499     * Tests whether the bit at position n in {@code this} is set. The result is
500     * equivalent to {@code this & pow(2, n) != 0}.
501     *
502     * <p><b>Implementation Note:</b> Usage of this method is not recommended as
503     * the current implementation is not efficient.
504     *
505     * @param n position where the bit in {@code this} has to be inspected.
506     * @throws ArithmeticException if {@code n < 0}.
507     */
508    public boolean testBit(int n) {
509        if (n < 0) {
510            throw new ArithmeticException("n < 0: " + n);
511        }
512        int sign = signum();
513        if (sign > 0 && nativeIsValid && !javaIsValid) {
514            return getBigInt().isBitSet(n);
515        } else {
516            // Negative numbers faking 2's complement:
517            // Not worth optimizing this:
518            // Sticking to Harmony Java implementation.
519            prepareJavaRepresentation();
520            if (n == 0) {
521                return ((digits[0] & 1) != 0);
522            }
523            int intCount = n >> 5;
524            if (intCount >= numberLength) {
525                return (sign < 0);
526            }
527            int digit = digits[intCount];
528            n = (1 << (n & 31)); // int with 1 set to the needed position
529            if (sign < 0) {
530                int firstNonZeroDigit = getFirstNonzeroDigit();
531                if (intCount < firstNonZeroDigit) {
532                    return false;
533                } else if (firstNonZeroDigit == intCount) {
534                    digit = -digit;
535                } else {
536                    digit = ~digit;
537                }
538            }
539            return ((digit & n) != 0);
540        }
541    }
542
543    /**
544     * Returns a {@code BigInteger} which has the same binary representation
545     * as {@code this} but with the bit at position n set. The result is
546     * equivalent to {@code this | pow(2, n)}.
547     *
548     * <p><b>Implementation Note:</b> Usage of this method is not recommended as
549     * the current implementation is not efficient.
550     *
551     * @param n position where the bit in {@code this} has to be set.
552     * @throws ArithmeticException if {@code n < 0}.
553     */
554    public BigInteger setBit(int n) {
555        prepareJavaRepresentation();
556        if (!testBit(n)) {
557            return BitLevel.flipBit(this, n);
558        } else {
559            return this;
560        }
561    }
562
563    /**
564     * Returns a {@code BigInteger} which has the same binary representation
565     * as {@code this} but with the bit at position n cleared. The result is
566     * equivalent to {@code this & ~pow(2, n)}.
567     *
568     * <p><b>Implementation Note:</b> Usage of this method is not recommended as
569     * the current implementation is not efficient.
570     *
571     * @param n position where the bit in {@code this} has to be cleared.
572     * @throws ArithmeticException if {@code n < 0}.
573     */
574    public BigInteger clearBit(int n) {
575        prepareJavaRepresentation();
576        if (testBit(n)) {
577            return BitLevel.flipBit(this, n);
578        } else {
579            return this;
580        }
581    }
582
583    /**
584     * Returns a {@code BigInteger} which has the same binary representation
585     * as {@code this} but with the bit at position n flipped. The result is
586     * equivalent to {@code this ^ pow(2, n)}.
587     *
588     * <p><b>Implementation Note:</b> Usage of this method is not recommended as
589     * the current implementation is not efficient.
590     *
591     * @param n position where the bit in {@code this} has to be flipped.
592     * @throws ArithmeticException if {@code n < 0}.
593     */
594    public BigInteger flipBit(int n) {
595        prepareJavaRepresentation();
596        if (n < 0) {
597            throw new ArithmeticException("n < 0: " + n);
598        }
599        return BitLevel.flipBit(this, n);
600    }
601
602    /**
603     * Returns the position of the lowest set bit in the two's complement
604     * representation of this {@code BigInteger}. If all bits are zero (this==0)
605     * then -1 is returned as result.
606     *
607     * <p><b>Implementation Note:</b> Usage of this method is not recommended as
608     * the current implementation is not efficient.
609     */
610    public int getLowestSetBit() {
611        prepareJavaRepresentation();
612        if (sign == 0) {
613            return -1;
614        }
615        // (sign != 0) implies that exists some non zero digit
616        int i = getFirstNonzeroDigit();
617        return ((i << 5) + Integer.numberOfTrailingZeros(digits[i]));
618    }
619
620    /**
621     * Returns the number of bits in the two's complement representation of
622     * {@code this} which differ from the sign bit. If {@code this} is negative,
623     * the result is equivalent to the number of bits set in the two's
624     * complement representation of {@code -this - 1}.
625     *
626     * <p>Use {@code bitLength(0)} to find the length of the binary value in
627     * bits.
628     *
629     * <p><b>Implementation Note:</b> Usage of this method is not recommended as
630     * the current implementation is not efficient.
631     */
632    public int bitCount() {
633        prepareJavaRepresentation();
634        return BitLevel.bitCount(this);
635    }
636
637    /**
638     * Returns a {@code BigInteger} whose value is {@code ~this}. The result
639     * of this operation is {@code -this-1}.
640     *
641     * <p><b>Implementation Note:</b> Usage of this method is not recommended as
642     * the current implementation is not efficient.
643     */
644    public BigInteger not() {
645        this.prepareJavaRepresentation();
646        return Logical.not(this);
647    }
648
649    /**
650     * Returns a {@code BigInteger} whose value is {@code this & value}.
651     *
652     * <p><b>Implementation Note:</b> Usage of this method is not recommended
653     * as the current implementation is not efficient.
654     *
655     * @param value value to be and'ed with {@code this}.
656     * @throws NullPointerException if {@code value == null}.
657     */
658    public BigInteger and(BigInteger value) {
659        this.prepareJavaRepresentation();
660        value.prepareJavaRepresentation();
661        return Logical.and(this, value);
662    }
663
664    /**
665     * Returns a {@code BigInteger} whose value is {@code this | value}.
666     *
667     * <p><b>Implementation Note:</b> Usage of this method is not recommended as
668     * the current implementation is not efficient.
669     *
670     * @param value value to be or'ed with {@code this}.
671     * @throws NullPointerException if {@code value == null}.
672     */
673    public BigInteger or(BigInteger value) {
674        this.prepareJavaRepresentation();
675        value.prepareJavaRepresentation();
676        return Logical.or(this, value);
677    }
678
679    /**
680     * Returns a {@code BigInteger} whose value is {@code this ^ value}.
681     *
682     * <p><b>Implementation Note:</b> Usage of this method is not recommended as
683     * the current implementation is not efficient.
684     *
685     * @param value value to be xor'ed with {@code this}
686     * @throws NullPointerException if {@code value == null}
687     */
688    public BigInteger xor(BigInteger value) {
689        this.prepareJavaRepresentation();
690        value.prepareJavaRepresentation();
691        return Logical.xor(this, value);
692    }
693
694    /**
695     * Returns a {@code BigInteger} whose value is {@code this & ~value}.
696     * Evaluating {@code x.andNot(value)} returns the same result as {@code
697     * x.and(value.not())}.
698     *
699     * <p><b>Implementation Note:</b> Usage of this method is not recommended
700     * as the current implementation is not efficient.
701     *
702     * @param value value to be not'ed and then and'ed with {@code this}.
703     * @throws NullPointerException if {@code value == null}.
704     */
705    public BigInteger andNot(BigInteger value) {
706        this.prepareJavaRepresentation();
707        value.prepareJavaRepresentation();
708        return Logical.andNot(this, value);
709    }
710
711    /**
712     * Returns this {@code BigInteger} as an int value. If {@code this} is too
713     * big to be represented as an int, then {@code this % (1 << 32)} is
714     * returned.
715     */
716    @Override
717    public int intValue() {
718        if (nativeIsValid && bigInt.twosCompFitsIntoBytes(4)) {
719            return (int) bigInt.longInt();
720        }
721        this.prepareJavaRepresentation();
722        return (sign * digits[0]);
723    }
724
725    /**
726     * Returns this {@code BigInteger} as a long value. If {@code this} is too
727     * big to be represented as a long, then {@code this % pow(2, 64)} is
728     * returned.
729     */
730    @Override
731    public long longValue() {
732        if (nativeIsValid && bigInt.twosCompFitsIntoBytes(8)) {
733            return bigInt.longInt();
734        }
735        prepareJavaRepresentation();
736        long value = numberLength > 1
737                ? ((long) digits[1]) << 32 | digits[0] & 0xFFFFFFFFL
738                : digits[0] & 0xFFFFFFFFL;
739        return sign * value;
740    }
741
742    /**
743     * Returns this {@code BigInteger} as a float. If {@code this} is too big to
744     * be represented as a float, then {@code Float.POSITIVE_INFINITY} or
745     * {@code Float.NEGATIVE_INFINITY} is returned. Note that not all integers
746     * in the range {@code [-Float.MAX_VALUE, Float.MAX_VALUE]} can be exactly
747     * represented as a float.
748     */
749    @Override
750    public float floatValue() {
751        return (float) doubleValue();
752    }
753
754    /**
755     * Returns this {@code BigInteger} as a double. If {@code this} is too big
756     * to be represented as a double, then {@code Double.POSITIVE_INFINITY} or
757     * {@code Double.NEGATIVE_INFINITY} is returned. Note that not all integers
758     * in the range {@code [-Double.MAX_VALUE, Double.MAX_VALUE]} can be exactly
759     * represented as a double.
760     */
761    @Override
762    public double doubleValue() {
763        return Conversion.bigInteger2Double(this);
764    }
765
766    /**
767     * Compares this {@code BigInteger} with {@code value}. Returns {@code -1}
768     * if {@code this < value}, {@code 0} if {@code this == value} and {@code 1}
769     * if {@code this > value}, .
770     *
771     * @param value value to be compared with {@code this}.
772     * @throws NullPointerException if {@code value == null}.
773     */
774    public int compareTo(BigInteger value) {
775        return BigInt.cmp(getBigInt(), value.getBigInt());
776    }
777
778    /**
779     * Returns the minimum of this {@code BigInteger} and {@code value}.
780     *
781     * @param value value to be used to compute the minimum with {@code this}.
782     * @throws NullPointerException if {@code value == null}.
783     */
784    public BigInteger min(BigInteger value) {
785        return this.compareTo(value) == -1 ? this : value;
786    }
787
788    /**
789     * Returns the maximum of this {@code BigInteger} and {@code value}.
790     *
791     * @param value value to be used to compute the maximum with {@code this}
792     * @throws NullPointerException if {@code value == null}
793     */
794    public BigInteger max(BigInteger value) {
795        return this.compareTo(value) == 1 ? this : value;
796    }
797
798    @Override
799    public int hashCode() {
800        if (hashCode != 0) {
801            return hashCode;
802        }
803        prepareJavaRepresentation();
804        for (int digit : digits) {
805            hashCode = hashCode * 33 + digit;
806        }
807        hashCode = hashCode * sign;
808        return hashCode;
809    }
810
811    @Override
812    public boolean equals(Object x) {
813        if (this == x) {
814            return true;
815        }
816        if (x instanceof BigInteger) {
817            return this.compareTo((BigInteger) x) == 0;
818        }
819        return false;
820    }
821
822    /**
823     * Returns a string representation of this {@code BigInteger} in decimal
824     * form.
825     */
826    @Override
827    public String toString() {
828        return getBigInt().decString();
829    }
830
831    /**
832     * Returns a string containing a string representation of this {@code
833     * BigInteger} with base radix. If {@code radix < Character.MIN_RADIX} or
834     * {@code radix > Character.MAX_RADIX} then a decimal representation is
835     * returned. The characters of the string representation are generated with
836     * method {@code Character.forDigit}.
837     *
838     * @param radix base to be used for the string representation.
839     */
840    public String toString(int radix) {
841        if (radix == 10) {
842            return getBigInt().decString();
843        } else {
844            prepareJavaRepresentation();
845            return Conversion.bigInteger2String(this, radix);
846        }
847    }
848
849    /**
850     * Returns a {@code BigInteger} whose value is greatest common divisor
851     * of {@code this} and {@code value}. If {@code this == 0} and {@code
852     * value == 0} then zero is returned, otherwise the result is positive.
853     *
854     * @param value value with which the greatest common divisor is computed.
855     * @throws NullPointerException if {@code value == null}.
856     */
857    public BigInteger gcd(BigInteger value) {
858        return new BigInteger(BigInt.gcd(getBigInt(), value.getBigInt()));
859    }
860
861    /**
862     * Returns a {@code BigInteger} whose value is {@code this * value}.
863     *
864     * @throws NullPointerException if {@code value == null}.
865     */
866    public BigInteger multiply(BigInteger value) {
867        return new BigInteger(BigInt.product(getBigInt(), value.getBigInt()));
868    }
869
870    /**
871     * Returns a {@code BigInteger} whose value is {@code pow(this, exp)}.
872     *
873     * @throws ArithmeticException if {@code exp < 0}.
874     */
875    public BigInteger pow(int exp) {
876        if (exp < 0) {
877            throw new ArithmeticException("exp < 0: " + exp);
878        }
879        return new BigInteger(BigInt.exp(getBigInt(), exp));
880    }
881
882    /**
883     * Returns a two element {@code BigInteger} array containing
884     * {@code this / divisor} at index 0 and {@code this % divisor} at index 1.
885     *
886     * @param divisor value by which {@code this} is divided.
887     * @throws NullPointerException if {@code divisor == null}.
888     * @throws ArithmeticException if {@code divisor == 0}.
889     * @see #divide
890     * @see #remainder
891     */
892    public BigInteger[] divideAndRemainder(BigInteger divisor) {
893        BigInt divisorBigInt = divisor.getBigInt();
894        BigInt quotient = new BigInt();
895        BigInt remainder = new BigInt();
896        BigInt.division(getBigInt(), divisorBigInt, quotient, remainder);
897        return new BigInteger[] {new BigInteger(quotient), new BigInteger(remainder) };
898    }
899
900    /**
901     * Returns a {@code BigInteger} whose value is {@code this / divisor}.
902     *
903     * @param divisor value by which {@code this} is divided.
904     * @return {@code this / divisor}.
905     * @throws NullPointerException if {@code divisor == null}.
906     * @throws ArithmeticException if {@code divisor == 0}.
907     */
908    public BigInteger divide(BigInteger divisor) {
909        BigInt quotient = new BigInt();
910        BigInt.division(getBigInt(), divisor.getBigInt(), quotient, null);
911        return new BigInteger(quotient);
912    }
913
914    /**
915     * Returns a {@code BigInteger} whose value is {@code this % divisor}.
916     * Regarding signs this methods has the same behavior as the % operator on
917     * ints: the sign of the remainder is the same as the sign of this.
918     *
919     * @param divisor value by which {@code this} is divided.
920     * @throws NullPointerException if {@code divisor == null}.
921     * @throws ArithmeticException if {@code divisor == 0}.
922     */
923    public BigInteger remainder(BigInteger divisor) {
924        BigInt remainder = new BigInt();
925        BigInt.division(getBigInt(), divisor.getBigInt(), null, remainder);
926        return new BigInteger(remainder);
927    }
928
929    /**
930     * Returns a {@code BigInteger} whose value is {@code 1/this mod m}. The
931     * modulus {@code m} must be positive. The result is guaranteed to be in the
932     * interval {@code [0, m)} (0 inclusive, m exclusive). If {@code this} is
933     * not relatively prime to m, then an exception is thrown.
934     *
935     * @param m the modulus.
936     * @throws NullPointerException if {@code m == null}
937     * @throws ArithmeticException if {@code m < 0 or} if {@code this} is not
938     *     relatively prime to {@code m}
939     */
940    public BigInteger modInverse(BigInteger m) {
941        if (m.signum() <= 0) {
942            throw new ArithmeticException("modulus not positive");
943        }
944        return new BigInteger(BigInt.modInverse(getBigInt(), m.getBigInt()));
945    }
946
947    /**
948     * Returns a {@code BigInteger} whose value is {@code
949     * pow(this, exponent) mod m}. The modulus {@code m} must be positive. The
950     * result is guaranteed to be in the interval {@code [0, m)} (0 inclusive,
951     * m exclusive). If the exponent is negative, then {@code
952     * pow(this.modInverse(m), -exponent) mod m} is computed. The inverse of
953     * this only exists if {@code this} is relatively prime to m, otherwise an
954     * exception is thrown.
955     *
956     * @param exponent the exponent.
957     * @param m the modulus.
958     * @throws NullPointerException if {@code m == null} or {@code exponent ==
959     *     null}.
960     * @throws ArithmeticException if {@code m < 0} or if {@code exponent<0} and
961     *     this is not relatively prime to {@code m}.
962     */
963    public BigInteger modPow(BigInteger exponent, BigInteger m) {
964        if (m.signum() <= 0) {
965            throw new ArithmeticException("m.signum() <= 0");
966        }
967        BigInteger base = exponent.signum() < 0 ? modInverse(m) : this;
968        return new BigInteger(BigInt.modExp(base.getBigInt(), exponent.getBigInt(), m.getBigInt()));
969    }
970
971    /**
972     * Returns a {@code BigInteger} whose value is {@code this mod m}. The
973     * modulus {@code m} must be positive. The result is guaranteed to be in the
974     * interval {@code [0, m)} (0 inclusive, m exclusive). The behavior of this
975     * function is not equivalent to the behavior of the % operator defined for
976     * the built-in {@code int}'s.
977     *
978     * @param m the modulus.
979     * @return {@code this mod m}.
980     * @throws NullPointerException if {@code m == null}.
981     * @throws ArithmeticException if {@code m < 0}.
982     */
983    public BigInteger mod(BigInteger m) {
984        if (m.signum() <= 0) {
985            throw new ArithmeticException("m.signum() <= 0");
986        }
987        return new BigInteger(BigInt.modulus(getBigInt(), m.getBigInt()));
988    }
989
990    /**
991     * Tests whether this {@code BigInteger} is probably prime. If {@code true}
992     * is returned, then this is prime with a probability beyond
993     * {@code 1 - 1/pow(2, certainty)}. If {@code false} is returned, then this
994     * is definitely composite. If the argument {@code certainty} <= 0, then
995     * this method returns true.
996     *
997     * @param certainty tolerated primality uncertainty.
998     * @return {@code true}, if {@code this} is probably prime, {@code false}
999     *     otherwise.
1000     */
1001    public boolean isProbablePrime(int certainty) {
1002        if (certainty <= 0) {
1003            return true;
1004        }
1005        return getBigInt().isPrime(certainty);
1006    }
1007
1008    /**
1009     * Returns the smallest integer x > {@code this} which is probably prime as
1010     * a {@code BigInteger} instance. The probability that the returned {@code
1011     * BigInteger} is prime is beyond {@code 1 - 1/pow(2, 80)}.
1012     *
1013     * @return smallest integer > {@code this} which is probably prime.
1014     * @throws ArithmeticException if {@code this < 0}.
1015     */
1016    public BigInteger nextProbablePrime() {
1017        if (sign < 0) {
1018            throw new ArithmeticException("sign < 0");
1019        }
1020        return Primality.nextProbablePrime(this);
1021    }
1022
1023    /**
1024     * Returns a random positive {@code BigInteger} instance in the range {@code
1025     * [0, pow(2, bitLength)-1]} which is probably prime. The probability that
1026     * the returned {@code BigInteger} is prime is beyond {@code
1027     * 1 - 1/pow(2, 80)}.
1028     *
1029     * <p><b>Implementation Note:</b> Currently {@code random} is ignored.
1030     *
1031     * @param bitLength length of the new {@code BigInteger} in bits.
1032     * @return probably prime random {@code BigInteger} instance.
1033     * @throws IllegalArgumentException if {@code bitLength < 2}.
1034     */
1035    public static BigInteger probablePrime(int bitLength, Random unused) {
1036        return new BigInteger(bitLength, 100, unused);
1037    }
1038
1039    /* Private Methods */
1040
1041    /**
1042     * Returns the two's complement representation of this BigInteger in a byte
1043     * array.
1044     *
1045     * @return two's complement representation of {@code this}
1046     */
1047    private byte[] twosComplement() {
1048        prepareJavaRepresentation();
1049        if (this.sign == 0) {
1050            return new byte[] { 0 };
1051        }
1052        BigInteger temp = this;
1053        int bitLen = bitLength();
1054        int iThis = getFirstNonzeroDigit();
1055        int bytesLen = (bitLen >> 3) + 1;
1056        /* Puts the little-endian int array representing the magnitude
1057         * of this BigInteger into the big-endian byte array. */
1058        byte[] bytes = new byte[bytesLen];
1059        int firstByteNumber = 0;
1060        int highBytes;
1061        int bytesInInteger = 4;
1062        int hB;
1063
1064        if (bytesLen - (numberLength << 2) == 1) {
1065            bytes[0] = (byte) ((sign < 0) ? -1 : 0);
1066            highBytes = 4;
1067            firstByteNumber++;
1068        } else {
1069            hB = bytesLen & 3;
1070            highBytes = (hB == 0) ? 4 : hB;
1071        }
1072
1073        int digitIndex = iThis;
1074        bytesLen -= iThis << 2;
1075
1076        if (sign < 0) {
1077            int digit = -temp.digits[digitIndex];
1078            digitIndex++;
1079            if (digitIndex == numberLength) {
1080                bytesInInteger = highBytes;
1081            }
1082            for (int i = 0; i < bytesInInteger; i++, digit >>= 8) {
1083                bytes[--bytesLen] = (byte) digit;
1084            }
1085            while (bytesLen > firstByteNumber) {
1086                digit = ~temp.digits[digitIndex];
1087                digitIndex++;
1088                if (digitIndex == numberLength) {
1089                    bytesInInteger = highBytes;
1090                }
1091                for (int i = 0; i < bytesInInteger; i++, digit >>= 8) {
1092                    bytes[--bytesLen] = (byte) digit;
1093                }
1094            }
1095        } else {
1096            while (bytesLen > firstByteNumber) {
1097                int digit = temp.digits[digitIndex];
1098                digitIndex++;
1099                if (digitIndex == numberLength) {
1100                    bytesInInteger = highBytes;
1101                }
1102                for (int i = 0; i < bytesInInteger; i++, digit >>= 8) {
1103                    bytes[--bytesLen] = (byte) digit;
1104                }
1105            }
1106        }
1107        return bytes;
1108    }
1109
1110
1111    static int multiplyByInt(int[] res, int[] a, int aSize, int factor) {
1112        long carry = 0;
1113
1114        for (int i = 0; i < aSize; i++) {
1115            carry += (a[i] & 0xFFFFFFFFL) * (factor & 0xFFFFFFFFL);
1116            res[i] = (int) carry;
1117            carry >>>= 32;
1118        }
1119        return (int) carry;
1120    }
1121
1122    static int inplaceAdd(int[] a, int aSize, int addend) {
1123        long carry = addend & 0xFFFFFFFFL;
1124
1125        for (int i = 0; (carry != 0) && (i < aSize); i++) {
1126            carry += a[i] & 0xFFFFFFFFL;
1127            a[i] = (int) carry;
1128            carry >>= 32;
1129        }
1130        return (int) carry;
1131    }
1132
1133    /** @see BigInteger#BigInteger(String, int) */
1134    private static void parseFromString(BigInteger bi, String value, int radix) {
1135        int stringLength = value.length();
1136        int endChar = stringLength;
1137
1138        int sign;
1139        int startChar;
1140        if (value.charAt(0) == '-') {
1141            sign = -1;
1142            startChar = 1;
1143            stringLength--;
1144        } else {
1145            sign = 1;
1146            startChar = 0;
1147        }
1148
1149        /*
1150         * We use the following algorithm: split a string into portions of n
1151         * characters and convert each portion to an integer according to the
1152         * radix. Then convert an pow(radix, n) based number to binary using the
1153         * multiplication method. See D. Knuth, The Art of Computer Programming,
1154         * vol. 2.
1155         */
1156
1157        int charsPerInt = Conversion.digitFitInInt[radix];
1158        int bigRadixDigitsLength = stringLength / charsPerInt;
1159        int topChars = stringLength % charsPerInt;
1160
1161        if (topChars != 0) {
1162            bigRadixDigitsLength++;
1163        }
1164        int[] digits = new int[bigRadixDigitsLength];
1165        // Get the maximal power of radix that fits in int
1166        int bigRadix = Conversion.bigRadices[radix - 2];
1167        // Parse an input string and accumulate the BigInteger's magnitude
1168        int digitIndex = 0; // index of digits array
1169        int substrEnd = startChar + ((topChars == 0) ? charsPerInt : topChars);
1170
1171        for (int substrStart = startChar; substrStart < endChar;
1172                substrStart = substrEnd, substrEnd = substrStart + charsPerInt) {
1173            int bigRadixDigit = Integer.parseInt(value.substring(substrStart, substrEnd), radix);
1174            int newDigit = multiplyByInt(digits, digits, digitIndex, bigRadix);
1175            newDigit += inplaceAdd(digits, digitIndex, bigRadixDigit);
1176            digits[digitIndex++] = newDigit;
1177        }
1178        int numberLength = digitIndex;
1179        bi.setJavaRepresentation(sign, numberLength, digits);
1180    }
1181
1182    int getFirstNonzeroDigit() {
1183        if (firstNonzeroDigit == -2) {
1184            int i;
1185            if (this.sign == 0) {
1186                i = -1;
1187            } else {
1188                for (i = 0; digits[i] == 0; i++) {
1189                    ;
1190                }
1191            }
1192            firstNonzeroDigit = i;
1193        }
1194        return firstNonzeroDigit;
1195    }
1196
1197    /**
1198     * Returns a copy of the current instance to achieve immutability
1199     */
1200    BigInteger copy() {
1201        prepareJavaRepresentation();
1202        int[] copyDigits = new int[numberLength];
1203        System.arraycopy(digits, 0, copyDigits, 0, numberLength);
1204        return new BigInteger(sign, numberLength, copyDigits);
1205    }
1206
1207    /**
1208     * Assigns all transient fields upon deserialization of a {@code BigInteger}
1209     * instance.
1210     */
1211    private void readObject(ObjectInputStream in)
1212            throws IOException, ClassNotFoundException {
1213        in.defaultReadObject();
1214        BigInt bigInt = new BigInt();
1215        bigInt.putBigEndian(magnitude, signum < 0);
1216        setBigInt(bigInt);
1217    }
1218
1219    /**
1220     * Prepares this {@code BigInteger} for serialization, i.e. the
1221     * non-transient fields {@code signum} and {@code magnitude} are assigned.
1222     */
1223    private void writeObject(ObjectOutputStream out) throws IOException {
1224        BigInt bigInt = getBigInt();
1225        signum = bigInt.sign();
1226        magnitude = bigInt.bigEndianMagnitude();
1227        out.defaultWriteObject();
1228    }
1229}
1230