• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 /*
27  * Portions Copyright (c) 1995  Colin Plumb.  All rights reserved.
28  */
29 
30 package java.math;
31 
32 import java.io.IOException;
33 import java.io.InvalidObjectException;
34 import java.io.ObjectInputStream;
35 import java.io.ObjectOutputStream;
36 import java.io.ObjectStreamField;
37 import java.io.ObjectStreamException;
38 import java.util.Arrays;
39 import java.util.Objects;
40 import java.util.Random;
41 import java.util.concurrent.ThreadLocalRandom;
42 
43 import jdk.internal.math.DoubleConsts;
44 import jdk.internal.math.FloatConsts;
45 import jdk.internal.vm.annotation.IntrinsicCandidate;
46 
47 import libcore.math.NativeBN;
48 /**
49  * Immutable arbitrary-precision integers.  All operations behave as if
50  * BigIntegers were represented in two's-complement notation (like Java's
51  * primitive integer types).  BigInteger provides analogues to all of Java's
52  * primitive integer operators, and all relevant methods from java.lang.Math.
53  * Additionally, BigInteger provides operations for modular arithmetic, GCD
54  * calculation, primality testing, prime generation, bit manipulation,
55  * and a few other miscellaneous operations.
56  *
57  * <p>Semantics of arithmetic operations exactly mimic those of Java's integer
58  * arithmetic operators, as defined in <i>The Java Language Specification</i>.
59  * For example, division by zero throws an {@code ArithmeticException}, and
60  * division of a negative by a positive yields a negative (or zero) remainder.
61  *
62  * <p>Semantics of shift operations extend those of Java's shift operators
63  * to allow for negative shift distances.  A right-shift with a negative
64  * shift distance results in a left shift, and vice-versa.  The unsigned
65  * right shift operator ({@code >>>}) is omitted since this operation
66  * only makes sense for a fixed sized word and not for a
67  * representation conceptually having an infinite number of leading
68  * virtual sign bits.
69  *
70  * <p>Semantics of bitwise logical operations exactly mimic those of Java's
71  * bitwise integer operators.  The binary operators ({@code and},
72  * {@code or}, {@code xor}) implicitly perform sign extension on the shorter
73  * of the two operands prior to performing the operation.
74  *
75  * <p>Comparison operations perform signed integer comparisons, analogous to
76  * those performed by Java's relational and equality operators.
77  *
78  * <p>Modular arithmetic operations are provided to compute residues, perform
79  * exponentiation, and compute multiplicative inverses.  These methods always
80  * return a non-negative result, between {@code 0} and {@code (modulus - 1)},
81  * inclusive.
82  *
83  * <p>Bit operations operate on a single bit of the two's-complement
84  * representation of their operand.  If necessary, the operand is sign-extended
85  * so that it contains the designated bit.  None of the single-bit
86  * operations can produce a BigInteger with a different sign from the
87  * BigInteger being operated on, as they affect only a single bit, and the
88  * arbitrarily large abstraction provided by this class ensures that conceptually
89  * there are infinitely many "virtual sign bits" preceding each BigInteger.
90  *
91  * <p>For the sake of brevity and clarity, pseudo-code is used throughout the
92  * descriptions of BigInteger methods.  The pseudo-code expression
93  * {@code (i + j)} is shorthand for "a BigInteger whose value is
94  * that of the BigInteger {@code i} plus that of the BigInteger {@code j}."
95  * The pseudo-code expression {@code (i == j)} is shorthand for
96  * "{@code true} if and only if the BigInteger {@code i} represents the same
97  * value as the BigInteger {@code j}."  Other pseudo-code expressions are
98  * interpreted similarly.
99  *
100  * <p>All methods and constructors in this class throw
101  * {@code NullPointerException} when passed
102  * a null object reference for any input parameter.
103  *
104  * BigInteger must support values in the range
105  * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
106  * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive)
107  * and may support values outside of that range.
108  *
109  * An {@code ArithmeticException} is thrown when a BigInteger
110  * constructor or method would generate a value outside of the
111  * supported range.
112  *
113  * The range of probable prime values is limited and may be less than
114  * the full supported positive range of {@code BigInteger}.
115  * The range must be at least 1 to 2<sup>500000000</sup>.
116  *
117  * @implNote
118  * In the reference implementation, BigInteger constructors and
119  * operations throw {@code ArithmeticException} when the result is out
120  * of the supported range of
121  * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
122  * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive).
123  *
124  * @see     BigDecimal
125  * @jls     4.2.2 Integer Operations
126  * @author  Josh Bloch
127  * @author  Michael McCloskey
128  * @author  Alan Eliasen
129  * @author  Timothy Buktu
130  * @since 1.1
131  */
132 
133 public class BigInteger extends Number implements Comparable<BigInteger> {
134     /**
135      * The signum of this BigInteger: -1 for negative, 0 for zero, or
136      * 1 for positive.  Note that the BigInteger zero <em>must</em> have
137      * a signum of 0.  This is necessary to ensures that there is exactly one
138      * representation for each BigInteger value.
139      */
140     final int signum;
141 
142     /**
143      * The magnitude of this BigInteger, in <i>big-endian</i> order: the
144      * zeroth element of this array is the most-significant int of the
145      * magnitude.  The magnitude must be "minimal" in that the most-significant
146      * int ({@code mag[0]}) must be non-zero.  This is necessary to
147      * ensure that there is exactly one representation for each BigInteger
148      * value.  Note that this implies that the BigInteger zero has a
149      * zero-length mag array.
150      */
151     final int[] mag;
152 
153     // The following fields are stable variables. A stable variable's value
154     // changes at most once from the default zero value to a non-zero stable
155     // value. A stable value is calculated lazily on demand.
156 
157     /**
158      * One plus the bitCount of this BigInteger. This is a stable variable.
159      *
160      * @see #bitCount
161      */
162     private int bitCountPlusOne;
163 
164     /**
165      * One plus the bitLength of this BigInteger. This is a stable variable.
166      * (either value is acceptable).
167      *
168      * @see #bitLength()
169      */
170     private int bitLengthPlusOne;
171 
172     /**
173      * Two plus the lowest set bit of this BigInteger. This is a stable variable.
174      *
175      * @see #getLowestSetBit
176      */
177     private int lowestSetBitPlusTwo;
178 
179     /**
180      * Two plus the index of the lowest-order int in the magnitude of this
181      * BigInteger that contains a nonzero int. This is a stable variable. The
182      * least significant int has int-number 0, the next int in order of
183      * increasing significance has int-number 1, and so forth.
184      *
185      * <p>Note: never used for a BigInteger with a magnitude of zero.
186      *
187      * @see #firstNonzeroIntNum()
188      */
189     private int firstNonzeroIntNumPlusTwo;
190 
191     /**
192      * This mask is used to obtain the value of an int as if it were unsigned.
193      */
194     static final long LONG_MASK = 0xffffffffL;
195 
196     /**
197      * This constant limits {@code mag.length} of BigIntegers to the supported
198      * range.
199      */
200     private static final int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26)
201 
202     /**
203      * Bit lengths larger than this constant can cause overflow in searchLen
204      * calculation and in BitSieve.singleSearch method.
205      */
206     private static final  int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;
207 
208     /**
209      * The threshold value for using Karatsuba multiplication.  If the number
210      * of ints in both mag arrays are greater than this number, then
211      * Karatsuba multiplication will be used.   This value is found
212      * experimentally to work well.
213      */
214     private static final int KARATSUBA_THRESHOLD = 80;
215 
216     /**
217      * The threshold value for using 3-way Toom-Cook multiplication.
218      * If the number of ints in each mag array is greater than the
219      * Karatsuba threshold, and the number of ints in at least one of
220      * the mag arrays is greater than this threshold, then Toom-Cook
221      * multiplication will be used.
222      */
223     private static final int TOOM_COOK_THRESHOLD = 240;
224 
225     /**
226      * The threshold value for using Karatsuba squaring.  If the number
227      * of ints in the number are larger than this value,
228      * Karatsuba squaring will be used.   This value is found
229      * experimentally to work well.
230      */
231     private static final int KARATSUBA_SQUARE_THRESHOLD = 128;
232 
233     /**
234      * The threshold value for using Toom-Cook squaring.  If the number
235      * of ints in the number are larger than this value,
236      * Toom-Cook squaring will be used.   This value is found
237      * experimentally to work well.
238      */
239     private static final int TOOM_COOK_SQUARE_THRESHOLD = 216;
240 
241     /**
242      * The threshold value for using Burnikel-Ziegler division.  If the number
243      * of ints in the divisor are larger than this value, Burnikel-Ziegler
244      * division may be used.  This value is found experimentally to work well.
245      */
246     static final int BURNIKEL_ZIEGLER_THRESHOLD = 80;
247 
248     /**
249      * The offset value for using Burnikel-Ziegler division.  If the number
250      * of ints in the divisor exceeds the Burnikel-Ziegler threshold, and the
251      * number of ints in the dividend is greater than the number of ints in the
252      * divisor plus this value, Burnikel-Ziegler division will be used.  This
253      * value is found experimentally to work well.
254      */
255     static final int BURNIKEL_ZIEGLER_OFFSET = 40;
256 
257     /**
258      * The threshold value for using Schoenhage recursive base conversion. If
259      * the number of ints in the number are larger than this value,
260      * the Schoenhage algorithm will be used.  In practice, it appears that the
261      * Schoenhage routine is faster for any threshold down to 2, and is
262      * relatively flat for thresholds between 2-25, so this choice may be
263      * varied within this range for very small effect.
264      */
265     private static final int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20;
266 
267     /**
268      * The threshold value for using squaring code to perform multiplication
269      * of a {@code BigInteger} instance by itself.  If the number of ints in
270      * the number are larger than this value, {@code multiply(this)} will
271      * return {@code square()}.
272      */
273     private static final int MULTIPLY_SQUARE_THRESHOLD = 20;
274 
275     /**
276      * The threshold for using an intrinsic version of
277      * implMontgomeryXXX to perform Montgomery multiplication.  If the
278      * number of ints in the number is more than this value we do not
279      * use the intrinsic.
280      */
281     private static final int MONTGOMERY_INTRINSIC_THRESHOLD = 512;
282 
283 
284     // Constructors
285 
286     /**
287      * Translates a byte sub-array containing the two's-complement binary
288      * representation of a BigInteger into a BigInteger.  The sub-array is
289      * specified via an offset into the array and a length.  The sub-array is
290      * assumed to be in <i>big-endian</i> byte-order: the most significant
291      * byte is the element at index {@code off}.  The {@code val} array is
292      * assumed to be unchanged for the duration of the constructor call.
293      *
294      * An {@code IndexOutOfBoundsException} is thrown if the length of the array
295      * {@code val} is non-zero and either {@code off} is negative, {@code len}
296      * is negative, or {@code off+len} is greater than the length of
297      * {@code val}.
298      *
299      * @param  val byte array containing a sub-array which is the big-endian
300      *         two's-complement binary representation of a BigInteger.
301      * @param  off the start offset of the binary representation.
302      * @param  len the number of bytes to use.
303      * @throws NumberFormatException {@code val} is zero bytes long.
304      * @throws IndexOutOfBoundsException if the provided array offset and
305      *         length would cause an index into the byte array to be
306      *         negative or greater than or equal to the array length.
307      * @since 9
308      */
BigInteger(byte[] val, int off, int len)309     public BigInteger(byte[] val, int off, int len) {
310         if (val.length == 0) {
311             throw new NumberFormatException("Zero length BigInteger");
312         }
313         Objects.checkFromIndexSize(off, len, val.length);
314 
315         if (val[off] < 0) {
316             mag = makePositive(val, off, len);
317             signum = -1;
318         } else {
319             mag = stripLeadingZeroBytes(val, off, len);
320             signum = (mag.length == 0 ? 0 : 1);
321         }
322         if (mag.length >= MAX_MAG_LENGTH) {
323             checkRange();
324         }
325     }
326 
327     /**
328      * Translates a byte array containing the two's-complement binary
329      * representation of a BigInteger into a BigInteger.  The input array is
330      * assumed to be in <i>big-endian</i> byte-order: the most significant
331      * byte is in the zeroth element.  The {@code val} array is assumed to be
332      * unchanged for the duration of the constructor call.
333      *
334      * @param  val big-endian two's-complement binary representation of a
335      *         BigInteger.
336      * @throws NumberFormatException {@code val} is zero bytes long.
337      */
BigInteger(byte[] val)338     public BigInteger(byte[] val) {
339         this(val, 0, val.length);
340     }
341 
342     /**
343      * This private constructor translates an int array containing the
344      * two's-complement binary representation of a BigInteger into a
345      * BigInteger. The input array is assumed to be in <i>big-endian</i>
346      * int-order: the most significant int is in the zeroth element.  The
347      * {@code val} array is assumed to be unchanged for the duration of
348      * the constructor call.
349      */
BigInteger(int[] val)350     private BigInteger(int[] val) {
351         if (val.length == 0)
352             throw new NumberFormatException("Zero length BigInteger");
353 
354         if (val[0] < 0) {
355             mag = makePositive(val);
356             signum = -1;
357         } else {
358             mag = trustedStripLeadingZeroInts(val);
359             signum = (mag.length == 0 ? 0 : 1);
360         }
361         if (mag.length >= MAX_MAG_LENGTH) {
362             checkRange();
363         }
364     }
365 
366     /**
367      * Translates the sign-magnitude representation of a BigInteger into a
368      * BigInteger.  The sign is represented as an integer signum value: -1 for
369      * negative, 0 for zero, or 1 for positive.  The magnitude is a sub-array of
370      * a byte array in <i>big-endian</i> byte-order: the most significant byte
371      * is the element at index {@code off}.  A zero value of the length
372      * {@code len} is permissible, and will result in a BigInteger value of 0,
373      * whether signum is -1, 0 or 1.  The {@code magnitude} array is assumed to
374      * be unchanged for the duration of the constructor call.
375      *
376      * An {@code IndexOutOfBoundsException} is thrown if the length of the array
377      * {@code magnitude} is non-zero and either {@code off} is negative,
378      * {@code len} is negative, or {@code off+len} is greater than the length of
379      * {@code magnitude}.
380      *
381      * @param  signum signum of the number (-1 for negative, 0 for zero, 1
382      *         for positive).
383      * @param  magnitude big-endian binary representation of the magnitude of
384      *         the number.
385      * @param  off the start offset of the binary representation.
386      * @param  len the number of bytes to use.
387      * @throws NumberFormatException {@code signum} is not one of the three
388      *         legal values (-1, 0, and 1), or {@code signum} is 0 and
389      *         {@code magnitude} contains one or more non-zero bytes.
390      * @throws IndexOutOfBoundsException if the provided array offset and
391      *         length would cause an index into the byte array to be
392      *         negative or greater than or equal to the array length.
393      * @since 9
394      */
BigInteger(int signum, byte[] magnitude, int off, int len)395     public BigInteger(int signum, byte[] magnitude, int off, int len) {
396         if (signum < -1 || signum > 1) {
397             throw(new NumberFormatException("Invalid signum value"));
398         }
399         Objects.checkFromIndexSize(off, len, magnitude.length);
400 
401         // stripLeadingZeroBytes() returns a zero length array if len == 0
402         this.mag = stripLeadingZeroBytes(magnitude, off, len);
403 
404         if (this.mag.length == 0) {
405             this.signum = 0;
406         } else {
407             if (signum == 0)
408                 throw(new NumberFormatException("signum-magnitude mismatch"));
409             this.signum = signum;
410         }
411         if (mag.length >= MAX_MAG_LENGTH) {
412             checkRange();
413         }
414     }
415 
416     /**
417      * Translates the sign-magnitude representation of a BigInteger into a
418      * BigInteger.  The sign is represented as an integer signum value: -1 for
419      * negative, 0 for zero, or 1 for positive.  The magnitude is a byte array
420      * in <i>big-endian</i> byte-order: the most significant byte is the
421      * zeroth element.  A zero-length magnitude array is permissible, and will
422      * result in a BigInteger value of 0, whether signum is -1, 0 or 1.  The
423      * {@code magnitude} array is assumed to be unchanged for the duration of
424      * the constructor call.
425      *
426      * @param  signum signum of the number (-1 for negative, 0 for zero, 1
427      *         for positive).
428      * @param  magnitude big-endian binary representation of the magnitude of
429      *         the number.
430      * @throws NumberFormatException {@code signum} is not one of the three
431      *         legal values (-1, 0, and 1), or {@code signum} is 0 and
432      *         {@code magnitude} contains one or more non-zero bytes.
433      */
BigInteger(int signum, byte[] magnitude)434     public BigInteger(int signum, byte[] magnitude) {
435          this(signum, magnitude, 0, magnitude.length);
436     }
437 
438     /**
439      * A constructor for internal use that translates the sign-magnitude
440      * representation of a BigInteger into a BigInteger. It checks the
441      * arguments and copies the magnitude so this constructor would be
442      * safe for external use.  The {@code magnitude} array is assumed to be
443      * unchanged for the duration of the constructor call.
444      */
BigInteger(int signum, int[] magnitude)445     private BigInteger(int signum, int[] magnitude) {
446         this.mag = stripLeadingZeroInts(magnitude);
447 
448         if (signum < -1 || signum > 1)
449             throw(new NumberFormatException("Invalid signum value"));
450 
451         if (this.mag.length == 0) {
452             this.signum = 0;
453         } else {
454             if (signum == 0)
455                 throw(new NumberFormatException("signum-magnitude mismatch"));
456             this.signum = signum;
457         }
458         if (mag.length >= MAX_MAG_LENGTH) {
459             checkRange();
460         }
461     }
462 
463     /**
464      * Translates the String representation of a BigInteger in the
465      * specified radix into a BigInteger.  The String representation
466      * consists of an optional minus or plus sign followed by a
467      * sequence of one or more digits in the specified radix.  The
468      * character-to-digit mapping is provided by {@link
469      * Character#digit(char, int) Character.digit}.  The String may
470      * not contain any extraneous characters (whitespace, for
471      * example).
472      *
473      * @param val String representation of BigInteger.
474      * @param radix radix to be used in interpreting {@code val}.
475      * @throws NumberFormatException {@code val} is not a valid representation
476      *         of a BigInteger in the specified radix, or {@code radix} is
477      *         outside the range from {@link Character#MIN_RADIX} to
478      *         {@link Character#MAX_RADIX}, inclusive.
479      */
BigInteger(String val, int radix)480     public BigInteger(String val, int radix) {
481         int cursor = 0, numDigits;
482         final int len = val.length();
483 
484         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
485             throw new NumberFormatException("Radix out of range");
486         if (len == 0)
487             throw new NumberFormatException("Zero length BigInteger");
488 
489         // Check for at most one leading sign
490         int sign = 1;
491         int index1 = val.lastIndexOf('-');
492         int index2 = val.lastIndexOf('+');
493         if (index1 >= 0) {
494             if (index1 != 0 || index2 >= 0) {
495                 throw new NumberFormatException("Illegal embedded sign character");
496             }
497             sign = -1;
498             cursor = 1;
499         } else if (index2 >= 0) {
500             if (index2 != 0) {
501                 throw new NumberFormatException("Illegal embedded sign character");
502             }
503             cursor = 1;
504         }
505         if (cursor == len)
506             throw new NumberFormatException("Zero length BigInteger");
507 
508         // Skip leading zeros and compute number of digits in magnitude
509         while (cursor < len &&
510                Character.digit(val.charAt(cursor), radix) == 0) {
511             cursor++;
512         }
513 
514         if (cursor == len) {
515             signum = 0;
516             mag = ZERO.mag;
517             return;
518         }
519 
520         numDigits = len - cursor;
521         signum = sign;
522 
523         // Pre-allocate array of expected size. May be too large but can
524         // never be too small. Typically exact.
525         long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1;
526         if (numBits + 31 >= (1L << 32)) {
527             reportOverflow();
528         }
529         int numWords = (int) (numBits + 31) >>> 5;
530         int[] magnitude = new int[numWords];
531 
532         // Process first (potentially short) digit group
533         int firstGroupLen = numDigits % digitsPerInt[radix];
534         if (firstGroupLen == 0)
535             firstGroupLen = digitsPerInt[radix];
536         String group = val.substring(cursor, cursor += firstGroupLen);
537         magnitude[numWords - 1] = Integer.parseInt(group, radix);
538         if (magnitude[numWords - 1] < 0)
539             throw new NumberFormatException("Illegal digit");
540 
541         // Process remaining digit groups
542         int superRadix = intRadix[radix];
543         int groupVal = 0;
544         while (cursor < len) {
545             group = val.substring(cursor, cursor += digitsPerInt[radix]);
546             groupVal = Integer.parseInt(group, radix);
547             if (groupVal < 0)
548                 throw new NumberFormatException("Illegal digit");
549             destructiveMulAdd(magnitude, superRadix, groupVal);
550         }
551         // Required for cases where the array was overallocated.
552         mag = trustedStripLeadingZeroInts(magnitude);
553         if (mag.length >= MAX_MAG_LENGTH) {
554             checkRange();
555         }
556     }
557 
558     /*
559      * Constructs a new BigInteger using a char array with radix=10.
560      * Sign is precalculated outside and not allowed in the val. The {@code val}
561      * array is assumed to be unchanged for the duration of the constructor
562      * call.
563      */
BigInteger(char[] val, int sign, int len)564     BigInteger(char[] val, int sign, int len) {
565         int cursor = 0, numDigits;
566 
567         // Skip leading zeros and compute number of digits in magnitude
568         while (cursor < len && Character.digit(val[cursor], 10) == 0) {
569             cursor++;
570         }
571         if (cursor == len) {
572             signum = 0;
573             mag = ZERO.mag;
574             return;
575         }
576 
577         numDigits = len - cursor;
578         signum = sign;
579         // Pre-allocate array of expected size
580         int numWords;
581         if (len < 10) {
582             numWords = 1;
583         } else {
584             long numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1;
585             if (numBits + 31 >= (1L << 32)) {
586                 reportOverflow();
587             }
588             numWords = (int) (numBits + 31) >>> 5;
589         }
590         int[] magnitude = new int[numWords];
591 
592         // Process first (potentially short) digit group
593         int firstGroupLen = numDigits % digitsPerInt[10];
594         if (firstGroupLen == 0)
595             firstGroupLen = digitsPerInt[10];
596         magnitude[numWords - 1] = parseInt(val, cursor,  cursor += firstGroupLen);
597 
598         // Process remaining digit groups
599         while (cursor < len) {
600             int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
601             destructiveMulAdd(magnitude, intRadix[10], groupVal);
602         }
603         mag = trustedStripLeadingZeroInts(magnitude);
604         if (mag.length >= MAX_MAG_LENGTH) {
605             checkRange();
606         }
607     }
608 
609     // Create an integer with the digits between the two indexes
610     // Assumes start < end. The result may be negative, but it
611     // is to be treated as an unsigned value.
parseInt(char[] source, int start, int end)612     private int parseInt(char[] source, int start, int end) {
613         int result = Character.digit(source[start++], 10);
614         if (result == -1)
615             throw new NumberFormatException(new String(source));
616 
617         for (int index = start; index < end; index++) {
618             int nextVal = Character.digit(source[index], 10);
619             if (nextVal == -1)
620                 throw new NumberFormatException(new String(source));
621             result = 10*result + nextVal;
622         }
623 
624         return result;
625     }
626 
627     // bitsPerDigit in the given radix times 1024
628     // Rounded up to avoid underallocation.
629     private static long bitsPerDigit[] = { 0, 0,
630         1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
631         3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
632         4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
633                                            5253, 5295};
634 
635     // Multiply x array times word y in place, and add word z
destructiveMulAdd(int[] x, int y, int z)636     private static void destructiveMulAdd(int[] x, int y, int z) {
637         // Perform the multiplication word by word
638         long ylong = y & LONG_MASK;
639         long zlong = z & LONG_MASK;
640         int len = x.length;
641 
642         long product = 0;
643         long carry = 0;
644         for (int i = len-1; i >= 0; i--) {
645             product = ylong * (x[i] & LONG_MASK) + carry;
646             x[i] = (int)product;
647             carry = product >>> 32;
648         }
649 
650         // Perform the addition
651         long sum = (x[len-1] & LONG_MASK) + zlong;
652         x[len-1] = (int)sum;
653         carry = sum >>> 32;
654         for (int i = len-2; i >= 0; i--) {
655             sum = (x[i] & LONG_MASK) + carry;
656             x[i] = (int)sum;
657             carry = sum >>> 32;
658         }
659     }
660 
661     /**
662      * Translates the decimal String representation of a BigInteger
663      * into a BigInteger.  The String representation consists of an
664      * optional minus or plus sign followed by a sequence of one or
665      * more decimal digits.  The character-to-digit mapping is
666      * provided by {@link Character#digit(char, int)
667      * Character.digit}.  The String may not contain any extraneous
668      * characters (whitespace, for example).
669      *
670      * @param val decimal String representation of BigInteger.
671      * @throws NumberFormatException {@code val} is not a valid representation
672      *         of a BigInteger.
673      */
BigInteger(String val)674     public BigInteger(String val) {
675         this(val, 10);
676     }
677 
678     /**
679      * Constructs a randomly generated BigInteger, uniformly distributed over
680      * the range 0 to (2<sup>{@code numBits}</sup> - 1), inclusive.
681      * The uniformity of the distribution assumes that a fair source of random
682      * bits is provided in {@code rnd}.  Note that this constructor always
683      * constructs a non-negative BigInteger.
684      *
685      * @param  numBits maximum bitLength of the new BigInteger.
686      * @param  rnd source of randomness to be used in computing the new
687      *         BigInteger.
688      * @throws IllegalArgumentException {@code numBits} is negative.
689      * @see #bitLength()
690      */
BigInteger(int numBits, Random rnd)691     public BigInteger(int numBits, Random rnd) {
692         byte[] magnitude = randomBits(numBits, rnd);
693 
694         try {
695             // stripLeadingZeroBytes() returns a zero length array if len == 0
696             this.mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);
697 
698             if (this.mag.length == 0) {
699                 this.signum = 0;
700             } else {
701                 this.signum = 1;
702             }
703             if (mag.length >= MAX_MAG_LENGTH) {
704                 checkRange();
705             }
706         } finally {
707             Arrays.fill(magnitude, (byte)0);
708         }
709     }
710 
randomBits(int numBits, Random rnd)711     private static byte[] randomBits(int numBits, Random rnd) {
712         if (numBits < 0)
713             throw new IllegalArgumentException("numBits must be non-negative");
714         int numBytes = (int)(((long)numBits+7)/8); // avoid overflow
715         byte[] randomBits = new byte[numBytes];
716 
717         // Generate random bytes and mask out any excess bits
718         if (numBytes > 0) {
719             rnd.nextBytes(randomBits);
720             int excessBits = 8*numBytes - numBits;
721             randomBits[0] &= (1 << (8-excessBits)) - 1;
722         }
723         return randomBits;
724     }
725 
726     /**
727      * Constructs a randomly generated positive BigInteger that is probably
728      * prime, with the specified bitLength.
729      *
730      * @apiNote It is recommended that the {@link #probablePrime probablePrime}
731      * method be used in preference to this constructor unless there
732      * is a compelling need to specify a certainty.
733      *
734      * @param  bitLength bitLength of the returned BigInteger.
735      * @param  certainty a measure of the uncertainty that the caller is
736      *         willing to tolerate.  The probability that the new BigInteger
737      *         represents a prime number will exceed
738      *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
739      *         this constructor is proportional to the value of this parameter.
740      * @param  rnd source of random bits used to select candidates to be
741      *         tested for primality.
742      * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.
743      * @see    #bitLength()
744      */
BigInteger(int bitLength, int certainty, Random rnd)745     public BigInteger(int bitLength, int certainty, Random rnd) {
746         BigInteger prime;
747 
748         if (bitLength < 2)
749             throw new ArithmeticException("bitLength < 2");
750         prime = (bitLength < SMALL_PRIME_THRESHOLD
751                                 ? smallPrime(bitLength, certainty, rnd)
752                                 : largePrime(bitLength, certainty, rnd));
753         signum = 1;
754         mag = prime.mag;
755     }
756 
757     // Minimum size in bits that the requested prime number has
758     // before we use the large prime number generating algorithms.
759     // The cutoff of 95 was chosen empirically for best performance.
760     private static final int SMALL_PRIME_THRESHOLD = 95;
761 
762     // Certainty required to meet the spec of probablePrime
763     private static final int DEFAULT_PRIME_CERTAINTY = 100;
764 
765     /**
766      * Returns a positive BigInteger that is probably prime, with the
767      * specified bitLength. The probability that a BigInteger returned
768      * by this method is composite does not exceed 2<sup>-100</sup>.
769      *
770      * @param  bitLength bitLength of the returned BigInteger.
771      * @param  rnd source of random bits used to select candidates to be
772      *         tested for primality.
773      * @return a BigInteger of {@code bitLength} bits that is probably prime
774      * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.
775      * @see    #bitLength()
776      * @since 1.4
777      */
probablePrime(int bitLength, Random rnd)778     public static BigInteger probablePrime(int bitLength, Random rnd) {
779         if (bitLength < 2)
780             throw new ArithmeticException("bitLength < 2");
781 
782         return (bitLength < SMALL_PRIME_THRESHOLD ?
783                 smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
784                 largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
785     }
786 
787     /**
788      * Find a random number of the specified bitLength that is probably prime.
789      * This method is used for smaller primes, its performance degrades on
790      * larger bitlengths.
791      *
792      * This method assumes bitLength > 1.
793      */
smallPrime(int bitLength, int certainty, Random rnd)794     private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
795         int magLen = (bitLength + 31) >>> 5;
796         int temp[] = new int[magLen];
797         int highBit = 1 << ((bitLength+31) & 0x1f);  // High bit of high int
798         int highMask = (highBit << 1) - 1;  // Bits to keep in high int
799 
800         while (true) {
801             // Construct a candidate
802             for (int i=0; i < magLen; i++)
803                 temp[i] = rnd.nextInt();
804             temp[0] = (temp[0] & highMask) | highBit;  // Ensure exact length
805             if (bitLength > 2)
806                 temp[magLen-1] |= 1;  // Make odd if bitlen > 2
807 
808             BigInteger p = new BigInteger(temp, 1);
809 
810             // Do cheap "pre-test" if applicable
811             if (bitLength > 6) {
812                 long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
813                 if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
814                     (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
815                     (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
816                     continue; // Candidate is composite; try another
817             }
818 
819             // All candidates of bitLength 2 and 3 are prime by this point
820             if (bitLength < 4)
821                 return p;
822 
823             // Do expensive test if we survive pre-test (or it's inapplicable)
824             if (p.primeToCertainty(certainty, rnd))
825                 return p;
826         }
827     }
828 
829     private static final BigInteger SMALL_PRIME_PRODUCT
830                        = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
831 
832     /**
833      * Find a random number of the specified bitLength that is probably prime.
834      * This method is more appropriate for larger bitlengths since it uses
835      * a sieve to eliminate most composites before using a more expensive
836      * test.
837      */
largePrime(int bitLength, int certainty, Random rnd)838     private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
839         BigInteger p;
840         p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
841         p.mag[p.mag.length-1] &= 0xfffffffe;
842 
843         // Use a sieve length likely to contain the next prime number
844         int searchLen = getPrimeSearchLen(bitLength);
845         BitSieve searchSieve = new BitSieve(p, searchLen);
846         BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);
847 
848         while ((candidate == null) || (candidate.bitLength() != bitLength)) {
849             p = p.add(BigInteger.valueOf(2*searchLen));
850             if (p.bitLength() != bitLength)
851                 p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
852             p.mag[p.mag.length-1] &= 0xfffffffe;
853             searchSieve = new BitSieve(p, searchLen);
854             candidate = searchSieve.retrieve(p, certainty, rnd);
855         }
856         return candidate;
857     }
858 
859    /**
860     * Returns the first integer greater than this {@code BigInteger} that
861     * is probably prime.  The probability that the number returned by this
862     * method is composite does not exceed 2<sup>-100</sup>. This method will
863     * never skip over a prime when searching: if it returns {@code p}, there
864     * is no prime {@code q} such that {@code this < q < p}.
865     *
866     * @return the first integer greater than this {@code BigInteger} that
867     *         is probably prime.
868     * @throws ArithmeticException {@code this < 0} or {@code this} is too large.
869     * @since 1.5
870     */
nextProbablePrime()871     public BigInteger nextProbablePrime() {
872         if (this.signum < 0)
873             throw new ArithmeticException("start < 0: " + this);
874 
875         // Handle trivial cases
876         if ((this.signum == 0) || this.equals(ONE))
877             return TWO;
878 
879         BigInteger result = this.add(ONE);
880 
881         // Fastpath for small numbers
882         if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
883 
884             // Ensure an odd number
885             if (!result.testBit(0))
886                 result = result.add(ONE);
887 
888             while (true) {
889                 // Do cheap "pre-test" if applicable
890                 if (result.bitLength() > 6) {
891                     long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
892                     if ((r%3==0)  || (r%5==0)  || (r%7==0)  || (r%11==0) ||
893                         (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
894                         (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {
895                         result = result.add(TWO);
896                         continue; // Candidate is composite; try another
897                     }
898                 }
899 
900                 // All candidates of bitLength 2 and 3 are prime by this point
901                 if (result.bitLength() < 4)
902                     return result;
903 
904                 // The expensive test
905                 if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))
906                     return result;
907 
908                 result = result.add(TWO);
909             }
910         }
911 
912         // Start at previous even number
913         if (result.testBit(0))
914             result = result.subtract(ONE);
915 
916         // Looking for the next large prime
917         int searchLen = getPrimeSearchLen(result.bitLength());
918 
919         while (true) {
920            BitSieve searchSieve = new BitSieve(result, searchLen);
921            BigInteger candidate = searchSieve.retrieve(result,
922                                                  DEFAULT_PRIME_CERTAINTY, null);
923            if (candidate != null)
924                return candidate;
925            result = result.add(BigInteger.valueOf(2 * searchLen));
926         }
927     }
928 
getPrimeSearchLen(int bitLength)929     private static int getPrimeSearchLen(int bitLength) {
930         if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) {
931             throw new ArithmeticException("Prime search implementation restriction on bitLength");
932         }
933         return bitLength / 20 * 64;
934     }
935 
936     /**
937      * Returns {@code true} if this BigInteger is probably prime,
938      * {@code false} if it's definitely composite.
939      *
940      * This method assumes bitLength > 2.
941      *
942      * @param  certainty a measure of the uncertainty that the caller is
943      *         willing to tolerate: if the call returns {@code true}
944      *         the probability that this BigInteger is prime exceeds
945      *         {@code (1 - 1/2<sup>certainty</sup>)}.  The execution time of
946      *         this method is proportional to the value of this parameter.
947      * @return {@code true} if this BigInteger is probably prime,
948      *         {@code false} if it's definitely composite.
949      */
primeToCertainty(int certainty, Random random)950     boolean primeToCertainty(int certainty, Random random) {
951         int rounds = 0;
952         int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;
953 
954         // The relationship between the certainty and the number of rounds
955         // we perform is given in the draft standard ANSI X9.80, "PRIME
956         // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
957         int sizeInBits = this.bitLength();
958         if (sizeInBits < 100) {
959             rounds = 50;
960             rounds = n < rounds ? n : rounds;
961             return passesMillerRabin(rounds, random);
962         }
963 
964         if (sizeInBits < 256) {
965             rounds = 27;
966         } else if (sizeInBits < 512) {
967             rounds = 15;
968         } else if (sizeInBits < 768) {
969             rounds = 8;
970         } else if (sizeInBits < 1024) {
971             rounds = 4;
972         } else {
973             rounds = 2;
974         }
975         rounds = n < rounds ? n : rounds;
976 
977         return passesMillerRabin(rounds, random) && passesLucasLehmer();
978     }
979 
980     /**
981      * Returns true iff this BigInteger is a Lucas-Lehmer probable prime.
982      *
983      * The following assumptions are made:
984      * This BigInteger is a positive, odd number.
985      */
986     private boolean passesLucasLehmer() {
987         BigInteger thisPlusOne = this.add(ONE);
988 
989         // Step 1
990         int d = 5;
991         while (jacobiSymbol(d, this) != -1) {
992             // 5, -7, 9, -11, ...
993             d = (d < 0) ? Math.abs(d)+2 : -(d+2);
994         }
995 
996         // Step 2
997         BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);
998 
999         // Step 3
1000         return u.mod(this).equals(ZERO);
1001     }
1002 
1003     /**
1004      * Computes Jacobi(p,n).
1005      * Assumes n positive, odd, n>=3.
1006      */
1007     private static int jacobiSymbol(int p, BigInteger n) {
1008         if (p == 0)
1009             return 0;
1010 
1011         // Algorithm and comments adapted from Colin Plumb's C library.
1012         int j = 1;
1013         int u = n.mag[n.mag.length-1];
1014 
1015         // Make p positive
1016         if (p < 0) {
1017             p = -p;
1018             int n8 = u & 7;
1019             if ((n8 == 3) || (n8 == 7))
1020                 j = -j; // 3 (011) or 7 (111) mod 8
1021         }
1022 
1023         // Get rid of factors of 2 in p
1024         while ((p & 3) == 0)
1025             p >>= 2;
1026         if ((p & 1) == 0) {
1027             p >>= 1;
1028             if (((u ^ (u>>1)) & 2) != 0)
1029                 j = -j; // 3 (011) or 5 (101) mod 8
1030         }
1031         if (p == 1)
1032             return j;
1033         // Then, apply quadratic reciprocity
1034         if ((p & u & 2) != 0)   // p = u = 3 (mod 4)?
1035             j = -j;
1036         // And reduce u mod p
1037         u = n.mod(BigInteger.valueOf(p)).intValue();
1038 
1039         // Now compute Jacobi(u,p), u < p
1040         while (u != 0) {
1041             while ((u & 3) == 0)
1042                 u >>= 2;
1043             if ((u & 1) == 0) {
1044                 u >>= 1;
1045                 if (((p ^ (p>>1)) & 2) != 0)
1046                     j = -j;     // 3 (011) or 5 (101) mod 8
1047             }
1048             if (u == 1)
1049                 return j;
1050             // Now both u and p are odd, so use quadratic reciprocity
assert(u < p); int t = u; u = p; p = t; if ((u & p & 2) != 0) j = -j; u %= p; } return 0; } private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) { BigInteger d = BigInteger.valueOf(z); BigInteger u = ONE; BigInteger u2; BigInteger v = ONE; BigInteger v2; for (int i=k.bitLength()-2; i >= 0; i--)1051             assert (u < p);
1052             int t = u; u = p; p = t;
1053             if ((u & p & 2) != 0) // u = p = 3 (mod 4)?
1054                 j = -j;
1055             // Now u >= p, so it can be reduced
1056             u %= p;
1057         }
1058         return 0;
1059     }
1060 
1061     private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
1062         BigInteger d = BigInteger.valueOf(z);
1063         BigInteger u = ONE; BigInteger u2;
1064         BigInteger v = ONE; BigInteger v2;
1065 
1066         for (int i=k.bitLength()-2; i >= 0; i--) {
1067             u2 = u.multiply(v).mod(n);
1068 
1069             v2 = v.square().add(d.multiply(u.square())).mod(n);
1070             if (v2.testBit(0))
1071                 v2 = v2.subtract(n);
1072 
1073             v2 = v2.shiftRight(1);
1074 
1075             u = u2; v = v2;
1076             if (k.testBit(i)) {
1077                 u2 = u.add(v).mod(n);
1078                 if (u2.testBit(0))
1079                     u2 = u2.subtract(n);
1080 
1081                 u2 = u2.shiftRight(1);
1082                 v2 = v.add(d.multiply(u)).mod(n);
1083                 if (v2.testBit(0))
1084                     v2 = v2.subtract(n);
1085                 v2 = v2.shiftRight(1);
1086 
1087                 u = u2; v = v2;
1088             }
1089         }
1090         return u;
1091     }
1092 
1093     /**
1094      * Returns true iff this BigInteger passes the specified number of
1095      * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
1096      * 186-2).
1097      *
1098      * The following assumptions are made:
1099      * This BigInteger is a positive, odd number greater than 2.
1100      * iterations<=50.
1101      */
passesMillerRabin(int iterations, Random rnd)1102     private boolean passesMillerRabin(int iterations, Random rnd) {
1103         // Find a and m such that m is odd and this == 1 + 2**a * m
1104         BigInteger thisMinusOne = this.subtract(ONE);
1105         BigInteger m = thisMinusOne;
1106         int a = m.getLowestSetBit();
1107         m = m.shiftRight(a);
1108 
1109         // Do the tests
1110         if (rnd == null) {
1111             rnd = ThreadLocalRandom.current();
1112         }
1113         for (int i=0; i < iterations; i++) {
1114             // Generate a uniform random on (1, this)
1115             BigInteger b;
1116             do {
1117                 b = new BigInteger(this.bitLength(), rnd);
1118             } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);
1119 
1120             int j = 0;
1121             BigInteger z = b.modPow(m, this);
1122             while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
1123                 if (j > 0 && z.equals(ONE) || ++j == a)
1124                     return false;
1125                 z = z.modPow(TWO, this);
1126             }
1127         }
1128         return true;
1129     }
1130 
1131     /**
1132      * This internal constructor differs from its public cousin
1133      * with the arguments reversed in two ways: it assumes that its
1134      * arguments are correct, and it doesn't copy the magnitude array.
1135      */
BigInteger(int[] magnitude, int signum)1136     BigInteger(int[] magnitude, int signum) {
1137         this.signum = (magnitude.length == 0 ? 0 : signum);
1138         this.mag = magnitude;
1139         if (mag.length >= MAX_MAG_LENGTH) {
1140             checkRange();
1141         }
1142     }
1143 
1144     /**
1145      * This private constructor is for internal use and assumes that its
1146      * arguments are correct.  The {@code magnitude} array is assumed to be
1147      * unchanged for the duration of the constructor call.
1148      */
BigInteger(byte[] magnitude, int signum)1149     private BigInteger(byte[] magnitude, int signum) {
1150         this.signum = (magnitude.length == 0 ? 0 : signum);
1151         this.mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);
1152         if (mag.length >= MAX_MAG_LENGTH) {
1153             checkRange();
1154         }
1155     }
1156 
1157     /**
1158      * Throws an {@code ArithmeticException} if the {@code BigInteger} would be
1159      * out of the supported range.
1160      *
1161      * @throws ArithmeticException if {@code this} exceeds the supported range.
1162      */
checkRange()1163     private void checkRange() {
1164         if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) {
1165             reportOverflow();
1166         }
1167     }
1168 
reportOverflow()1169     private static void reportOverflow() {
1170         throw new ArithmeticException("BigInteger would overflow supported range");
1171     }
1172 
1173     //Static Factory Methods
1174 
1175     /**
1176      * Returns a BigInteger whose value is equal to that of the
1177      * specified {@code long}.
1178      *
1179      * @apiNote This static factory method is provided in preference
1180      * to a ({@code long}) constructor because it allows for reuse of
1181      * frequently used BigIntegers.
1182      *
1183      * @param  val value of the BigInteger to return.
1184      * @return a BigInteger with the specified value.
1185      */
valueOf(long val)1186     public static BigInteger valueOf(long val) {
1187         // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
1188         if (val == 0)
1189             return ZERO;
1190         if (val > 0 && val <= MAX_CONSTANT)
1191             return posConst[(int) val];
1192         else if (val < 0 && val >= -MAX_CONSTANT)
1193             return negConst[(int) -val];
1194 
1195         return new BigInteger(val);
1196     }
1197 
1198     /**
1199      * Constructs a BigInteger with the specified value, which may not be zero.
1200      */
BigInteger(long val)1201     private BigInteger(long val) {
1202         if (val < 0) {
1203             val = -val;
1204             signum = -1;
1205         } else {
1206             signum = 1;
1207         }
1208 
1209         int highWord = (int)(val >>> 32);
1210         if (highWord == 0) {
1211             mag = new int[1];
1212             mag[0] = (int)val;
1213         } else {
1214             mag = new int[2];
1215             mag[0] = highWord;
1216             mag[1] = (int)val;
1217         }
1218     }
1219 
1220     /**
1221      * Returns a BigInteger with the given two's complement representation.
1222      * Assumes that the input array will not be modified (the returned
1223      * BigInteger will reference the input array if feasible).
1224      */
valueOf(int val[])1225     private static BigInteger valueOf(int val[]) {
1226         return (val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val));
1227     }
1228 
1229     // Constants
1230 
1231     /**
1232      * Initialize static constant array when class is loaded.
1233      */
1234     private static final int MAX_CONSTANT = 16;
1235     private static final BigInteger[] posConst = new BigInteger[MAX_CONSTANT+1];
1236     private static final BigInteger[] negConst = new BigInteger[MAX_CONSTANT+1];
1237 
1238     /**
1239      * The cache of powers of each radix.  This allows us to not have to
1240      * recalculate powers of radix^(2^n) more than once.  This speeds
1241      * Schoenhage recursive base conversion significantly.
1242      */
1243     private static volatile BigInteger[][] powerCache;
1244 
1245     /** The cache of logarithms of radices for base conversion. */
1246     private static final double[] logCache;
1247 
1248     /** The natural log of 2.  This is used in computing cache indices. */
1249     private static final double LOG_TWO = Math.log(2.0);
1250 
1251     static {
1252         assert 0 < KARATSUBA_THRESHOLD
1253             && KARATSUBA_THRESHOLD < TOOM_COOK_THRESHOLD
1254             && TOOM_COOK_THRESHOLD < Integer.MAX_VALUE
1255             && 0 < KARATSUBA_SQUARE_THRESHOLD
1256             && KARATSUBA_SQUARE_THRESHOLD < TOOM_COOK_SQUARE_THRESHOLD
1257             && TOOM_COOK_SQUARE_THRESHOLD < Integer.MAX_VALUE :
1258             "Algorithm thresholds are inconsistent";
1259 
1260         for (int i = 1; i <= MAX_CONSTANT; i++) {
1261             int[] magnitude = new int[1];
1262             magnitude[0] = i;
1263             posConst[i] = new BigInteger(magnitude,  1);
1264             negConst[i] = new BigInteger(magnitude, -1);
1265         }
1266 
1267         /*
1268          * Initialize the cache of radix^(2^x) values used for base conversion
1269          * with just the very first value.  Additional values will be created
1270          * on demand.
1271          */
1272         powerCache = new BigInteger[Character.MAX_RADIX+1][];
1273         logCache = new double[Character.MAX_RADIX+1];
1274 
1275         for (int i=Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {
1276             powerCache[i] = new BigInteger[] { BigInteger.valueOf(i) };
1277             logCache[i] = Math.log(i);
1278         }
1279     }
1280 
1281     /**
1282      * The BigInteger constant zero.
1283      *
1284      * @since   1.2
1285      */
1286     public static final BigInteger ZERO = new BigInteger(new int[0], 0);
1287 
1288     /**
1289      * The BigInteger constant one.
1290      *
1291      * @since   1.2
1292      */
1293     public static final BigInteger ONE = valueOf(1);
1294 
1295     /**
1296      * The BigInteger constant two.
1297      *
1298      * @since   9
1299      */
1300     public static final BigInteger TWO = valueOf(2);
1301 
1302     /**
1303      * The BigInteger constant -1.  (Not exported.)
1304      */
1305     private static final BigInteger NEGATIVE_ONE = valueOf(-1);
1306 
1307     /**
1308      * The BigInteger constant ten.
1309      *
1310      * @since   1.5
1311      */
1312     public static final BigInteger TEN = valueOf(10);
1313 
1314     // Arithmetic Operations
1315 
1316     /**
1317      * Returns a BigInteger whose value is {@code (this + val)}.
1318      *
1319      * @param  val value to be added to this BigInteger.
1320      * @return {@code this + val}
1321      */
1322     public BigInteger add(BigInteger val) {
1323         if (val.signum == 0)
1324             return this;
1325         if (signum == 0)
1326             return val;
1327         if (val.signum == signum)
1328             return new BigInteger(add(mag, val.mag), signum);
1329 
1330         int cmp = compareMagnitude(val);
1331         if (cmp == 0)
1332             return ZERO;
1333         int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
1334                            : subtract(val.mag, mag));
1335         resultMag = trustedStripLeadingZeroInts(resultMag);
1336 
1337         return new BigInteger(resultMag, cmp == signum ? 1 : -1);
1338     }
1339 
1340     /**
1341      * Package private methods used by BigDecimal code to add a BigInteger
1342      * with a long. Assumes val is not equal to INFLATED.
1343      */
1344     BigInteger add(long val) {
1345         if (val == 0)
1346             return this;
1347         if (signum == 0)
1348             return valueOf(val);
1349         if (Long.signum(val) == signum)
1350             return new BigInteger(add(mag, Math.abs(val)), signum);
1351         int cmp = compareMagnitude(val);
1352         if (cmp == 0)
1353             return ZERO;
1354         int[] resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag));
1355         resultMag = trustedStripLeadingZeroInts(resultMag);
1356         return new BigInteger(resultMag, cmp == signum ? 1 : -1);
1357     }
1358 
1359     /**
1360      * Adds the contents of the int array x and long value val. This
1361      * method allocates a new int array to hold the answer and returns
1362      * a reference to that array.  Assumes x.length &gt; 0 and val is
1363      * non-negative
1364      */
1365     private static int[] add(int[] x, long val) {
1366         int[] y;
1367         long sum = 0;
1368         int xIndex = x.length;
1369         int[] result;
1370         int highWord = (int)(val >>> 32);
1371         if (highWord == 0) {
1372             result = new int[xIndex];
1373             sum = (x[--xIndex] & LONG_MASK) + val;
1374             result[xIndex] = (int)sum;
1375         } else {
1376             if (xIndex == 1) {
1377                 result = new int[2];
1378                 sum = val  + (x[0] & LONG_MASK);
1379                 result[1] = (int)sum;
1380                 result[0] = (int)(sum >>> 32);
1381                 return result;
1382             } else {
1383                 result = new int[xIndex];
1384                 sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK);
1385                 result[xIndex] = (int)sum;
1386                 sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32);
1387                 result[xIndex] = (int)sum;
1388             }
1389         }
1390         // Copy remainder of longer number while carry propagation is required
1391         boolean carry = (sum >>> 32 != 0);
1392         while (xIndex > 0 && carry)
1393             carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
1394         // Copy remainder of longer number
1395         while (xIndex > 0)
1396             result[--xIndex] = x[xIndex];
1397         // Grow result if necessary
1398         if (carry) {
1399             int bigger[] = new int[result.length + 1];
System.arraycopy(result, 0, bigger, 1, result.length)1400             System.arraycopy(result, 0, bigger, 1, result.length);
1401             bigger[0] = 0x01;
1402             return bigger;
1403         }
1404         return result;
1405     }
1406 
1407     /**
1408      * Adds the contents of the int arrays x and y. This method allocates
1409      * a new int array to hold the answer and returns a reference to that
1410      * array.
1411      */
add(int[] x, int[] y)1412     private static int[] add(int[] x, int[] y) {
1413         // If x is shorter, swap the two arrays
1414         if (x.length < y.length) {
1415             int[] tmp = x;
1416             x = y;
1417             y = tmp;
1418         }
1419 
1420         int xIndex = x.length;
1421         int yIndex = y.length;
1422         int result[] = new int[xIndex];
1423         long sum = 0;
1424         if (yIndex == 1) {
1425             sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ;
1426             result[xIndex] = (int)sum;
1427         } else {
1428             // Add common parts of both numbers
1429             while (yIndex > 0) {
1430                 sum = (x[--xIndex] & LONG_MASK) +
1431                       (y[--yIndex] & LONG_MASK) + (sum >>> 32);
1432                 result[xIndex] = (int)sum;
1433             }
1434         }
1435         // Copy remainder of longer number while carry propagation is required
1436         boolean carry = (sum >>> 32 != 0);
1437         while (xIndex > 0 && carry)
1438             carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
1439 
1440         // Copy remainder of longer number
1441         while (xIndex > 0)
1442             result[--xIndex] = x[xIndex];
1443 
1444         // Grow result if necessary
1445         if (carry) {
1446             int bigger[] = new int[result.length + 1];
1447             System.arraycopy(result, 0, bigger, 1, result.length);
1448             bigger[0] = 0x01;
1449             return bigger;
1450         }
1451         return result;
1452     }
1453 
subtract(long val, int[] little)1454     private static int[] subtract(long val, int[] little) {
1455         int highWord = (int)(val >>> 32);
1456         if (highWord == 0) {
1457             int result[] = new int[1];
1458             result[0] = (int)(val - (little[0] & LONG_MASK));
1459             return result;
1460         } else {
1461             int result[] = new int[2];
1462             if (little.length == 1) {
1463                 long difference = ((int)val & LONG_MASK) - (little[0] & LONG_MASK);
1464                 result[1] = (int)difference;
1465                 // Subtract remainder of longer number while borrow propagates
1466                 boolean borrow = (difference >> 32 != 0);
1467                 if (borrow) {
1468                     result[0] = highWord - 1;
1469                 } else {        // Copy remainder of longer number
1470                     result[0] = highWord;
1471                 }
1472                 return result;
1473             } else { // little.length == 2
1474                 long difference = ((int)val & LONG_MASK) - (little[1] & LONG_MASK);
1475                 result[1] = (int)difference;
1476                 difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32);
1477                 result[0] = (int)difference;
1478                 return result;
1479             }
1480         }
1481     }
1482 
1483     /**
1484      * Subtracts the contents of the second argument (val) from the
1485      * first (big).  The first int array (big) must represent a larger number
1486      * than the second.  This method allocates the space necessary to hold the
1487      * answer.
1488      * assumes val &gt;= 0
1489      */
subtract(int[] big, long val)1490     private static int[] subtract(int[] big, long val) {
1491         int highWord = (int)(val >>> 32);
1492         int bigIndex = big.length;
1493         int result[] = new int[bigIndex];
1494         long difference = 0;
1495 
1496         if (highWord == 0) {
1497             difference = (big[--bigIndex] & LONG_MASK) - val;
1498             result[bigIndex] = (int)difference;
1499         } else {
1500             difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK);
1501             result[bigIndex] = (int)difference;
1502             difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32);
1503             result[bigIndex] = (int)difference;
1504         }
1505 
1506         // Subtract remainder of longer number while borrow propagates
1507         boolean borrow = (difference >> 32 != 0);
1508         while (bigIndex > 0 && borrow)
1509             borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
1510 
1511         // Copy remainder of longer number
1512         while (bigIndex > 0)
1513             result[--bigIndex] = big[bigIndex];
1514 
1515         return result;
1516     }
1517 
1518     /**
1519      * Returns a BigInteger whose value is {@code (this - val)}.
1520      *
1521      * @param  val value to be subtracted from this BigInteger.
1522      * @return {@code this - val}
1523      */
subtract(BigInteger val)1524     public BigInteger subtract(BigInteger val) {
1525         if (val.signum == 0)
1526             return this;
1527         if (signum == 0)
1528             return val.negate();
1529         if (val.signum != signum)
1530             return new BigInteger(add(mag, val.mag), signum);
1531 
1532         int cmp = compareMagnitude(val);
1533         if (cmp == 0)
1534             return ZERO;
1535         int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
1536                            : subtract(val.mag, mag));
1537         resultMag = trustedStripLeadingZeroInts(resultMag);
1538         return new BigInteger(resultMag, cmp == signum ? 1 : -1);
1539     }
1540 
1541     /**
1542      * Subtracts the contents of the second int arrays (little) from the
1543      * first (big).  The first int array (big) must represent a larger number
1544      * than the second.  This method allocates the space necessary to hold the
1545      * answer.
1546      */
subtract(int[] big, int[] little)1547     private static int[] subtract(int[] big, int[] little) {
1548         int bigIndex = big.length;
1549         int result[] = new int[bigIndex];
1550         int littleIndex = little.length;
1551         long difference = 0;
1552 
1553         // Subtract common parts of both numbers
1554         while (littleIndex > 0) {
1555             difference = (big[--bigIndex] & LONG_MASK) -
1556                          (little[--littleIndex] & LONG_MASK) +
1557                          (difference >> 32);
1558             result[bigIndex] = (int)difference;
1559         }
1560 
1561         // Subtract remainder of longer number while borrow propagates
1562         boolean borrow = (difference >> 32 != 0);
1563         while (bigIndex > 0 && borrow)
1564             borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
1565 
1566         // Copy remainder of longer number
1567         while (bigIndex > 0)
1568             result[--bigIndex] = big[bigIndex];
1569 
1570         return result;
1571     }
1572 
1573     /**
1574      * Returns a BigInteger whose value is {@code (this * val)}.
1575      *
1576      * @implNote An implementation may offer better algorithmic
1577      * performance when {@code val == this}.
1578      *
1579      * @param  val value to be multiplied by this BigInteger.
1580      * @return {@code this * val}
1581      */
multiply(BigInteger val)1582     public BigInteger multiply(BigInteger val) {
1583         return multiply(val, false);
1584     }
1585 
1586     /**
1587      * Returns a BigInteger whose value is {@code (this * val)}.  If
1588      * the invocation is recursive certain overflow checks are skipped.
1589      *
1590      * @param  val value to be multiplied by this BigInteger.
1591      * @param  isRecursion whether this is a recursive invocation
1592      * @return {@code this * val}
1593      */
multiply(BigInteger val, boolean isRecursion)1594     private BigInteger multiply(BigInteger val, boolean isRecursion) {
1595         if (val.signum == 0 || signum == 0)
1596             return ZERO;
1597 
1598         int xlen = mag.length;
1599 
1600         // BEGIN Android-changed: Fall back to the boringssl implementation for
1601         // large arguments.
1602         final int BORINGSSL_MUL_THRESHOLD = 50;
1603 
1604         if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD
1605                 && xlen < BORINGSSL_MUL_THRESHOLD) {
1606             return square();
1607         }
1608 
1609         int ylen = val.mag.length;
1610 
1611         int resultSign = signum == val.signum ? 1 : -1;
1612         if ((xlen < BORINGSSL_MUL_THRESHOLD) || (ylen < BORINGSSL_MUL_THRESHOLD)) {
1613             if (val.mag.length == 1) {
1614                 return multiplyByInt(mag,val.mag[0], resultSign);
1615             }
1616             if (mag.length == 1) {
1617                 return multiplyByInt(val.mag,mag[0], resultSign);
1618             }
1619             int[] result = multiplyToLen(mag, xlen,
1620                                          val.mag, ylen, null);
1621             result = trustedStripLeadingZeroInts(result);
1622             return new BigInteger(result, resultSign);
1623         } else {
1624             long xBN = 0, yBN = 0, resultBN = 0;
1625             try {
1626                 xBN = bigEndInts2NewBN(mag, /* neg= */false);
1627                 yBN = bigEndInts2NewBN(val.mag, /* neg= */false);
1628                 resultBN = NativeBN.BN_new();
1629                 NativeBN.BN_mul(resultBN, xBN, yBN);
1630                 return new BigInteger(resultSign, bn2BigEndInts(resultBN));
1631             } finally {
1632                 NativeBN.BN_free(xBN);
1633                 NativeBN.BN_free(yBN);
1634                 NativeBN.BN_free(resultBN);
1635             }
1636 
1637             /*
1638             if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {
1639                 return multiplyKaratsuba(this, val);
1640             } else {
1641                 //
1642                 // In "Hacker's Delight" section 2-13, p.33, it is explained
1643                 // that if x and y are unsigned 32-bit quantities and m and n
1644                 // are their respective numbers of leading zeros within 32 bits,
1645                 // then the number of leading zeros within their product as a
1646                 // 64-bit unsigned quantity is either m + n or m + n + 1. If
1647                 // their product is not to overflow, it cannot exceed 32 bits,
1648                 // and so the number of leading zeros of the product within 64
1649                 // bits must be at least 32, i.e., the leftmost set bit is at
1650                 // zero-relative position 31 or less.
1651                 //
1652                 // From the above there are three cases:
1653                 //
1654                 //     m + n    leftmost set bit    condition
1655                 //     -----    ----------------    ---------
1656                 //     >= 32    x <= 64 - 32 = 32   no overflow
1657                 //     == 31    x >= 64 - 32 = 32   possible overflow
1658                 //     <= 30    x >= 64 - 31 = 33   definite overflow
1659                 //
1660                 // The "possible overflow" condition cannot be detected by
1661                 // examning data lengths alone and requires further calculation.
1662                 //
1663                 // By analogy, if 'this' and 'val' have m and n as their
1664                 // respective numbers of leading zeros within 32*MAX_MAG_LENGTH
1665                 // bits, then:
1666                 //
1667                 //     m + n >= 32*MAX_MAG_LENGTH        no overflow
1668                 //     m + n == 32*MAX_MAG_LENGTH - 1    possible overflow
1669                 //     m + n <= 32*MAX_MAG_LENGTH - 2    definite overflow
1670                 //
1671                 // Note however that if the number of ints in the result
1672                 // were to be MAX_MAG_LENGTH and mag[0] < 0, then there would
1673                 // be overflow. As a result the leftmost bit (of mag[0]) cannot
1674                 // be used and the constraints must be adjusted by one bit to:
1675                 //
1676                 //     m + n >  32*MAX_MAG_LENGTH        no overflow
1677                 //     m + n == 32*MAX_MAG_LENGTH        possible overflow
1678                 //     m + n <  32*MAX_MAG_LENGTH        definite overflow
1679                 //
1680                 // The foregoing leading zero-based discussion is for clarity
1681                 // only. The actual calculations use the estimated bit length
1682                 // of the product as this is more natural to the internal
1683                 // array representation of the magnitude which has no leading
1684                 // zero elements.
1685                 //
1686                 if (!isRecursion) {
1687                     // The bitLength() instance method is not used here as we
1688                     // are only considering the magnitudes as non-negative. The
1689                     // Toom-Cook multiplication algorithm determines the sign
1690                     // at its end from the two signum values.
1691                     if ((long)bitLength(mag, mag.length) +
1692                         (long)bitLength(val.mag, val.mag.length) >
1693                         32L*MAX_MAG_LENGTH) {
1694                         reportOverflow();
1695                     }
1696                 }
1697 
1698                 return multiplyToomCook3(this, val);
1699             }
1700             */
1701         // END Android-changed: Fall back to the boringssl implementation for
1702         // large arguments.
1703         }
1704     }
1705 
multiplyByInt(int[] x, int y, int sign)1706     private static BigInteger multiplyByInt(int[] x, int y, int sign) {
1707         if (Integer.bitCount(y) == 1) {
1708             return new BigInteger(shiftLeft(x,Integer.numberOfTrailingZeros(y)), sign);
1709         }
1710         int xlen = x.length;
1711         // BEGIN Android-changed: Try to predict result length to avoid copy. http://b/140780742
1712         /*
1713         int[] rmag =  new int[xlen + 1];
1714         long carry = 0;
1715         long yl = y & LONG_MASK;
1716         int rstart = rmag.length - 1;
1717         for (int i = xlen - 1; i >= 0; i--) {
1718             long product = (x[i] & LONG_MASK) * yl + carry;
1719             rmag[rstart--] = (int)product;
1720             carry = product >>> 32;
1721         }
1722         if (carry == 0L) {
1723             rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
1724         } else {
1725             rmag[rstart] = (int)carry;
1726         }
1727         */
1728         long carry = 0;
1729         long yl = y & LONG_MASK;
1730         // Bound the 2 most significant product (int-sized) "digits". Less-significant ints in x's
1731         // magnitude cannot contribute more than 1 in the uppermost int.
1732         long highDigitsBound = ((x[0] & LONG_MASK) + 1) * yl;  // Cannot overflow as unsigned long.
1733         int rlen = ((highDigitsBound >>> 32) == 0) ? xlen : xlen + 1;
1734         int[] rmag =  new int[rlen];
1735         int rindex = rlen - 1;
1736         for (int i = xlen - 1; i >= 0; i--) {
1737             long product = (x[i] & LONG_MASK) * yl + carry;
1738             rmag[rindex--] = (int)product;
1739             carry = product >>> 32;
1740         }
1741         if (rindex == -1) {
1742             assert(carry == 0);
1743         } else {
1744             assert(rindex == 0);
1745             if (carry == 0) {
1746                 // We mis-estimated the length. Very rare.
1747                 rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
1748             } else {
1749                 rmag[0] = (int)carry;
1750             }
1751         }
1752         // END Android-changed: Try to predict result length to avoid copy.
1753         return new BigInteger(rmag, sign);
1754     }
1755 
1756     /**
1757      * Package private methods used by BigDecimal code to multiply a BigInteger
1758      * with a long. Assumes v is not equal to INFLATED.
1759      */
multiply(long v)1760     BigInteger multiply(long v) {
1761         if (v == 0 || signum == 0)
1762           return ZERO;
1763         if (v == BigDecimal.INFLATED)
1764             return multiply(BigInteger.valueOf(v));
1765         int rsign = (v > 0 ? signum : -signum);
1766         if (v < 0)
1767             v = -v;
1768         long dh = v >>> 32;      // higher order bits
1769         long dl = v & LONG_MASK; // lower order bits
1770 
1771         int xlen = mag.length;
1772         int[] value = mag;
1773         int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]);
1774         long carry = 0;
1775         int rstart = rmag.length - 1;
1776         for (int i = xlen - 1; i >= 0; i--) {
1777             long product = (value[i] & LONG_MASK) * dl + carry;
1778             rmag[rstart--] = (int)product;
1779             carry = product >>> 32;
1780         }
1781         rmag[rstart] = (int)carry;
1782         if (dh != 0L) {
1783             carry = 0;
1784             rstart = rmag.length - 2;
1785             for (int i = xlen - 1; i >= 0; i--) {
1786                 long product = (value[i] & LONG_MASK) * dh +
1787                     (rmag[rstart] & LONG_MASK) + carry;
1788                 rmag[rstart--] = (int)product;
1789                 carry = product >>> 32;
1790             }
1791             rmag[0] = (int)carry;
1792         }
1793         if (carry == 0L)
1794             rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
1795         return new BigInteger(rmag, rsign);
1796     }
1797 
1798     /**
1799      * Multiplies int arrays x and y to the specified lengths and places
1800      * the result into z. There will be no leading zeros in the resultant array.
1801      */
multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z)1802     private static int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
1803         multiplyToLenCheck(x, xlen);
1804         multiplyToLenCheck(y, ylen);
1805         return implMultiplyToLen(x, xlen, y, ylen, z);
1806     }
1807 
1808     @IntrinsicCandidate
implMultiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z)1809     private static int[] implMultiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
1810         int xstart = xlen - 1;
1811         int ystart = ylen - 1;
1812 
1813         if (z == null || z.length < (xlen+ ylen))
1814              z = new int[xlen+ylen];
1815 
1816         long carry = 0;
1817         for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {
1818             long product = (y[j] & LONG_MASK) *
1819                            (x[xstart] & LONG_MASK) + carry;
1820             z[k] = (int)product;
1821             carry = product >>> 32;
1822         }
1823         z[xstart] = (int)carry;
1824 
1825         for (int i = xstart-1; i >= 0; i--) {
1826             carry = 0;
1827             for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) {
1828                 long product = (y[j] & LONG_MASK) *
1829                                (x[i] & LONG_MASK) +
1830                                (z[k] & LONG_MASK) + carry;
1831                 z[k] = (int)product;
1832                 carry = product >>> 32;
1833             }
1834             z[i] = (int)carry;
1835         }
1836         return z;
1837     }
1838 
multiplyToLenCheck(int[] array, int length)1839     private static void multiplyToLenCheck(int[] array, int length) {
1840         if (length <= 0) {
1841             return;  // not an error because multiplyToLen won't execute if len <= 0
1842         }
1843 
1844         Objects.requireNonNull(array);
1845 
1846         if (length > array.length) {
1847             throw new ArrayIndexOutOfBoundsException(length - 1);
1848         }
1849     }
1850 
1851     /**
1852      * Multiplies two BigIntegers using the Karatsuba multiplication
1853      * algorithm.  This is a recursive divide-and-conquer algorithm which is
1854      * more efficient for large numbers than what is commonly called the
1855      * "grade-school" algorithm used in multiplyToLen.  If the numbers to be
1856      * multiplied have length n, the "grade-school" algorithm has an
1857      * asymptotic complexity of O(n^2).  In contrast, the Karatsuba algorithm
1858      * has complexity of O(n^(log2(3))), or O(n^1.585).  It achieves this
1859      * increased performance by doing 3 multiplies instead of 4 when
1860      * evaluating the product.  As it has some overhead, should be used when
1861      * both numbers are larger than a certain threshold (found
1862      * experimentally).
1863      *
1864      * See:  http://en.wikipedia.org/wiki/Karatsuba_algorithm
1865      */
multiplyKaratsuba(BigInteger x, BigInteger y)1866     private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) {
1867         int xlen = x.mag.length;
1868         int ylen = y.mag.length;
1869 
1870         // The number of ints in each half of the number.
1871         int half = (Math.max(xlen, ylen)+1) / 2;
1872 
1873         // xl and yl are the lower halves of x and y respectively,
1874         // xh and yh are the upper halves.
1875         BigInteger xl = x.getLower(half);
1876         BigInteger xh = x.getUpper(half);
1877         BigInteger yl = y.getLower(half);
1878         BigInteger yh = y.getUpper(half);
1879 
1880         BigInteger p1 = xh.multiply(yh);  // p1 = xh*yh
1881         BigInteger p2 = xl.multiply(yl);  // p2 = xl*yl
1882 
1883         // p3=(xh+xl)*(yh+yl)
1884         BigInteger p3 = xh.add(xl).multiply(yh.add(yl));
1885 
1886         // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2
1887         BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2);
1888 
1889         if (x.signum != y.signum) {
1890             return result.negate();
1891         } else {
1892             return result;
1893         }
1894     }
1895 
1896     /**
1897      * Multiplies two BigIntegers using a 3-way Toom-Cook multiplication
1898      * algorithm.  This is a recursive divide-and-conquer algorithm which is
1899      * more efficient for large numbers than what is commonly called the
1900      * "grade-school" algorithm used in multiplyToLen.  If the numbers to be
1901      * multiplied have length n, the "grade-school" algorithm has an
1902      * asymptotic complexity of O(n^2).  In contrast, 3-way Toom-Cook has a
1903      * complexity of about O(n^1.465).  It achieves this increased asymptotic
1904      * performance by breaking each number into three parts and by doing 5
1905      * multiplies instead of 9 when evaluating the product.  Due to overhead
1906      * (additions, shifts, and one division) in the Toom-Cook algorithm, it
1907      * should only be used when both numbers are larger than a certain
1908      * threshold (found experimentally).  This threshold is generally larger
1909      * than that for Karatsuba multiplication, so this algorithm is generally
1910      * only used when numbers become significantly larger.
1911      *
1912      * The algorithm used is the "optimal" 3-way Toom-Cook algorithm outlined
1913      * by Marco Bodrato.
1914      *
1915      *  See: http://bodrato.it/toom-cook/
1916      *       http://bodrato.it/papers/#WAIFI2007
1917      *
1918      * "Towards Optimal Toom-Cook Multiplication for Univariate and
1919      * Multivariate Polynomials in Characteristic 2 and 0." by Marco BODRATO;
1920      * In C.Carlet and B.Sunar, Eds., "WAIFI'07 proceedings", p. 116-133,
1921      * LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007.
1922      *
1923      */
multiplyToomCook3(BigInteger a, BigInteger b)1924     private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) {
1925         int alen = a.mag.length;
1926         int blen = b.mag.length;
1927 
1928         int largest = Math.max(alen, blen);
1929 
1930         // k is the size (in ints) of the lower-order slices.
1931         int k = (largest+2)/3;   // Equal to ceil(largest/3)
1932 
1933         // r is the size (in ints) of the highest-order slice.
1934         int r = largest - 2*k;
1935 
1936         // Obtain slices of the numbers. a2 and b2 are the most significant
1937         // bits of the numbers a and b, and a0 and b0 the least significant.
1938         BigInteger a0, a1, a2, b0, b1, b2;
1939         a2 = a.getToomSlice(k, r, 0, largest);
1940         a1 = a.getToomSlice(k, r, 1, largest);
1941         a0 = a.getToomSlice(k, r, 2, largest);
1942         b2 = b.getToomSlice(k, r, 0, largest);
1943         b1 = b.getToomSlice(k, r, 1, largest);
1944         b0 = b.getToomSlice(k, r, 2, largest);
1945 
1946         BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
1947 
1948         v0 = a0.multiply(b0, true);
1949         da1 = a2.add(a0);
1950         db1 = b2.add(b0);
1951         vm1 = da1.subtract(a1).multiply(db1.subtract(b1), true);
1952         da1 = da1.add(a1);
1953         db1 = db1.add(b1);
1954         v1 = da1.multiply(db1, true);
1955         v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
1956              db1.add(b2).shiftLeft(1).subtract(b0), true);
1957         vinf = a2.multiply(b2, true);
1958 
1959         // The algorithm requires two divisions by 2 and one by 3.
1960         // All divisions are known to be exact, that is, they do not produce
1961         // remainders, and all results are positive.  The divisions by 2 are
1962         // implemented as right shifts which are relatively efficient, leaving
1963         // only an exact division by 3, which is done by a specialized
1964         // linear-time algorithm.
1965         t2 = v2.subtract(vm1).exactDivideBy3();
1966         tm1 = v1.subtract(vm1).shiftRight(1);
1967         t1 = v1.subtract(v0);
1968         t2 = t2.subtract(t1).shiftRight(1);
1969         t1 = t1.subtract(tm1).subtract(vinf);
1970         t2 = t2.subtract(vinf.shiftLeft(1));
1971         tm1 = tm1.subtract(t2);
1972 
1973         // Number of bits to shift left.
1974         int ss = k*32;
1975 
1976         BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
1977 
1978         if (a.signum != b.signum) {
1979             return result.negate();
1980         } else {
1981             return result;
1982         }
1983     }
1984 
1985 
1986     /**
1987      * Returns a slice of a BigInteger for use in Toom-Cook multiplication.
1988      *
1989      * @param lowerSize The size of the lower-order bit slices.
1990      * @param upperSize The size of the higher-order bit slices.
1991      * @param slice The index of which slice is requested, which must be a
1992      * number from 0 to size-1. Slice 0 is the highest-order bits, and slice
1993      * size-1 are the lowest-order bits. Slice 0 may be of different size than
1994      * the other slices.
1995      * @param fullsize The size of the larger integer array, used to align
1996      * slices to the appropriate position when multiplying different-sized
1997      * numbers.
1998      */
getToomSlice(int lowerSize, int upperSize, int slice, int fullsize)1999     private BigInteger getToomSlice(int lowerSize, int upperSize, int slice,
2000                                     int fullsize) {
2001         int start, end, sliceSize, len, offset;
2002 
2003         len = mag.length;
2004         offset = fullsize - len;
2005 
2006         if (slice == 0) {
2007             start = 0 - offset;
2008             end = upperSize - 1 - offset;
2009         } else {
2010             start = upperSize + (slice-1)*lowerSize - offset;
2011             end = start + lowerSize - 1;
2012         }
2013 
2014         if (start < 0) {
2015             start = 0;
2016         }
2017         if (end < 0) {
2018            return ZERO;
2019         }
2020 
2021         sliceSize = (end-start) + 1;
2022 
2023         if (sliceSize <= 0) {
2024             return ZERO;
2025         }
2026 
2027         // While performing Toom-Cook, all slices are positive and
2028         // the sign is adjusted when the final number is composed.
2029         if (start == 0 && sliceSize >= len) {
2030             return this.abs();
2031         }
2032 
2033         int intSlice[] = new int[sliceSize];
2034         System.arraycopy(mag, start, intSlice, 0, sliceSize);
2035 
2036         return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1);
2037     }
2038 
2039     /**
2040      * Does an exact division (that is, the remainder is known to be zero)
2041      * of the specified number by 3.  This is used in Toom-Cook
2042      * multiplication.  This is an efficient algorithm that runs in linear
2043      * time.  If the argument is not exactly divisible by 3, results are
2044      * undefined.  Note that this is expected to be called with positive
2045      * arguments only.
2046      */
exactDivideBy3()2047     private BigInteger exactDivideBy3() {
2048         int len = mag.length;
2049         int[] result = new int[len];
2050         long x, w, q, borrow;
2051         borrow = 0L;
2052         for (int i=len-1; i >= 0; i--) {
2053             x = (mag[i] & LONG_MASK);
2054             w = x - borrow;
2055             if (borrow > x) {      // Did we make the number go negative?
2056                 borrow = 1L;
2057             } else {
2058                 borrow = 0L;
2059             }
2060 
2061             // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32).  Thus,
2062             // the effect of this is to divide by 3 (mod 2^32).
2063             // This is much faster than division on most architectures.
2064             q = (w * 0xAAAAAAABL) & LONG_MASK;
2065             result[i] = (int) q;
2066 
2067             // Now check the borrow. The second check can of course be
2068             // eliminated if the first fails.
2069             if (q >= 0x55555556L) {
2070                 borrow++;
2071                 if (q >= 0xAAAAAAABL)
2072                     borrow++;
2073             }
2074         }
2075         result = trustedStripLeadingZeroInts(result);
2076         return new BigInteger(result, signum);
2077     }
2078 
2079     /**
2080      * Returns a new BigInteger representing n lower ints of the number.
2081      * This is used by Karatsuba multiplication and Karatsuba squaring.
2082      */
getLower(int n)2083     private BigInteger getLower(int n) {
2084         int len = mag.length;
2085 
2086         if (len <= n) {
2087             return abs();
2088         }
2089 
2090         int lowerInts[] = new int[n];
2091         System.arraycopy(mag, len-n, lowerInts, 0, n);
2092 
2093         return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);
2094     }
2095 
2096     /**
2097      * Returns a new BigInteger representing mag.length-n upper
2098      * ints of the number.  This is used by Karatsuba multiplication and
2099      * Karatsuba squaring.
2100      */
getUpper(int n)2101     private BigInteger getUpper(int n) {
2102         int len = mag.length;
2103 
2104         if (len <= n) {
2105             return ZERO;
2106         }
2107 
2108         int upperLen = len - n;
2109         int upperInts[] = new int[upperLen];
2110         System.arraycopy(mag, 0, upperInts, 0, upperLen);
2111 
2112         return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1);
2113     }
2114 
2115     // Squaring
2116 
2117     /**
2118      * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}.
2119      *
2120      * @return {@code this<sup>2</sup>}
2121      */
square()2122     private BigInteger square() {
2123         return square(false);
2124     }
2125 
2126     /**
2127      * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}. If
2128      * the invocation is recursive certain overflow checks are skipped.
2129      *
2130      * @param isRecursion whether this is a recursive invocation
2131      * @return {@code this<sup>2</sup>}
2132      */
square(boolean isRecursion)2133     private BigInteger square(boolean isRecursion) {
2134         if (signum == 0) {
2135             return ZERO;
2136         }
2137         int len = mag.length;
2138 
2139         if (len < KARATSUBA_SQUARE_THRESHOLD) {
2140             int[] z = squareToLen(mag, len, null);
2141             return new BigInteger(trustedStripLeadingZeroInts(z), 1);
2142         } else {
2143             if (len < TOOM_COOK_SQUARE_THRESHOLD) {
2144                 return squareKaratsuba();
2145             } else {
2146                 //
2147                 // For a discussion of overflow detection see multiply()
2148                 //
2149                 if (!isRecursion) {
2150                     if (bitLength(mag, mag.length) > 16L*MAX_MAG_LENGTH) {
2151                         reportOverflow();
2152                     }
2153                 }
2154 
2155                 return squareToomCook3();
2156             }
2157         }
2158     }
2159 
2160     /**
2161      * Squares the contents of the int array x. The result is placed into the
2162      * int array z.  The contents of x are not changed.
2163      */
squareToLen(int[] x, int len, int[] z)2164     private static final int[] squareToLen(int[] x, int len, int[] z) {
2165          int zlen = len << 1;
2166          if (z == null || z.length < zlen)
2167              z = new int[zlen];
2168 
2169          // Execute checks before calling intrinsified method.
2170          implSquareToLenChecks(x, len, z, zlen);
2171          return implSquareToLen(x, len, z, zlen);
2172      }
2173 
2174      /**
2175       * Parameters validation.
2176       */
implSquareToLenChecks(int[] x, int len, int[] z, int zlen)2177      private static void implSquareToLenChecks(int[] x, int len, int[] z, int zlen) throws RuntimeException {
2178          if (len < 1) {
2179              throw new IllegalArgumentException("invalid input length: " + len);
2180          }
2181          if (len > x.length) {
2182              throw new IllegalArgumentException("input length out of bound: " +
2183                                         len + " > " + x.length);
2184          }
2185          if (len * 2 > z.length) {
2186              throw new IllegalArgumentException("input length out of bound: " +
2187                                         (len * 2) + " > " + z.length);
2188          }
2189          if (zlen < 1) {
2190              throw new IllegalArgumentException("invalid input length: " + zlen);
2191          }
2192          if (zlen > z.length) {
2193              throw new IllegalArgumentException("input length out of bound: " +
2194                                         len + " > " + z.length);
2195          }
2196      }
2197 
2198      /**
2199       * Java Runtime may use intrinsic for this method.
2200       */
2201      @IntrinsicCandidate
implSquareToLen(int[] x, int len, int[] z, int zlen)2202      private static final int[] implSquareToLen(int[] x, int len, int[] z, int zlen) {
2203         /*
2204          * The algorithm used here is adapted from Colin Plumb's C library.
2205          * Technique: Consider the partial products in the multiplication
2206          * of "abcde" by itself:
2207          *
2208          *               a  b  c  d  e
2209          *            *  a  b  c  d  e
2210          *          ==================
2211          *              ae be ce de ee
2212          *           ad bd cd dd de
2213          *        ac bc cc cd ce
2214          *     ab bb bc bd be
2215          *  aa ab ac ad ae
2216          *
2217          * Note that everything above the main diagonal:
2218          *              ae be ce de = (abcd) * e
2219          *           ad bd cd       = (abc) * d
2220          *        ac bc             = (ab) * c
2221          *     ab                   = (a) * b
2222          *
2223          * is a copy of everything below the main diagonal:
2224          *                       de
2225          *                 cd ce
2226          *           bc bd be
2227          *     ab ac ad ae
2228          *
2229          * Thus, the sum is 2 * (off the diagonal) + diagonal.
2230          *
2231          * This is accumulated beginning with the diagonal (which
2232          * consist of the squares of the digits of the input), which is then
2233          * divided by two, the off-diagonal added, and multiplied by two
2234          * again.  The low bit is simply a copy of the low bit of the
2235          * input, so it doesn't need special care.
2236          */
2237 
2238         // Store the squares, right shifted one bit (i.e., divided by 2)
2239         int lastProductLowWord = 0;
2240         for (int j=0, i=0; j < len; j++) {
2241             long piece = (x[j] & LONG_MASK);
2242             long product = piece * piece;
2243             z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);
2244             z[i++] = (int)(product >>> 1);
2245             lastProductLowWord = (int)product;
2246         }
2247 
2248         // Add in off-diagonal sums
2249         for (int i=len, offset=1; i > 0; i--, offset+=2) {
2250             int t = x[i-1];
2251             t = mulAdd(z, x, offset, i-1, t);
2252             addOne(z, offset-1, i, t);
2253         }
2254 
2255         // Shift back up and set low bit
2256         primitiveLeftShift(z, zlen, 1);
2257         z[zlen-1] |= x[len-1] & 1;
2258 
2259         return z;
2260     }
2261 
2262     /**
2263      * Squares a BigInteger using the Karatsuba squaring algorithm.  It should
2264      * be used when both numbers are larger than a certain threshold (found
2265      * experimentally).  It is a recursive divide-and-conquer algorithm that
2266      * has better asymptotic performance than the algorithm used in
2267      * squareToLen.
2268      */
squareKaratsuba()2269     private BigInteger squareKaratsuba() {
2270         int half = (mag.length+1) / 2;
2271 
2272         BigInteger xl = getLower(half);
2273         BigInteger xh = getUpper(half);
2274 
2275         BigInteger xhs = xh.square();  // xhs = xh^2
2276         BigInteger xls = xl.square();  // xls = xl^2
2277 
2278         // xh^2 << 64  +  (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2
2279         return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls);
2280     }
2281 
2282     /**
2283      * Squares a BigInteger using the 3-way Toom-Cook squaring algorithm.  It
2284      * should be used when both numbers are larger than a certain threshold
2285      * (found experimentally).  It is a recursive divide-and-conquer algorithm
2286      * that has better asymptotic performance than the algorithm used in
2287      * squareToLen or squareKaratsuba.
2288      */
squareToomCook3()2289     private BigInteger squareToomCook3() {
2290         int len = mag.length;
2291 
2292         // k is the size (in ints) of the lower-order slices.
2293         int k = (len+2)/3;   // Equal to ceil(largest/3)
2294 
2295         // r is the size (in ints) of the highest-order slice.
2296         int r = len - 2*k;
2297 
2298         // Obtain slices of the numbers. a2 is the most significant
2299         // bits of the number, and a0 the least significant.
2300         BigInteger a0, a1, a2;
2301         a2 = getToomSlice(k, r, 0, len);
2302         a1 = getToomSlice(k, r, 1, len);
2303         a0 = getToomSlice(k, r, 2, len);
2304         BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
2305 
2306         v0 = a0.square(true);
2307         da1 = a2.add(a0);
2308         vm1 = da1.subtract(a1).square(true);
2309         da1 = da1.add(a1);
2310         v1 = da1.square(true);
2311         vinf = a2.square(true);
2312         v2 = da1.add(a2).shiftLeft(1).subtract(a0).square(true);
2313 
2314         // The algorithm requires two divisions by 2 and one by 3.
2315         // All divisions are known to be exact, that is, they do not produce
2316         // remainders, and all results are positive.  The divisions by 2 are
2317         // implemented as right shifts which are relatively efficient, leaving
2318         // only a division by 3.
2319         // The division by 3 is done by an optimized algorithm for this case.
2320         t2 = v2.subtract(vm1).exactDivideBy3();
2321         tm1 = v1.subtract(vm1).shiftRight(1);
2322         t1 = v1.subtract(v0);
2323         t2 = t2.subtract(t1).shiftRight(1);
2324         t1 = t1.subtract(tm1).subtract(vinf);
2325         t2 = t2.subtract(vinf.shiftLeft(1));
2326         tm1 = tm1.subtract(t2);
2327 
2328         // Number of bits to shift left.
2329         int ss = k*32;
2330 
2331         return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
2332     }
2333 
2334     // Division
2335 
2336 
2337     // BEGIN Android-changed: Fall back to boringssl for large problems.
2338     private static final int BORINGSSL_DIV_THRESHOLD = 40;
2339     private static final int BORINGSSL_DIV_OFFSET = 20;
2340 
2341     /**
2342      * Returns a BigInteger whose value is {@code (this / val)}.
2343      *
2344      * @param  val value by which this BigInteger is to be divided.
2345      * @return {@code this / val}
2346      * @throws ArithmeticException if {@code val} is zero.
2347      */
divide(BigInteger val)2348     public BigInteger divide(BigInteger val) {
2349         /*
2350         if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
2351                 mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
2352         */
2353         if (mag.length < BORINGSSL_DIV_THRESHOLD ||
2354                 mag.length - val.mag.length < BORINGSSL_DIV_OFFSET) {
2355             return divideKnuth(val);
2356         } else {
2357             /*
2358             return divideBurnikelZiegler(val);
2359             */
2360             return divideAndRemainder(val)[0];
2361         }
2362     }
2363     // END Android-changed: Fall back to boringssl for large problems.
2364 
2365 
2366     /**
2367      * Returns a BigInteger whose value is {@code (this / val)} using an O(n^2) algorithm from Knuth.
2368      *
2369      * @param  val value by which this BigInteger is to be divided.
2370      * @return {@code this / val}
2371      * @throws ArithmeticException if {@code val} is zero.
2372      * @see MutableBigInteger#divideKnuth(MutableBigInteger, MutableBigInteger, boolean)
2373      */
divideKnuth(BigInteger val)2374     private BigInteger divideKnuth(BigInteger val) {
2375         MutableBigInteger q = new MutableBigInteger(),
2376                           a = new MutableBigInteger(this.mag),
2377                           b = new MutableBigInteger(val.mag);
2378 
2379         a.divideKnuth(b, q, false);
2380         return q.toBigInteger(this.signum * val.signum);
2381     }
2382 
2383     /**
2384      * Returns an array of two BigIntegers containing {@code (this / val)}
2385      * followed by {@code (this % val)}.
2386      *
2387      * @param  val value by which this BigInteger is to be divided, and the
2388      *         remainder computed.
2389      * @return an array of two BigIntegers: the quotient {@code (this / val)}
2390      *         is the initial element, and the remainder {@code (this % val)}
2391      *         is the final element.
2392      * @throws ArithmeticException if {@code val} is zero.
2393      */
divideAndRemainder(BigInteger val)2394     public BigInteger[] divideAndRemainder(BigInteger val) {
2395         // BEGIN Android-changed: Fall back to boringssl for large problems.
2396         /*
2397         if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
2398                 mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
2399          */
2400         if (val.mag.length < BORINGSSL_DIV_THRESHOLD ||
2401                 mag.length < BORINGSSL_DIV_OFFSET ||
2402                 mag.length - val.mag.length < BORINGSSL_DIV_OFFSET) {
2403             return divideAndRemainderKnuth(val);
2404         } else {
2405             /*
2406             return divideAndRemainderBurnikelZiegler(val);
2407             */
2408             int quotSign = signum == val.signum ? 1 : -1;  // 0 divided doesn't get here.
2409             long xBN = 0, yBN = 0, quotBN = 0, remBN = 0;
2410             try {
2411                 xBN = bigEndInts2NewBN(mag, /* neg= */false);
2412                 yBN = bigEndInts2NewBN(val.mag, /* neg= */false);
2413                 quotBN = NativeBN.BN_new();
2414                 remBN = NativeBN.BN_new();
2415                 NativeBN.BN_div(quotBN, remBN, xBN, yBN);
2416                 BigInteger quotient = new BigInteger(quotSign, bn2BigEndInts(quotBN));
2417                         // The sign of a zero quotient is fixed by the constructor.
2418                 BigInteger remainder = new BigInteger(signum, bn2BigEndInts(remBN));
2419                 BigInteger[] result = {quotient, remainder};
2420                 return result;
2421             } finally {
2422                 NativeBN.BN_free(xBN);
2423                 NativeBN.BN_free(yBN);
2424                 NativeBN.BN_free(quotBN);
2425                 NativeBN.BN_free(remBN);
2426             }
2427         }
2428         // END Android-changed: Fall back to boringssl for large problems.
2429     }
2430 
2431     /** Long division */
divideAndRemainderKnuth(BigInteger val)2432     private BigInteger[] divideAndRemainderKnuth(BigInteger val) {
2433         BigInteger[] result = new BigInteger[2];
2434         MutableBigInteger q = new MutableBigInteger(),
2435                           a = new MutableBigInteger(this.mag),
2436                           b = new MutableBigInteger(val.mag);
2437         MutableBigInteger r = a.divideKnuth(b, q);
2438         result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);
2439         result[1] = r.toBigInteger(this.signum);
2440         return result;
2441     }
2442 
2443     /**
2444      * Returns a BigInteger whose value is {@code (this % val)}.
2445      *
2446      * @param  val value by which this BigInteger is to be divided, and the
2447      *         remainder computed.
2448      * @return {@code this % val}
2449      * @throws ArithmeticException if {@code val} is zero.
2450      */
remainder(BigInteger val)2451     public BigInteger remainder(BigInteger val) {
2452         // BEGIN Android-changed: Fall back to boringssl for large problems.
2453         /*
2454         if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
2455                 mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
2456          */
2457         if (val.mag.length < BORINGSSL_DIV_THRESHOLD ||
2458                 mag.length - val.mag.length < BORINGSSL_DIV_THRESHOLD) {
2459             return remainderKnuth(val);
2460         } else {
2461             /*
2462             return remainderBurnikelZiegler(val);
2463             */
2464             return divideAndRemainder(val)[1];
2465         }
2466         // END Android-changed: Fall back to boringssl for large problems.
2467     }
2468 
2469     /** Long division */
remainderKnuth(BigInteger val)2470     private BigInteger remainderKnuth(BigInteger val) {
2471         MutableBigInteger q = new MutableBigInteger(),
2472                           a = new MutableBigInteger(this.mag),
2473                           b = new MutableBigInteger(val.mag);
2474 
2475         return a.divideKnuth(b, q).toBigInteger(this.signum);
2476     }
2477 
2478     /**
2479      * Calculates {@code this / val} using the Burnikel-Ziegler algorithm.
2480      * @param  val the divisor
2481      * @return {@code this / val}
2482      */
divideBurnikelZiegler(BigInteger val)2483     private BigInteger divideBurnikelZiegler(BigInteger val) {
2484         return divideAndRemainderBurnikelZiegler(val)[0];
2485     }
2486 
2487     /**
2488      * Calculates {@code this % val} using the Burnikel-Ziegler algorithm.
2489      * @param val the divisor
2490      * @return {@code this % val}
2491      */
remainderBurnikelZiegler(BigInteger val)2492     private BigInteger remainderBurnikelZiegler(BigInteger val) {
2493         return divideAndRemainderBurnikelZiegler(val)[1];
2494     }
2495 
2496     /**
2497      * Computes {@code this / val} and {@code this % val} using the
2498      * Burnikel-Ziegler algorithm.
2499      * @param val the divisor
2500      * @return an array containing the quotient and remainder
2501      */
divideAndRemainderBurnikelZiegler(BigInteger val)2502     private BigInteger[] divideAndRemainderBurnikelZiegler(BigInteger val) {
2503         MutableBigInteger q = new MutableBigInteger();
2504         MutableBigInteger r = new MutableBigInteger(this).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q);
2505         BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum);
2506         BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum);
2507         return new BigInteger[] {qBigInt, rBigInt};
2508     }
2509 
2510     /**
2511      * Returns a BigInteger whose value is <code>(this<sup>exponent</sup>)</code>.
2512      * Note that {@code exponent} is an integer rather than a BigInteger.
2513      *
2514      * @param  exponent exponent to which this BigInteger is to be raised.
2515      * @return <code>this<sup>exponent</sup></code>
2516      * @throws ArithmeticException {@code exponent} is negative.  (This would
2517      *         cause the operation to yield a non-integer value.)
2518      */
pow(int exponent)2519     public BigInteger pow(int exponent) {
2520         if (exponent < 0) {
2521             throw new ArithmeticException("Negative exponent");
2522         }
2523         if (signum == 0) {
2524             return (exponent == 0 ? ONE : this);
2525         }
2526 
2527         BigInteger partToSquare = this.abs();
2528 
2529         // Factor out powers of two from the base, as the exponentiation of
2530         // these can be done by left shifts only.
2531         // The remaining part can then be exponentiated faster.  The
2532         // powers of two will be multiplied back at the end.
2533         int powersOfTwo = partToSquare.getLowestSetBit();
2534         long bitsToShiftLong = (long)powersOfTwo * exponent;
2535         if (bitsToShiftLong > Integer.MAX_VALUE) {
2536             reportOverflow();
2537         }
2538         int bitsToShift = (int)bitsToShiftLong;
2539 
2540         int remainingBits;
2541 
2542         // Factor the powers of two out quickly by shifting right, if needed.
2543         if (powersOfTwo > 0) {
2544             partToSquare = partToSquare.shiftRight(powersOfTwo);
2545             remainingBits = partToSquare.bitLength();
2546             if (remainingBits == 1) {  // Nothing left but +/- 1?
2547                 if (signum < 0 && (exponent&1) == 1) {
2548                     return NEGATIVE_ONE.shiftLeft(bitsToShift);
2549                 } else {
2550                     return ONE.shiftLeft(bitsToShift);
2551                 }
2552             }
2553         } else {
2554             remainingBits = partToSquare.bitLength();
2555             if (remainingBits == 1) { // Nothing left but +/- 1?
2556                 if (signum < 0  && (exponent&1) == 1) {
2557                     return NEGATIVE_ONE;
2558                 } else {
2559                     return ONE;
2560                 }
2561             }
2562         }
2563 
2564         // This is a quick way to approximate the size of the result,
2565         // similar to doing log2[n] * exponent.  This will give an upper bound
2566         // of how big the result can be, and which algorithm to use.
2567         long scaleFactor = (long)remainingBits * exponent;
2568 
2569         // Use slightly different algorithms for small and large operands.
2570         // See if the result will safely fit into a long. (Largest 2^63-1)
2571         if (partToSquare.mag.length == 1 && scaleFactor <= 62) {
2572             // Small number algorithm.  Everything fits into a long.
2573             int newSign = (signum <0  && (exponent&1) == 1 ? -1 : 1);
2574             long result = 1;
2575             long baseToPow2 = partToSquare.mag[0] & LONG_MASK;
2576 
2577             int workingExponent = exponent;
2578 
2579             // Perform exponentiation using repeated squaring trick
2580             while (workingExponent != 0) {
2581                 if ((workingExponent & 1) == 1) {
2582                     result = result * baseToPow2;
2583                 }
2584 
2585                 if ((workingExponent >>>= 1) != 0) {
2586                     baseToPow2 = baseToPow2 * baseToPow2;
2587                 }
2588             }
2589 
2590             // Multiply back the powers of two (quickly, by shifting left)
2591             if (powersOfTwo > 0) {
2592                 if (bitsToShift + scaleFactor <= 62) { // Fits in long?
2593                     return valueOf((result << bitsToShift) * newSign);
2594                 } else {
2595                     return valueOf(result*newSign).shiftLeft(bitsToShift);
2596                 }
2597             } else {
2598                 return valueOf(result*newSign);
2599             }
2600         } else {
2601             if ((long)bitLength() * exponent / Integer.SIZE > MAX_MAG_LENGTH) {
2602                 reportOverflow();
2603             }
2604 
2605             // Large number algorithm.  This is basically identical to
2606             // the algorithm above, but calls multiply() and square()
2607             // which may use more efficient algorithms for large numbers.
2608             BigInteger answer = ONE;
2609 
2610             int workingExponent = exponent;
2611             // Perform exponentiation using repeated squaring trick
2612             while (workingExponent != 0) {
2613                 if ((workingExponent & 1) == 1) {
2614                     answer = answer.multiply(partToSquare);
2615                 }
2616 
2617                 if ((workingExponent >>>= 1) != 0) {
2618                     partToSquare = partToSquare.square();
2619                 }
2620             }
2621             // Multiply back the (exponentiated) powers of two (quickly,
2622             // by shifting left)
2623             if (powersOfTwo > 0) {
2624                 answer = answer.shiftLeft(bitsToShift);
2625             }
2626 
2627             if (signum < 0 && (exponent&1) == 1) {
2628                 return answer.negate();
2629             } else {
2630                 return answer;
2631             }
2632         }
2633     }
2634 
2635     /**
2636      * Returns the integer square root of this BigInteger.  The integer square
2637      * root of the corresponding mathematical integer {@code n} is the largest
2638      * mathematical integer {@code s} such that {@code s*s <= n}.  It is equal
2639      * to the value of {@code floor(sqrt(n))}, where {@code sqrt(n)} denotes the
2640      * real square root of {@code n} treated as a real.  Note that the integer
2641      * square root will be less than the real square root if the latter is not
2642      * representable as an integral value.
2643      *
2644      * @return the integer square root of {@code this}
2645      * @throws ArithmeticException if {@code this} is negative.  (The square
2646      *         root of a negative integer {@code val} is
2647      *         {@code (i * sqrt(-val))} where <i>i</i> is the
2648      *         <i>imaginary unit</i> and is equal to
2649      *         {@code sqrt(-1)}.)
2650      * @since  9
2651      */
sqrt()2652     public BigInteger sqrt() {
2653         if (this.signum < 0) {
2654             throw new ArithmeticException("Negative BigInteger");
2655         }
2656 
2657         return new MutableBigInteger(this.mag).sqrt().toBigInteger();
2658     }
2659 
2660     /**
2661      * Returns an array of two BigIntegers containing the integer square root
2662      * {@code s} of {@code this} and its remainder {@code this - s*s},
2663      * respectively.
2664      *
2665      * @return an array of two BigIntegers with the integer square root at
2666      *         offset 0 and the remainder at offset 1
2667      * @throws ArithmeticException if {@code this} is negative.  (The square
2668      *         root of a negative integer {@code val} is
2669      *         {@code (i * sqrt(-val))} where <i>i</i> is the
2670      *         <i>imaginary unit</i> and is equal to
2671      *         {@code sqrt(-1)}.)
2672      * @see #sqrt()
2673      * @since  9
2674      */
sqrtAndRemainder()2675     public BigInteger[] sqrtAndRemainder() {
2676         BigInteger s = sqrt();
2677         BigInteger r = this.subtract(s.square());
2678         assert r.compareTo(BigInteger.ZERO) >= 0;
2679         return new BigInteger[] {s, r};
2680     }
2681 
2682     /**
2683      * Returns a BigInteger whose value is the greatest common divisor of
2684      * {@code abs(this)} and {@code abs(val)}.  Returns 0 if
2685      * {@code this == 0 && val == 0}.
2686      *
2687      * @param  val value with which the GCD is to be computed.
2688      * @return {@code GCD(abs(this), abs(val))}
2689      */
gcd(BigInteger val)2690     public BigInteger gcd(BigInteger val) {
2691         if (val.signum == 0)
2692             return this.abs();
2693         else if (this.signum == 0)
2694             return val.abs();
2695 
2696         MutableBigInteger a = new MutableBigInteger(this);
2697         MutableBigInteger b = new MutableBigInteger(val);
2698 
2699         MutableBigInteger result = a.hybridGCD(b);
2700 
2701         return result.toBigInteger(1);
2702     }
2703 
2704     /**
2705      * Package private method to return bit length for an integer.
2706      */
bitLengthForInt(int n)2707     static int bitLengthForInt(int n) {
2708         return 32 - Integer.numberOfLeadingZeros(n);
2709     }
2710 
2711     /**
2712      * Left shift int array a up to len by n bits. Returns the array that
2713      * results from the shift since space may have to be reallocated.
2714      */
leftShift(int[] a, int len, int n)2715     private static int[] leftShift(int[] a, int len, int n) {
2716         int nInts = n >>> 5;
2717         int nBits = n&0x1F;
2718         int bitsInHighWord = bitLengthForInt(a[0]);
2719 
2720         // If shift can be done without recopy, do so
2721         if (n <= (32-bitsInHighWord)) {
2722             primitiveLeftShift(a, len, nBits);
2723             return a;
2724         } else { // Array must be resized
2725             if (nBits <= (32-bitsInHighWord)) {
2726                 int result[] = new int[nInts+len];
2727                 System.arraycopy(a, 0, result, 0, len);
2728                 primitiveLeftShift(result, result.length, nBits);
2729                 return result;
2730             } else {
2731                 int result[] = new int[nInts+len+1];
2732                 System.arraycopy(a, 0, result, 0, len);
2733                 primitiveRightShift(result, result.length, 32 - nBits);
2734                 return result;
2735             }
2736         }
2737     }
2738 
2739     // shifts a up to len right n bits assumes no leading zeros, 0<n<32
primitiveRightShift(int[] a, int len, int n)2740     static void primitiveRightShift(int[] a, int len, int n) {
2741         Objects.checkFromToIndex(0, len, a.length);
2742         shiftRightImplWorker(a, a, 1, n, len-1);
2743         a[0] >>>= n;
2744     }
2745 
2746     // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
primitiveLeftShift(int[] a, int len, int n)2747     static void primitiveLeftShift(int[] a, int len, int n) {
2748         if (len == 0 || n == 0)
2749             return;
2750         Objects.checkFromToIndex(0, len, a.length);
2751         shiftLeftImplWorker(a, a, 0, n, len-1);
2752         a[len-1] <<= n;
2753     }
2754 
2755     /**
2756      * Calculate bitlength of contents of the first len elements an int array,
2757      * assuming there are no leading zero ints.
2758      */
bitLength(int[] val, int len)2759     private static int bitLength(int[] val, int len) {
2760         if (len == 0)
2761             return 0;
2762         return ((len - 1) << 5) + bitLengthForInt(val[0]);
2763     }
2764 
2765     /**
2766      * Returns a BigInteger whose value is the absolute value of this
2767      * BigInteger.
2768      *
2769      * @return {@code abs(this)}
2770      */
abs()2771     public BigInteger abs() {
2772         return (signum >= 0 ? this : this.negate());
2773     }
2774 
2775     /**
2776      * Returns a BigInteger whose value is {@code (-this)}.
2777      *
2778      * @return {@code -this}
2779      */
negate()2780     public BigInteger negate() {
2781         return new BigInteger(this.mag, -this.signum);
2782     }
2783 
2784     /**
2785      * Returns the signum function of this BigInteger.
2786      *
2787      * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or
2788      *         positive.
2789      */
signum()2790     public int signum() {
2791         return this.signum;
2792     }
2793 
2794     // Modular Arithmetic Operations
2795 
2796     /**
2797      * Returns a BigInteger whose value is {@code (this mod m}).  This method
2798      * differs from {@code remainder} in that it always returns a
2799      * <i>non-negative</i> BigInteger.
2800      *
2801      * @param  m the modulus.
2802      * @return {@code this mod m}
2803      * @throws ArithmeticException {@code m} &le; 0
2804      * @see    #remainder
2805      */
mod(BigInteger m)2806     public BigInteger mod(BigInteger m) {
2807         if (m.signum <= 0)
2808             throw new ArithmeticException("BigInteger: modulus not positive");
2809 
2810         BigInteger result = this.remainder(m);
2811         return (result.signum >= 0 ? result : result.add(m));
2812     }
2813 
2814     // BEGIN Android-added: Support fallback to boringssl where it makes sense.
2815     // The conversion itself takes linear time, so this only makes sense for largish superlinear
2816     // operations.
2817 
reverse(int[] arg)2818     private static int[] reverse(int[] arg) {
2819       int len = arg.length;
2820       int[] result = new int[len];
2821       for (int i = 0; i < len; ++i) {
2822         result[i] = arg[len - i - 1];
2823       }
2824       return result;
2825     }
2826 
bigEndInts2NewBN(int[] beArray, boolean neg)2827     private static long /* BN */ bigEndInts2NewBN(int[] beArray, boolean neg) {
2828       // The input is an array of ints arranged in big-endian order, i.e. most significant int
2829       // first. BN deals with big-endian or little-endian byte arrays, so we need to reverse order.
2830       int[] leArray = reverse(beArray);
2831       long resultBN = NativeBN.BN_new();
2832       NativeBN.litEndInts2bn(leArray, leArray.length, neg, resultBN);
2833       return resultBN;
2834     }
2835 
bn2BigEndInts(long bn)2836     private int[] bn2BigEndInts(long bn) {
2837       return reverse(NativeBN.bn2litEndInts(bn));
2838     }
2839 
2840     // END Android-added: Support fallback to boringssl.
2841 
2842 
2843     /**
2844      * Returns a BigInteger whose value is
2845      * <code>(this<sup>exponent</sup> mod m)</code>.  (Unlike {@code pow}, this
2846      * method permits negative exponents.)
2847      *
2848      * @param  exponent the exponent.
2849      * @param  m the modulus.
2850      * @return <code>this<sup>exponent</sup> mod m</code>
2851      * @throws ArithmeticException {@code m} &le; 0 or the exponent is
2852      *         negative and this BigInteger is not <i>relatively
2853      *         prime</i> to {@code m}.
2854      * @see    #modInverse
2855      */
modPow(BigInteger exponent, BigInteger m)2856     public BigInteger modPow(BigInteger exponent, BigInteger m) {
2857         if (m.signum <= 0)
2858             throw new ArithmeticException("BigInteger: modulus not positive");
2859 
2860         // Trivial cases
2861         if (exponent.signum == 0)
2862             return (m.equals(ONE) ? ZERO : ONE);
2863 
2864         if (this.equals(ONE))
2865             return (m.equals(ONE) ? ZERO : ONE);
2866 
2867         if (this.equals(ZERO) && exponent.signum >= 0)
2868             return ZERO;
2869 
2870         if (this.equals(negConst[1]) && (!exponent.testBit(0)))
2871             return (m.equals(ONE) ? ZERO : ONE);
2872 
2873         boolean invertResult;
2874         if ((invertResult = (exponent.signum < 0)))
2875             exponent = exponent.negate();
2876 
2877         BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
2878                            ? this.mod(m) : this);
2879         BigInteger result;
2880         // BEGIN Android-added: Fall back to the boringssl implementation, which
2881         // is usually faster.
2882         final int BORINGSSL_MOD_EXP_THRESHOLD = 3;
2883         if (m.mag.length >= BORINGSSL_MOD_EXP_THRESHOLD) {
2884             long baseBN = 0, expBN = 0, modBN = 0, resultBN = 0;
2885             try {
2886                 baseBN = bigEndInts2NewBN(base.mag, /* neg= */false);
2887                 expBN = bigEndInts2NewBN(exponent.mag, /* neg= */false);
2888                 modBN = bigEndInts2NewBN(m.mag, /* neg= */false);
2889                 resultBN = NativeBN.BN_new();
2890                 NativeBN.BN_mod_exp(resultBN, baseBN, expBN, modBN);
2891                 result = new BigInteger(1, bn2BigEndInts(resultBN));
2892                         // The sign of a zero result is fixed by the constructor.
2893                 return (invertResult ? result.modInverse(m) : result);
2894             } finally {
2895                 NativeBN.BN_free(baseBN);
2896                 NativeBN.BN_free(expBN);
2897                 NativeBN.BN_free(modBN);
2898                 NativeBN.BN_free(resultBN);
2899             }
2900         }
2901         // END Android-added: Fall back to the boringssl implementation.
2902         if (m.testBit(0)) { // odd modulus
2903             result = base.oddModPow(exponent, m);
2904         } else {
2905             /*
2906              * Even modulus.  Tear it into an "odd part" (m1) and power of two
2907              * (m2), exponentiate mod m1, manually exponentiate mod m2, and
2908              * use Chinese Remainder Theorem to combine results.
2909              */
2910 
2911             // Tear m apart into odd part (m1) and power of 2 (m2)
2912             int p = m.getLowestSetBit();   // Max pow of 2 that divides m
2913 
2914             BigInteger m1 = m.shiftRight(p);  // m/2**p
2915             BigInteger m2 = ONE.shiftLeft(p); // 2**p
2916 
2917             // Calculate new base from m1
2918             BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0
2919                                 ? this.mod(m1) : this);
2920 
2921             // Calculate (base ** exponent) mod m1.
2922             BigInteger a1 = (m1.equals(ONE) ? ZERO :
2923                              base2.oddModPow(exponent, m1));
2924 
2925             // Calculate (this ** exponent) mod m2
2926             BigInteger a2 = base.modPow2(exponent, p);
2927 
2928             // Combine results using Chinese Remainder Theorem
2929             BigInteger y1 = m2.modInverse(m1);
2930             BigInteger y2 = m1.modInverse(m2);
2931 
2932             if (m.mag.length < MAX_MAG_LENGTH / 2) {
2933                 result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);
2934             } else {
2935                 MutableBigInteger t1 = new MutableBigInteger();
2936                 new MutableBigInteger(a1.multiply(m2)).multiply(new MutableBigInteger(y1), t1);
2937                 MutableBigInteger t2 = new MutableBigInteger();
2938                 new MutableBigInteger(a2.multiply(m1)).multiply(new MutableBigInteger(y2), t2);
2939                 t1.add(t2);
2940                 MutableBigInteger q = new MutableBigInteger();
2941                 result = t1.divide(new MutableBigInteger(m), q).toBigInteger();
2942             }
2943         }
2944 
2945         return (invertResult ? result.modInverse(m) : result);
2946     }
2947 
2948     // Montgomery multiplication.  These are wrappers for
2949     // implMontgomeryXX routines which are expected to be replaced by
2950     // virtual machine intrinsics.  We don't use the intrinsics for
2951     // very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be
2952     // larger than any reasonable crypto key.
montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv, int[] product)2953     private static int[] montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv,
2954                                             int[] product) {
2955         implMontgomeryMultiplyChecks(a, b, n, len, product);
2956         if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
2957             // Very long argument: do not use an intrinsic
2958             product = multiplyToLen(a, len, b, len, product);
2959             return montReduce(product, n, len, (int)inv);
2960         } else {
2961             return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len));
2962         }
2963     }
montgomerySquare(int[] a, int[] n, int len, long inv, int[] product)2964     private static int[] montgomerySquare(int[] a, int[] n, int len, long inv,
2965                                           int[] product) {
2966         implMontgomeryMultiplyChecks(a, a, n, len, product);
2967         if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
2968             // Very long argument: do not use an intrinsic
2969             product = squareToLen(a, len, product);
2970             return montReduce(product, n, len, (int)inv);
2971         } else {
2972             return implMontgomerySquare(a, n, len, inv, materialize(product, len));
2973         }
2974     }
2975 
2976     // Range-check everything.
implMontgomeryMultiplyChecks(int[] a, int[] b, int[] n, int len, int[] product)2977     private static void implMontgomeryMultiplyChecks
2978         (int[] a, int[] b, int[] n, int len, int[] product) throws RuntimeException {
2979         if (len % 2 != 0) {
2980             throw new IllegalArgumentException("input array length must be even: " + len);
2981         }
2982 
2983         if (len < 1) {
2984             throw new IllegalArgumentException("invalid input length: " + len);
2985         }
2986 
2987         if (len > a.length ||
2988             len > b.length ||
2989             len > n.length ||
2990             (product != null && len > product.length)) {
2991             throw new IllegalArgumentException("input array length out of bound: " + len);
2992         }
2993     }
2994 
2995     // Make sure that the int array z (which is expected to contain
2996     // the result of a Montgomery multiplication) is present and
2997     // sufficiently large.
materialize(int[] z, int len)2998     private static int[] materialize(int[] z, int len) {
2999          if (z == null || z.length < len)
3000              z = new int[len];
3001          return z;
3002     }
3003 
3004     // These methods are intended to be replaced by virtual machine
3005     // intrinsics.
3006     @IntrinsicCandidate
implMontgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv, int[] product)3007     private static int[] implMontgomeryMultiply(int[] a, int[] b, int[] n, int len,
3008                                          long inv, int[] product) {
3009         product = multiplyToLen(a, len, b, len, product);
3010         return montReduce(product, n, len, (int)inv);
3011     }
3012     @IntrinsicCandidate
implMontgomerySquare(int[] a, int[] n, int len, long inv, int[] product)3013     private static int[] implMontgomerySquare(int[] a, int[] n, int len,
3014                                        long inv, int[] product) {
3015         product = squareToLen(a, len, product);
3016         return montReduce(product, n, len, (int)inv);
3017     }
3018 
3019     static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,
3020                                                 Integer.MAX_VALUE}; // Sentinel
3021 
3022     /**
3023      * Returns a BigInteger whose value is x to the power of y mod z.
3024      * Assumes: z is odd && x < z.
3025      */
oddModPow(BigInteger y, BigInteger z)3026     private BigInteger oddModPow(BigInteger y, BigInteger z) {
3027     /*
3028      * The algorithm is adapted from Colin Plumb's C library.
3029      *
3030      * The window algorithm:
3031      * The idea is to keep a running product of b1 = n^(high-order bits of exp)
3032      * and then keep appending exponent bits to it.  The following patterns
3033      * apply to a 3-bit window (k = 3):
3034      * To append   0: square
3035      * To append   1: square, multiply by n^1
3036      * To append  10: square, multiply by n^1, square
3037      * To append  11: square, square, multiply by n^3
3038      * To append 100: square, multiply by n^1, square, square
3039      * To append 101: square, square, square, multiply by n^5
3040      * To append 110: square, square, multiply by n^3, square
3041      * To append 111: square, square, square, multiply by n^7
3042      *
3043      * Since each pattern involves only one multiply, the longer the pattern
3044      * the better, except that a 0 (no multiplies) can be appended directly.
3045      * We precompute a table of odd powers of n, up to 2^k, and can then
3046      * multiply k bits of exponent at a time.  Actually, assuming random
3047      * exponents, there is on average one zero bit between needs to
3048      * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
3049      * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so
3050      * you have to do one multiply per k+1 bits of exponent.
3051      *
3052      * The loop walks down the exponent, squaring the result buffer as
3053      * it goes.  There is a wbits+1 bit lookahead buffer, buf, that is
3054      * filled with the upcoming exponent bits.  (What is read after the
3055      * end of the exponent is unimportant, but it is filled with zero here.)
3056      * When the most-significant bit of this buffer becomes set, i.e.
3057      * (buf & tblmask) != 0, we have to decide what pattern to multiply
3058      * by, and when to do it.  We decide, remember to do it in future
3059      * after a suitable number of squarings have passed (e.g. a pattern
3060      * of "100" in the buffer requires that we multiply by n^1 immediately;
3061      * a pattern of "110" calls for multiplying by n^3 after one more
3062      * squaring), clear the buffer, and continue.
3063      *
3064      * When we start, there is one more optimization: the result buffer
3065      * is implcitly one, so squaring it or multiplying by it can be
3066      * optimized away.  Further, if we start with a pattern like "100"
3067      * in the lookahead window, rather than placing n into the buffer
3068      * and then starting to square it, we have already computed n^2
3069      * to compute the odd-powers table, so we can place that into
3070      * the buffer and save a squaring.
3071      *
3072      * This means that if you have a k-bit window, to compute n^z,
3073      * where z is the high k bits of the exponent, 1/2 of the time
3074      * it requires no squarings.  1/4 of the time, it requires 1
3075      * squaring, ... 1/2^(k-1) of the time, it requires k-2 squarings.
3076      * And the remaining 1/2^(k-1) of the time, the top k bits are a
3077      * 1 followed by k-1 0 bits, so it again only requires k-2
3078      * squarings, not k-1.  The average of these is 1.  Add that
3079      * to the one squaring we have to do to compute the table,
3080      * and you'll see that a k-bit window saves k-2 squarings
3081      * as well as reducing the multiplies.  (It actually doesn't
3082      * hurt in the case k = 1, either.)
3083      */
3084         // Special case for exponent of one
3085         if (y.equals(ONE))
3086             return this;
3087 
3088         // Special case for base of zero
3089         if (signum == 0)
3090             return ZERO;
3091 
3092         int[] base = mag.clone();
3093         int[] exp = y.mag;
3094         int[] mod = z.mag;
3095         int modLen = mod.length;
3096 
3097         // Make modLen even. It is conventional to use a cryptographic
3098         // modulus that is 512, 768, 1024, or 2048 bits, so this code
3099         // will not normally be executed. However, it is necessary for
3100         // the correct functioning of the HotSpot intrinsics.
3101         if ((modLen & 1) != 0) {
3102             int[] x = new int[modLen + 1];
3103             System.arraycopy(mod, 0, x, 1, modLen);
3104             mod = x;
3105             modLen++;
3106         }
3107 
3108         // Select an appropriate window size
3109         int wbits = 0;
3110         int ebits = bitLength(exp, exp.length);
3111         // if exponent is 65537 (0x10001), use minimum window size
3112         if ((ebits != 17) || (exp[0] != 65537)) {
3113             while (ebits > bnExpModThreshTable[wbits]) {
3114                 wbits++;
3115             }
3116         }
3117 
3118         // Calculate appropriate table size
3119         int tblmask = 1 << wbits;
3120 
3121         // Allocate table for precomputed odd powers of base in Montgomery form
3122         int[][] table = new int[tblmask][];
3123         for (int i=0; i < tblmask; i++)
3124             table[i] = new int[modLen];
3125 
3126         // Compute the modular inverse of the least significant 64-bit
3127         // digit of the modulus
3128         long n0 = (mod[modLen-1] & LONG_MASK) + ((mod[modLen-2] & LONG_MASK) << 32);
3129         long inv = -MutableBigInteger.inverseMod64(n0);
3130 
3131         // Convert base to Montgomery form
3132         int[] a = leftShift(base, base.length, modLen << 5);
3133 
3134         MutableBigInteger q = new MutableBigInteger(),
3135                           a2 = new MutableBigInteger(a),
3136                           b2 = new MutableBigInteger(mod);
3137         b2.normalize(); // MutableBigInteger.divide() assumes that its
3138                         // divisor is in normal form.
3139 
3140         MutableBigInteger r= a2.divide(b2, q);
3141         table[0] = r.toIntArray();
3142 
3143         // Pad table[0] with leading zeros so its length is at least modLen
3144         if (table[0].length < modLen) {
3145            int offset = modLen - table[0].length;
3146            int[] t2 = new int[modLen];
3147            System.arraycopy(table[0], 0, t2, offset, table[0].length);
3148            table[0] = t2;
3149         }
3150 
3151         // Set b to the square of the base
3152         int[] b = montgomerySquare(table[0], mod, modLen, inv, null);
3153 
3154         // Set t to high half of b
3155         int[] t = Arrays.copyOf(b, modLen);
3156 
3157         // Fill in the table with odd powers of the base
3158         for (int i=1; i < tblmask; i++) {
3159             table[i] = montgomeryMultiply(t, table[i-1], mod, modLen, inv, null);
3160         }
3161 
3162         // Pre load the window that slides over the exponent
3163         int bitpos = 1 << ((ebits-1) & (32-1));
3164 
3165         int buf = 0;
3166         int elen = exp.length;
3167         int eIndex = 0;
3168         for (int i = 0; i <= wbits; i++) {
3169             buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);
3170             bitpos >>>= 1;
3171             if (bitpos == 0) {
3172                 eIndex++;
3173                 bitpos = 1 << (32-1);
3174                 elen--;
3175             }
3176         }
3177 
3178         int multpos = ebits;
3179 
3180         // The first iteration, which is hoisted out of the main loop
3181         ebits--;
3182         boolean isone = true;
3183 
3184         multpos = ebits - wbits;
3185         while ((buf & 1) == 0) {
3186             buf >>>= 1;
3187             multpos++;
3188         }
3189 
3190         int[] mult = table[buf >>> 1];
3191 
3192         buf = 0;
3193         if (multpos == ebits)
3194             isone = false;
3195 
3196         // The main loop
3197         while (true) {
3198             ebits--;
3199             // Advance the window
3200             buf <<= 1;
3201 
3202             if (elen != 0) {
3203                 buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
3204                 bitpos >>>= 1;
3205                 if (bitpos == 0) {
3206                     eIndex++;
3207                     bitpos = 1 << (32-1);
3208                     elen--;
3209                 }
3210             }
3211 
3212             // Examine the window for pending multiplies
3213             if ((buf & tblmask) != 0) {
3214                 multpos = ebits - wbits;
3215                 while ((buf & 1) == 0) {
3216                     buf >>>= 1;
3217                     multpos++;
3218                 }
3219                 mult = table[buf >>> 1];
3220                 buf = 0;
3221             }
3222 
3223             // Perform multiply
3224             if (ebits == multpos) {
3225                 if (isone) {
3226                     b = mult.clone();
3227                     isone = false;
3228                 } else {
3229                     t = b;
3230                     a = montgomeryMultiply(t, mult, mod, modLen, inv, a);
3231                     t = a; a = b; b = t;
3232                 }
3233             }
3234 
3235             // Check if done
3236             if (ebits == 0)
3237                 break;
3238 
3239             // Square the input
3240             if (!isone) {
3241                 t = b;
3242                 a = montgomerySquare(t, mod, modLen, inv, a);
3243                 t = a; a = b; b = t;
3244             }
3245         }
3246 
3247         // Convert result out of Montgomery form and return
3248         int[] t2 = new int[2*modLen];
3249         System.arraycopy(b, 0, t2, modLen, modLen);
3250 
3251         b = montReduce(t2, mod, modLen, (int)inv);
3252 
3253         t2 = Arrays.copyOf(b, modLen);
3254 
3255         return new BigInteger(1, t2);
3256     }
3257 
3258     /**
3259      * Montgomery reduce n, modulo mod.  This reduces modulo mod and divides
3260      * by 2^(32*mlen). Adapted from Colin Plumb's C library.
3261      */
montReduce(int[] n, int[] mod, int mlen, int inv)3262     private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {
3263         int c=0;
3264         int len = mlen;
3265         int offset=0;
3266 
3267         do {
3268             int nEnd = n[n.length-1-offset];
3269             int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
3270             c += addOne(n, offset, mlen, carry);
3271             offset++;
3272         } while (--len > 0);
3273 
3274         while (c > 0)
3275             c += subN(n, mod, mlen);
3276 
3277         while (intArrayCmpToLen(n, mod, mlen) >= 0)
3278             subN(n, mod, mlen);
3279 
3280         return n;
3281     }
3282 
3283 
3284     /*
3285      * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,
3286      * equal to, or greater than arg2 up to length len.
3287      */
intArrayCmpToLen(int[] arg1, int[] arg2, int len)3288     private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
3289         for (int i=0; i < len; i++) {
3290             long b1 = arg1[i] & LONG_MASK;
3291             long b2 = arg2[i] & LONG_MASK;
3292             if (b1 < b2)
3293                 return -1;
3294             if (b1 > b2)
3295                 return 1;
3296         }
3297         return 0;
3298     }
3299 
3300     /**
3301      * Subtracts two numbers of same length, returning borrow.
3302      */
subN(int[] a, int[] b, int len)3303     private static int subN(int[] a, int[] b, int len) {
3304         long sum = 0;
3305 
3306         while (--len >= 0) {
3307             sum = (a[len] & LONG_MASK) -
3308                  (b[len] & LONG_MASK) + (sum >> 32);
3309             a[len] = (int)sum;
3310         }
3311 
3312         return (int)(sum >> 32);
3313     }
3314 
3315     /**
3316      * Multiply an array by one word k and add to result, return the carry
3317      */
mulAdd(int[] out, int[] in, int offset, int len, int k)3318     static int mulAdd(int[] out, int[] in, int offset, int len, int k) {
3319         implMulAddCheck(out, in, offset, len, k);
3320         return implMulAdd(out, in, offset, len, k);
3321     }
3322 
3323     /**
3324      * Parameters validation.
3325      */
implMulAddCheck(int[] out, int[] in, int offset, int len, int k)3326     private static void implMulAddCheck(int[] out, int[] in, int offset, int len, int k) {
3327         if (len > in.length) {
3328             throw new IllegalArgumentException("input length is out of bound: " + len + " > " + in.length);
3329         }
3330         if (offset < 0) {
3331             throw new IllegalArgumentException("input offset is invalid: " + offset);
3332         }
3333         if (offset > (out.length - 1)) {
3334             throw new IllegalArgumentException("input offset is out of bound: " + offset + " > " + (out.length - 1));
3335         }
3336         if (len > (out.length - offset)) {
3337             throw new IllegalArgumentException("input len is out of bound: " + len + " > " + (out.length - offset));
3338         }
3339     }
3340 
3341     /**
3342      * Java Runtime may use intrinsic for this method.
3343      */
3344     @IntrinsicCandidate
implMulAdd(int[] out, int[] in, int offset, int len, int k)3345     private static int implMulAdd(int[] out, int[] in, int offset, int len, int k) {
3346         long kLong = k & LONG_MASK;
3347         long carry = 0;
3348 
3349         offset = out.length-offset - 1;
3350         for (int j=len-1; j >= 0; j--) {
3351             long product = (in[j] & LONG_MASK) * kLong +
3352                            (out[offset] & LONG_MASK) + carry;
3353             out[offset--] = (int)product;
3354             carry = product >>> 32;
3355         }
3356         return (int)carry;
3357     }
3358 
3359     /**
3360      * Add one word to the number a mlen words into a. Return the resulting
3361      * carry.
3362      */
addOne(int[] a, int offset, int mlen, int carry)3363     static int addOne(int[] a, int offset, int mlen, int carry) {
3364         offset = a.length-1-mlen-offset;
3365         long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);
3366 
3367         a[offset] = (int)t;
3368         if ((t >>> 32) == 0)
3369             return 0;
3370         while (--mlen >= 0) {
3371             if (--offset < 0) { // Carry out of number
3372                 return 1;
3373             } else {
3374                 a[offset]++;
3375                 if (a[offset] != 0)
3376                     return 0;
3377             }
3378         }
3379         return 1;
3380     }
3381 
3382     /**
3383      * Returns a BigInteger whose value is (this ** exponent) mod (2**p)
3384      */
modPow2(BigInteger exponent, int p)3385     private BigInteger modPow2(BigInteger exponent, int p) {
3386         /*
3387          * Perform exponentiation using repeated squaring trick, chopping off
3388          * high order bits as indicated by modulus.
3389          */
3390         BigInteger result = ONE;
3391         BigInteger baseToPow2 = this.mod2(p);
3392         int expOffset = 0;
3393 
3394         int limit = exponent.bitLength();
3395 
3396         if (this.testBit(0))
3397            limit = (p-1) < limit ? (p-1) : limit;
3398 
3399         while (expOffset < limit) {
3400             if (exponent.testBit(expOffset))
3401                 result = result.multiply(baseToPow2).mod2(p);
3402             expOffset++;
3403             if (expOffset < limit)
3404                 baseToPow2 = baseToPow2.square().mod2(p);
3405         }
3406 
3407         return result;
3408     }
3409 
3410     /**
3411      * Returns a BigInteger whose value is this mod(2**p).
3412      * Assumes that this {@code BigInteger >= 0} and {@code p > 0}.
3413      */
3414     private BigInteger mod2(int p) {
3415         if (bitLength() <= p)
3416             return this;
3417 
3418         // Copy remaining ints of mag
3419         int numInts = (p + 31) >>> 5;
3420         int[] mag = new int[numInts];
3421         System.arraycopy(this.mag, (this.mag.length - numInts), mag, 0, numInts);
3422 
3423         // Mask out any excess bits
3424         int excessBits = (numInts << 5) - p;
3425         mag[0] &= (1L << (32-excessBits)) - 1;
3426 
3427         return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
3428     }
3429 
3430     /**
3431      * Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}.
3432      *
3433      * @param  m the modulus.
3434      * @return {@code this}<sup>-1</sup> {@code mod m}.
3435      * @throws ArithmeticException {@code  m} &le; 0, or this BigInteger
3436      *         has no multiplicative inverse mod m (that is, this BigInteger
3437      *         is not <i>relatively prime</i> to m).
3438      */
3439     public BigInteger modInverse(BigInteger m) {
3440         if (m.signum != 1)
3441             throw new ArithmeticException("BigInteger: modulus not positive");
3442 
3443         if (m.equals(ONE))
3444             return ZERO;
3445 
3446         // Calculate (this mod m)
3447         BigInteger modVal = this;
3448         if (signum < 0 || (this.compareMagnitude(m) >= 0))
3449             modVal = this.mod(m);
3450 
3451         if (modVal.equals(ONE))
3452             return ONE;
3453 
3454         MutableBigInteger a = new MutableBigInteger(modVal);
3455         MutableBigInteger b = new MutableBigInteger(m);
3456 
3457         MutableBigInteger result = a.mutableModInverse(b);
3458         return result.toBigInteger(1);
3459     }
3460 
3461     // Shift Operations
3462 
3463     /**
3464      * Returns a BigInteger whose value is {@code (this << n)}.
3465      * The shift distance, {@code n}, may be negative, in which case
3466      * this method performs a right shift.
3467      * (Computes <code>floor(this * 2<sup>n</sup>)</code>.)
3468      *
3469      * @param  n shift distance, in bits.
3470      * @return {@code this << n}
3471      * @see #shiftRight
3472      */
3473     public BigInteger shiftLeft(int n) {
3474         if (signum == 0)
3475             return ZERO;
3476         if (n > 0) {
3477             return new BigInteger(shiftLeft(mag, n), signum);
3478         } else if (n == 0) {
3479             return this;
3480         } else {
3481             // Possible int overflow in (-n) is not a trouble,
3482             // because shiftRightImpl considers its argument unsigned
3483             return shiftRightImpl(-n);
3484         }
3485     }
3486 
3487     /**
3488      * Returns a magnitude array whose value is {@code (mag << n)}.
3489      * The shift distance, {@code n}, is considered unnsigned.
3490      * (Computes <code>this * 2<sup>n</sup></code>.)
3491      *
3492      * @param mag magnitude, the most-significant int ({@code mag[0]}) must be non-zero.
3493      * @param  n unsigned shift distance, in bits.
3494      * @return {@code mag << n}
3495      */
3496     private static int[] shiftLeft(int[] mag, int n) {
3497         int nInts = n >>> 5;
3498         int nBits = n & 0x1f;
3499         int magLen = mag.length;
3500         int newMag[] = null;
3501 
3502         if (nBits == 0) {
3503             newMag = new int[magLen + nInts];
3504             System.arraycopy(mag, 0, newMag, 0, magLen);
3505         } else {
3506             int i = 0;
3507             int nBits2 = 32 - nBits;
3508             int highBits = mag[0] >>> nBits2;
3509             if (highBits != 0) {
3510                 newMag = new int[magLen + nInts + 1];
3511                 newMag[i++] = highBits;
3512             } else {
3513                 newMag = new int[magLen + nInts];
3514             }
3515             int numIter = magLen - 1;
3516             Objects.checkFromToIndex(0, numIter + 1, mag.length);
3517             Objects.checkFromToIndex(i, numIter + i + 1, newMag.length);
3518             shiftLeftImplWorker(newMag, mag, i, nBits, numIter);
3519             newMag[numIter + i] = mag[numIter] << nBits;
3520         }
3521         return newMag;
3522     }
3523 
3524     private static void shiftLeftImplWorker(int[] newArr, int[] oldArr, int newIdx, int shiftCount, int numIter) {
3525         int shiftCountRight = 32 - shiftCount;
3526         int oldIdx = 0;
3527         while (oldIdx < numIter) {
3528             newArr[newIdx++] = (oldArr[oldIdx++] << shiftCount) | (oldArr[oldIdx] >>> shiftCountRight);
3529         }
3530     }
3531 
3532     /**
3533      * Returns a BigInteger whose value is {@code (this >> n)}.  Sign
3534      * extension is performed.  The shift distance, {@code n}, may be
3535      * negative, in which case this method performs a left shift.
3536      * (Computes <code>floor(this / 2<sup>n</sup>)</code>.)
3537      *
3538      * @param  n shift distance, in bits.
3539      * @return {@code this >> n}
3540      * @see #shiftLeft
3541      */
3542     public BigInteger shiftRight(int n) {
3543         if (signum == 0)
3544             return ZERO;
3545         if (n > 0) {
3546             return shiftRightImpl(n);
3547         } else if (n == 0) {
3548             return this;
3549         } else {
3550             // Possible int overflow in {@code -n} is not a trouble,
3551             // because shiftLeft considers its argument unsigned
3552             return new BigInteger(shiftLeft(mag, -n), signum);
3553         }
3554     }
3555 
3556     /**
3557      * Returns a BigInteger whose value is {@code (this >> n)}. The shift
3558      * distance, {@code n}, is considered unsigned.
3559      * (Computes <code>floor(this * 2<sup>-n</sup>)</code>.)
3560      *
3561      * @param  n unsigned shift distance, in bits.
3562      * @return {@code this >> n}
3563      */
3564     private BigInteger shiftRightImpl(int n) {
3565         int nInts = n >>> 5;
3566         int nBits = n & 0x1f;
3567         int magLen = mag.length;
3568         int newMag[] = null;
3569 
3570         // Special case: entire contents shifted off the end
3571         if (nInts >= magLen)
3572             return (signum >= 0 ? ZERO : negConst[1]);
3573 
3574         if (nBits == 0) {
3575             int newMagLen = magLen - nInts;
3576             newMag = Arrays.copyOf(mag, newMagLen);
3577         } else {
3578             int i = 0;
3579             int highBits = mag[0] >>> nBits;
3580             if (highBits != 0) {
3581                 newMag = new int[magLen - nInts];
3582                 newMag[i++] = highBits;
3583             } else {
3584                 newMag = new int[magLen - nInts -1];
3585             }
3586             int numIter = magLen - nInts - 1;
3587             Objects.checkFromToIndex(0, numIter + 1, mag.length);
3588             Objects.checkFromToIndex(i, numIter + i, newMag.length);
3589             shiftRightImplWorker(newMag, mag, i, nBits, numIter);
3590         }
3591 
3592         if (signum < 0) {
3593             // Find out whether any one-bits were shifted off the end.
3594             boolean onesLost = false;
3595             for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--)
3596                 onesLost = (mag[i] != 0);
3597             if (!onesLost && nBits != 0)
3598                 onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
3599 
3600             if (onesLost)
3601                 newMag = javaIncrement(newMag);
3602         }
3603 
3604         return new BigInteger(newMag, signum);
3605     }
3606 
3607     private static void shiftRightImplWorker(int[] newArr, int[] oldArr, int newIdx, int shiftCount, int numIter) {
3608         int shiftCountLeft = 32 - shiftCount;
3609         int idx = numIter;
3610         int nidx = (newIdx == 0) ? numIter - 1 : numIter;
3611         while (nidx >= newIdx) {
3612             newArr[nidx--] = (oldArr[idx--] >>> shiftCount) | (oldArr[idx] << shiftCountLeft);
3613         }
3614     }
3615 
3616     int[] javaIncrement(int[] val) {
3617         int lastSum = 0;
3618         for (int i=val.length-1;  i >= 0 && lastSum == 0; i--)
3619             lastSum = (val[i] += 1);
3620         if (lastSum == 0) {
3621             val = new int[val.length+1];
3622             val[0] = 1;
3623         }
3624         return val;
3625     }
3626 
3627     // Bitwise Operations
3628 
3629     /**
3630      * Returns a BigInteger whose value is {@code (this & val)}.  (This
3631      * method returns a negative BigInteger if and only if this and val are
3632      * both negative.)
3633      *
3634      * @param val value to be AND'ed with this BigInteger.
3635      * @return {@code this & val}
3636      */
3637     public BigInteger and(BigInteger val) {
3638         int[] result = new int[Math.max(intLength(), val.intLength())];
3639         for (int i=0; i < result.length; i++)
3640             result[i] = (getInt(result.length-i-1)
3641                          & val.getInt(result.length-i-1));
3642 
3643         return valueOf(result);
3644     }
3645 
3646     /**
3647      * Returns a BigInteger whose value is {@code (this | val)}.  (This method
3648      * returns a negative BigInteger if and only if either this or val is
3649      * negative.)
3650      *
3651      * @param val value to be OR'ed with this BigInteger.
3652      * @return {@code this | val}
3653      */
3654     public BigInteger or(BigInteger val) {
3655         int[] result = new int[Math.max(intLength(), val.intLength())];
3656         for (int i=0; i < result.length; i++)
3657             result[i] = (getInt(result.length-i-1)
3658                          | val.getInt(result.length-i-1));
3659 
3660         return valueOf(result);
3661     }
3662 
3663     /**
3664      * Returns a BigInteger whose value is {@code (this ^ val)}.  (This method
3665      * returns a negative BigInteger if and only if exactly one of this and
3666      * val are negative.)
3667      *
3668      * @param val value to be XOR'ed with this BigInteger.
3669      * @return {@code this ^ val}
3670      */
3671     public BigInteger xor(BigInteger val) {
3672         int[] result = new int[Math.max(intLength(), val.intLength())];
3673         for (int i=0; i < result.length; i++)
3674             result[i] = (getInt(result.length-i-1)
3675                          ^ val.getInt(result.length-i-1));
3676 
3677         return valueOf(result);
3678     }
3679 
3680     /**
3681      * Returns a BigInteger whose value is {@code (~this)}.  (This method
3682      * returns a negative value if and only if this BigInteger is
3683      * non-negative.)
3684      *
3685      * @return {@code ~this}
3686      */
3687     public BigInteger not() {
3688         int[] result = new int[intLength()];
3689         for (int i=0; i < result.length; i++)
3690             result[i] = ~getInt(result.length-i-1);
3691 
3692         return valueOf(result);
3693     }
3694 
3695     /**
3696      * Returns a BigInteger whose value is {@code (this & ~val)}.  This
3697      * method, which is equivalent to {@code and(val.not())}, is provided as
3698      * a convenience for masking operations.  (This method returns a negative
3699      * BigInteger if and only if {@code this} is negative and {@code val} is
3700      * positive.)
3701      *
3702      * @param val value to be complemented and AND'ed with this BigInteger.
3703      * @return {@code this & ~val}
3704      */
3705     public BigInteger andNot(BigInteger val) {
3706         int[] result = new int[Math.max(intLength(), val.intLength())];
3707         for (int i=0; i < result.length; i++)
3708             result[i] = (getInt(result.length-i-1)
3709                          & ~val.getInt(result.length-i-1));
3710 
3711         return valueOf(result);
3712     }
3713 
3714 
3715     // Single Bit Operations
3716 
3717     /**
3718      * Returns {@code true} if and only if the designated bit is set.
3719      * (Computes {@code ((this & (1<<n)) != 0)}.)
3720      *
3721      * @param  n index of bit to test.
3722      * @return {@code true} if and only if the designated bit is set.
3723      * @throws ArithmeticException {@code n} is negative.
3724      */
3725     public boolean testBit(int n) {
3726         if (n < 0)
3727             throw new ArithmeticException("Negative bit address");
3728 
3729         return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
3730     }
3731 
3732     /**
3733      * Returns a BigInteger whose value is equivalent to this BigInteger
3734      * with the designated bit set.  (Computes {@code (this | (1<<n))}.)
3735      *
3736      * @param  n index of bit to set.
3737      * @return {@code this | (1<<n)}
3738      * @throws ArithmeticException {@code n} is negative.
3739      */
3740     public BigInteger setBit(int n) {
3741         if (n < 0)
3742             throw new ArithmeticException("Negative bit address");
3743 
3744         int intNum = n >>> 5;
3745         int[] result = new int[Math.max(intLength(), intNum+2)];
3746 
3747         for (int i=0; i < result.length; i++)
3748             result[result.length-i-1] = getInt(i);
3749 
3750         result[result.length-intNum-1] |= (1 << (n & 31));
3751 
3752         return valueOf(result);
3753     }
3754 
3755     /**
3756      * Returns a BigInteger whose value is equivalent to this BigInteger
3757      * with the designated bit cleared.
3758      * (Computes {@code (this & ~(1<<n))}.)
3759      *
3760      * @param  n index of bit to clear.
3761      * @return {@code this & ~(1<<n)}
3762      * @throws ArithmeticException {@code n} is negative.
3763      */
3764     public BigInteger clearBit(int n) {
3765         if (n < 0)
3766             throw new ArithmeticException("Negative bit address");
3767 
3768         int intNum = n >>> 5;
3769         int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];
3770 
3771         for (int i=0; i < result.length; i++)
3772             result[result.length-i-1] = getInt(i);
3773 
3774         result[result.length-intNum-1] &= ~(1 << (n & 31));
3775 
3776         return valueOf(result);
3777     }
3778 
3779     /**
3780      * Returns a BigInteger whose value is equivalent to this BigInteger
3781      * with the designated bit flipped.
3782      * (Computes {@code (this ^ (1<<n))}.)
3783      *
3784      * @param  n index of bit to flip.
3785      * @return {@code this ^ (1<<n)}
3786      * @throws ArithmeticException {@code n} is negative.
3787      */
3788     public BigInteger flipBit(int n) {
3789         if (n < 0)
3790             throw new ArithmeticException("Negative bit address");
3791 
3792         int intNum = n >>> 5;
3793         int[] result = new int[Math.max(intLength(), intNum+2)];
3794 
3795         for (int i=0; i < result.length; i++)
3796             result[result.length-i-1] = getInt(i);
3797 
3798         result[result.length-intNum-1] ^= (1 << (n & 31));
3799 
3800         return valueOf(result);
3801     }
3802 
3803     /**
3804      * Returns the index of the rightmost (lowest-order) one bit in this
3805      * BigInteger (the number of zero bits to the right of the rightmost
3806      * one bit).  Returns -1 if this BigInteger contains no one bits.
3807      * (Computes {@code (this == 0? -1 : log2(this & -this))}.)
3808      *
3809      * @return index of the rightmost one bit in this BigInteger.
3810      */
3811     public int getLowestSetBit() {
3812         int lsb = lowestSetBitPlusTwo - 2;
3813         if (lsb == -2) {  // lowestSetBit not initialized yet
3814             lsb = 0;
3815             if (signum == 0) {
3816                 lsb -= 1;
3817             } else {
3818                 // Search for lowest order nonzero int
3819                 int i,b;
3820                 for (i=0; (b = getInt(i)) == 0; i++)
3821                     ;
3822                 lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
3823             }
3824             lowestSetBitPlusTwo = lsb + 2;
3825         }
3826         return lsb;
3827     }
3828 
3829 
3830     // Miscellaneous Bit Operations
3831 
3832     /**
3833      * Returns the number of bits in the minimal two's-complement
3834      * representation of this BigInteger, <em>excluding</em> a sign bit.
3835      * For positive BigIntegers, this is equivalent to the number of bits in
3836      * the ordinary binary representation.  For zero this method returns
3837      * {@code 0}.  (Computes {@code (ceil(log2(this < 0 ? -this : this+1)))}.)
3838      *
3839      * @return number of bits in the minimal two's-complement
3840      *         representation of this BigInteger, <em>excluding</em> a sign bit.
3841      */
3842     public int bitLength() {
3843         int n = bitLengthPlusOne - 1;
3844         if (n == -1) { // bitLength not initialized yet
3845             int[] m = mag;
3846             int len = m.length;
3847             if (len == 0) {
3848                 n = 0; // offset by one to initialize
3849             }  else {
3850                 // Calculate the bit length of the magnitude
3851                 int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
3852                  if (signum < 0) {
3853                      // Check if magnitude is a power of two
3854                      boolean pow2 = (Integer.bitCount(mag[0]) == 1);
3855                      for (int i=1; i< len && pow2; i++)
3856                          pow2 = (mag[i] == 0);
3857 
3858                      n = (pow2 ? magBitLength - 1 : magBitLength);
3859                  } else {
3860                      n = magBitLength;
3861                  }
3862             }
3863             bitLengthPlusOne = n + 1;
3864         }
3865         return n;
3866     }
3867 
3868     /**
3869      * Returns the number of bits in the two's complement representation
3870      * of this BigInteger that differ from its sign bit.  This method is
3871      * useful when implementing bit-vector style sets atop BigIntegers.
3872      *
3873      * @return number of bits in the two's complement representation
3874      *         of this BigInteger that differ from its sign bit.
3875      */
3876     public int bitCount() {
3877         int bc = bitCountPlusOne - 1;
3878         if (bc == -1) {  // bitCount not initialized yet
3879             bc = 0;      // offset by one to initialize
3880             // Count the bits in the magnitude
3881             for (int i=0; i < mag.length; i++)
3882                 bc += Integer.bitCount(mag[i]);
3883             if (signum < 0) {
3884                 // Count the trailing zeros in the magnitude
3885                 int magTrailingZeroCount = 0, j;
3886                 for (j=mag.length-1; mag[j] == 0; j--)
3887                     magTrailingZeroCount += 32;
3888                 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
3889                 bc += magTrailingZeroCount - 1;
3890             }
3891             bitCountPlusOne = bc + 1;
3892         }
3893         return bc;
3894     }
3895 
3896     // Primality Testing
3897 
3898     /**
3899      * Returns {@code true} if this BigInteger is probably prime,
3900      * {@code false} if it's definitely composite.  If
3901      * {@code certainty} is &le; 0, {@code true} is
3902      * returned.
3903      *
3904      * @param  certainty a measure of the uncertainty that the caller is
3905      *         willing to tolerate: if the call returns {@code true}
3906      *         the probability that this BigInteger is prime exceeds
3907      *         (1 - 1/2<sup>{@code certainty}</sup>).  The execution time of
3908      *         this method is proportional to the value of this parameter.
3909      * @return {@code true} if this BigInteger is probably prime,
3910      *         {@code false} if it's definitely composite.
3911      */
3912     public boolean isProbablePrime(int certainty) {
3913         if (certainty <= 0)
3914             return true;
3915         BigInteger w = this.abs();
3916         if (w.equals(TWO))
3917             return true;
3918         if (!w.testBit(0) || w.equals(ONE))
3919             return false;
3920 
3921         return w.primeToCertainty(certainty, null);
3922     }
3923 
3924     // Comparison Operations
3925 
3926     /**
3927      * Compares this BigInteger with the specified BigInteger.  This
3928      * method is provided in preference to individual methods for each
3929      * of the six boolean comparison operators ({@literal <}, ==,
3930      * {@literal >}, {@literal >=}, !=, {@literal <=}).  The suggested
3931      * idiom for performing these comparisons is: {@code
3932      * (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
3933      * &lt;<i>op</i>&gt; is one of the six comparison operators.
3934      *
3935      * @param  val BigInteger to which this BigInteger is to be compared.
3936      * @return -1, 0 or 1 as this BigInteger is numerically less than, equal
3937      *         to, or greater than {@code val}.
3938      */
3939     public int compareTo(BigInteger val) {
3940         if (signum == val.signum) {
3941             return switch (signum) {
3942                 case 1  -> compareMagnitude(val);
3943                 case -1 -> val.compareMagnitude(this);
3944                 default -> 0;
3945             };
3946         }
3947         return signum > val.signum ? 1 : -1;
3948     }
3949 
3950     /**
3951      * Compares the magnitude array of this BigInteger with the specified
3952      * BigInteger's. This is the version of compareTo ignoring sign.
3953      *
3954      * @param val BigInteger whose magnitude array to be compared.
3955      * @return -1, 0 or 1 as this magnitude array is less than, equal to or
3956      *         greater than the magnitude aray for the specified BigInteger's.
3957      */
3958     final int compareMagnitude(BigInteger val) {
3959         int[] m1 = mag;
3960         int len1 = m1.length;
3961         int[] m2 = val.mag;
3962         int len2 = m2.length;
3963         if (len1 < len2)
3964             return -1;
3965         if (len1 > len2)
3966             return 1;
3967         for (int i = 0; i < len1; i++) {
3968             int a = m1[i];
3969             int b = m2[i];
3970             if (a != b)
3971                 return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
3972         }
3973         return 0;
3974     }
3975 
3976     /**
3977      * Version of compareMagnitude that compares magnitude with long value.
3978      * val can't be Long.MIN_VALUE.
3979      */
3980     final int compareMagnitude(long val) {
3981         assert val != Long.MIN_VALUE;
3982         int[] m1 = mag;
3983         int len = m1.length;
3984         if (len > 2) {
3985             return 1;
3986         }
3987         if (val < 0) {
3988             val = -val;
3989         }
3990         int highWord = (int)(val >>> 32);
3991         if (highWord == 0) {
3992             if (len < 1)
3993                 return -1;
3994             if (len > 1)
3995                 return 1;
3996             int a = m1[0];
3997             int b = (int)val;
3998             if (a != b) {
3999                 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
4000             }
4001             return 0;
4002         } else {
4003             if (len < 2)
4004                 return -1;
4005             int a = m1[0];
4006             int b = highWord;
4007             if (a != b) {
4008                 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
4009             }
4010             a = m1[1];
4011             b = (int)val;
4012             if (a != b) {
4013                 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
4014             }
4015             return 0;
4016         }
4017     }
4018 
4019     /**
4020      * Compares this BigInteger with the specified Object for equality.
4021      *
4022      * @param  x Object to which this BigInteger is to be compared.
4023      * @return {@code true} if and only if the specified Object is a
4024      *         BigInteger whose value is numerically equal to this BigInteger.
4025      */
4026     public boolean equals(Object x) {
4027         // This test is just an optimization, which may or may not help
4028         if (x == this)
4029             return true;
4030 
4031         if (!(x instanceof BigInteger xInt))
4032             return false;
4033 
4034         if (xInt.signum != signum)
4035             return false;
4036 
4037         int[] m = mag;
4038         int len = m.length;
4039         int[] xm = xInt.mag;
4040         if (len != xm.length)
4041             return false;
4042 
4043         for (int i = 0; i < len; i++)
4044             if (xm[i] != m[i])
4045                 return false;
4046 
4047         return true;
4048     }
4049 
4050     /**
4051      * Returns the minimum of this BigInteger and {@code val}.
4052      *
4053      * @param  val value with which the minimum is to be computed.
4054      * @return the BigInteger whose value is the lesser of this BigInteger and
4055      *         {@code val}.  If they are equal, either may be returned.
4056      */
4057     public BigInteger min(BigInteger val) {
4058         return (compareTo(val) < 0 ? this : val);
4059     }
4060 
4061     /**
4062      * Returns the maximum of this BigInteger and {@code val}.
4063      *
4064      * @param  val value with which the maximum is to be computed.
4065      * @return the BigInteger whose value is the greater of this and
4066      *         {@code val}.  If they are equal, either may be returned.
4067      */
4068     public BigInteger max(BigInteger val) {
4069         return (compareTo(val) > 0 ? this : val);
4070     }
4071 
4072 
4073     // Hash Function
4074 
4075     /**
4076      * Returns the hash code for this BigInteger.
4077      *
4078      * @return hash code for this BigInteger.
4079      */
4080     public int hashCode() {
4081         int hashCode = 0;
4082 
4083         for (int i=0; i < mag.length; i++)
4084             hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));
4085 
4086         return hashCode * signum;
4087     }
4088 
4089     /**
4090      * Returns the String representation of this BigInteger in the
4091      * given radix.  If the radix is outside the range from {@link
4092      * Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive,
4093      * it will default to 10 (as is the case for
4094      * {@code Integer.toString}).  The digit-to-character mapping
4095      * provided by {@code Character.forDigit} is used, and a minus
4096      * sign is prepended if appropriate.  (This representation is
4097      * compatible with the {@link #BigInteger(String, int) (String,
4098      * int)} constructor.)
4099      *
4100      * @param  radix  radix of the String representation.
4101      * @return String representation of this BigInteger in the given radix.
4102      * @see    Integer#toString
4103      * @see    Character#forDigit
4104      * @see    #BigInteger(java.lang.String, int)
4105      */
4106     public String toString(int radix) {
4107         if (signum == 0)
4108             return "0";
4109         if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
4110             radix = 10;
4111 
4112         BigInteger abs = this.abs();
4113 
4114         // Ensure buffer capacity sufficient to contain string representation
4115         //     floor(bitLength*log(2)/log(radix)) + 1
4116         // plus an additional character for the sign if negative.
4117         int b = abs.bitLength();
4118         int numChars = (int)(Math.floor(b*LOG_TWO/logCache[radix]) + 1) +
4119             (signum < 0 ? 1 : 0);
4120         StringBuilder sb = new StringBuilder(numChars);
4121 
4122         if (signum < 0) {
4123             sb.append('-');
4124         }
4125 
4126         // Use recursive toString.
4127         toString(abs, sb, radix, 0);
4128 
4129         return sb.toString();
4130     }
4131 
4132     /**
4133      * If {@code numZeros > 0}, appends that many zeros to the
4134      * specified StringBuilder; otherwise, does nothing.
4135      *
4136      * @param buf       The StringBuilder that will be appended to.
4137      * @param numZeros  The number of zeros to append.
4138      */
4139     private static void padWithZeros(StringBuilder buf, int numZeros) {
4140         while (numZeros >= NUM_ZEROS) {
4141             buf.append(ZEROS);
4142             numZeros -= NUM_ZEROS;
4143         }
4144         if (numZeros > 0) {
4145             buf.append(ZEROS, 0, numZeros);
4146         }
4147     }
4148 
4149     /**
4150      * This method is used to perform toString when arguments are small.
4151      * The value must be non-negative. If {@code digits <= 0} no padding
4152      * (pre-pending with zeros) will be effected.
4153      *
4154      * @param radix  The base to convert to.
4155      * @param buf    The StringBuilder that will be appended to in place.
4156      * @param digits The minimum number of digits to pad to.
4157      */
4158     private void smallToString(int radix, StringBuilder buf, int digits) {
4159         assert signum >= 0;
4160 
4161         if (signum == 0) {
4162             padWithZeros(buf, digits);
4163             return;
4164         }
4165 
4166         // Compute upper bound on number of digit groups and allocate space
4167         int maxNumDigitGroups = (4*mag.length + 6)/7;
4168         long[] digitGroups = new long[maxNumDigitGroups];
4169 
4170         // Translate number to string, a digit group at a time
4171         BigInteger tmp = this;
4172         int numGroups = 0;
4173         while (tmp.signum != 0) {
4174             BigInteger d = longRadix[radix];
4175 
4176             MutableBigInteger q = new MutableBigInteger(),
4177                               a = new MutableBigInteger(tmp.mag),
4178                               b = new MutableBigInteger(d.mag);
4179             MutableBigInteger r = a.divide(b, q);
4180             BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);
4181             BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
4182 
4183             digitGroups[numGroups++] = r2.longValue();
4184             tmp = q2;
4185         }
4186 
4187         // Get string version of first digit group
4188         String s = Long.toString(digitGroups[numGroups-1], radix);
4189 
4190         // Pad with internal zeros if necessary.
4191         padWithZeros(buf, digits - (s.length() +
4192             (numGroups - 1)*digitsPerLong[radix]));
4193 
4194         // Put first digit group into result buffer
4195         buf.append(s);
4196 
4197         // Append remaining digit groups each padded with leading zeros
4198         for (int i=numGroups-2; i >= 0; i--) {
4199             // Prepend (any) leading zeros for this digit group
4200             s = Long.toString(digitGroups[i], radix);
4201             int numLeadingZeros = digitsPerLong[radix] - s.length();
4202             if (numLeadingZeros != 0) {
4203                 buf.append(ZEROS, 0, numLeadingZeros);
4204             }
4205             buf.append(s);
4206         }
4207     }
4208 
4209     /**
4210      * Converts the specified BigInteger to a string and appends to
4211      * {@code sb}.  This implements the recursive Schoenhage algorithm
4212      * for base conversions. This method can only be called for non-negative
4213      * numbers.
4214      * <p>
4215      * See Knuth, Donald,  _The Art of Computer Programming_, Vol. 2,
4216      * Answers to Exercises (4.4) Question 14.
4217      *
4218      * @param u      The number to convert to a string.
4219      * @param sb     The StringBuilder that will be appended to in place.
4220      * @param radix  The base to convert to.
4221      * @param digits The minimum number of digits to pad to.
4222      */
4223     private static void toString(BigInteger u, StringBuilder sb,
4224                                  int radix, int digits) {
4225         assert u.signum() >= 0;
4226 
4227         // If we're smaller than a certain threshold, use the smallToString
4228         // method, padding with leading zeroes when necessary unless we're
4229         // at the beginning of the string or digits <= 0. As u.signum() >= 0,
4230         // smallToString() will not prepend a negative sign.
4231         if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
4232             u.smallToString(radix, sb, digits);
4233             return;
4234         }
4235 
4236         // Calculate a value for n in the equation radix^(2^n) = u
4237         // and subtract 1 from that value.  This is used to find the
4238         // cache index that contains the best value to divide u.
4239         int b = u.bitLength();
4240         int n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) /
4241                                  LOG_TWO - 1.0);
4242 
4243         BigInteger v = getRadixConversionCache(radix, n);
4244         BigInteger[] results;
4245         results = u.divideAndRemainder(v);
4246 
4247         int expectedDigits = 1 << n;
4248 
4249         // Now recursively build the two halves of each number.
4250         toString(results[0], sb, radix, digits - expectedDigits);
4251         toString(results[1], sb, radix, expectedDigits);
4252     }
4253 
4254     /**
4255      * Returns the value radix^(2^exponent) from the cache.
4256      * If this value doesn't already exist in the cache, it is added.
4257      * <p>
4258      * This could be changed to a more complicated caching method using
4259      * {@code Future}.
4260      */
4261     private static BigInteger getRadixConversionCache(int radix, int exponent) {
4262         BigInteger[] cacheLine = powerCache[radix]; // volatile read
4263         if (exponent < cacheLine.length) {
4264             return cacheLine[exponent];
4265         }
4266 
4267         int oldLength = cacheLine.length;
4268         cacheLine = Arrays.copyOf(cacheLine, exponent + 1);
4269         for (int i = oldLength; i <= exponent; i++) {
4270             cacheLine[i] = cacheLine[i - 1].pow(2);
4271         }
4272 
4273         BigInteger[][] pc = powerCache; // volatile read again
4274         if (exponent >= pc[radix].length) {
4275             pc = pc.clone();
4276             pc[radix] = cacheLine;
4277             powerCache = pc; // volatile write, publish
4278         }
4279         return cacheLine[exponent];
4280     }
4281 
4282     /* Size of ZEROS string. */
4283     private static int NUM_ZEROS = 63;
4284 
4285     /* ZEROS is a string of NUM_ZEROS consecutive zeros. */
4286     private static final String ZEROS = "0".repeat(NUM_ZEROS);
4287 
4288     /**
4289      * Returns the decimal String representation of this BigInteger.
4290      * The digit-to-character mapping provided by
4291      * {@code Character.forDigit} is used, and a minus sign is
4292      * prepended if appropriate.  (This representation is compatible
4293      * with the {@link #BigInteger(String) (String)} constructor, and
4294      * allows for String concatenation with Java's + operator.)
4295      *
4296      * @return decimal String representation of this BigInteger.
4297      * @see    Character#forDigit
4298      * @see    #BigInteger(java.lang.String)
4299      */
4300     public String toString() {
4301         return toString(10);
4302     }
4303 
4304     /**
4305      * Returns a byte array containing the two's-complement
4306      * representation of this BigInteger.  The byte array will be in
4307      * <i>big-endian</i> byte-order: the most significant byte is in
4308      * the zeroth element.  The array will contain the minimum number
4309      * of bytes required to represent this BigInteger, including at
4310      * least one sign bit, which is {@code (ceil((this.bitLength() +
4311      * 1)/8))}.  (This representation is compatible with the
4312      * {@link #BigInteger(byte[]) (byte[])} constructor.)
4313      *
4314      * @return a byte array containing the two's-complement representation of
4315      *         this BigInteger.
4316      * @see    #BigInteger(byte[])
4317      */
4318     public byte[] toByteArray() {
4319         int byteLen = bitLength()/8 + 1;
4320         byte[] byteArray = new byte[byteLen];
4321 
4322         for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {
4323             if (bytesCopied == 4) {
4324                 nextInt = getInt(intIndex++);
4325                 bytesCopied = 1;
4326             } else {
4327                 nextInt >>>= 8;
4328                 bytesCopied++;
4329             }
4330             byteArray[i] = (byte)nextInt;
4331         }
4332         return byteArray;
4333     }
4334 
4335     /**
4336      * Converts this BigInteger to an {@code int}.  This
4337      * conversion is analogous to a
4338      * <i>narrowing primitive conversion</i> from {@code long} to
4339      * {@code int} as defined in
4340      * <cite>The Java Language Specification</cite>:
4341      * if this BigInteger is too big to fit in an
4342      * {@code int}, only the low-order 32 bits are returned.
4343      * Note that this conversion can lose information about the
4344      * overall magnitude of the BigInteger value as well as return a
4345      * result with the opposite sign.
4346      *
4347      * @return this BigInteger converted to an {@code int}.
4348      * @see #intValueExact()
4349      * @jls 5.1.3 Narrowing Primitive Conversion
4350      */
4351     public int intValue() {
4352         int result = 0;
4353         result = getInt(0);
4354         return result;
4355     }
4356 
4357     /**
4358      * Converts this BigInteger to a {@code long}.  This
4359      * conversion is analogous to a
4360      * <i>narrowing primitive conversion</i> from {@code long} to
4361      * {@code int} as defined in
4362      * <cite>The Java Language Specification</cite>:
4363      * if this BigInteger is too big to fit in a
4364      * {@code long}, only the low-order 64 bits are returned.
4365      * Note that this conversion can lose information about the
4366      * overall magnitude of the BigInteger value as well as return a
4367      * result with the opposite sign.
4368      *
4369      * @return this BigInteger converted to a {@code long}.
4370      * @see #longValueExact()
4371      * @jls 5.1.3 Narrowing Primitive Conversion
4372      */
4373     public long longValue() {
4374         long result = 0;
4375 
4376         for (int i=1; i >= 0; i--)
4377             result = (result << 32) + (getInt(i) & LONG_MASK);
4378         return result;
4379     }
4380 
4381     /**
4382      * Converts this BigInteger to a {@code float}.  This
4383      * conversion is similar to the
4384      * <i>narrowing primitive conversion</i> from {@code double} to
4385      * {@code float} as defined in
4386      * <cite>The Java Language Specification</cite>:
4387      * if this BigInteger has too great a magnitude
4388      * to represent as a {@code float}, it will be converted to
4389      * {@link Float#NEGATIVE_INFINITY} or {@link
4390      * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
4391      * the return value is finite, this conversion can lose
4392      * information about the precision of the BigInteger value.
4393      *
4394      * @return this BigInteger converted to a {@code float}.
4395      * @jls 5.1.3 Narrowing Primitive Conversion
4396      */
4397     public float floatValue() {
4398         if (signum == 0) {
4399             return 0.0f;
4400         }
4401 
4402         int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
4403 
4404         // exponent == floor(log2(abs(this)))
4405         if (exponent < Long.SIZE - 1) {
4406             return longValue();
4407         } else if (exponent > Float.MAX_EXPONENT) {
4408             return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
4409         }
4410 
4411         /*
4412          * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
4413          * one bit. To make rounding easier, we pick out the top
4414          * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
4415          * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1
4416          * bits, and signifFloor the top SIGNIFICAND_WIDTH.
4417          *
4418          * It helps to consider the real number signif = abs(this) *
4419          * 2^(SIGNIFICAND_WIDTH - 1 - exponent).
4420          */
4421         int shift = exponent - FloatConsts.SIGNIFICAND_WIDTH;
4422 
4423         int twiceSignifFloor;
4424         // twiceSignifFloor will be == abs().shiftRight(shift).intValue()
4425         // We do the shift into an int directly to improve performance.
4426 
4427         int nBits = shift & 0x1f;
4428         int nBits2 = 32 - nBits;
4429 
4430         if (nBits == 0) {
4431             twiceSignifFloor = mag[0];
4432         } else {
4433             twiceSignifFloor = mag[0] >>> nBits;
4434             if (twiceSignifFloor == 0) {
4435                 twiceSignifFloor = (mag[0] << nBits2) | (mag[1] >>> nBits);
4436             }
4437         }
4438 
4439         int signifFloor = twiceSignifFloor >> 1;
4440         signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit
4441 
4442         /*
4443          * We round up if either the fractional part of signif is strictly
4444          * greater than 0.5 (which is true if the 0.5 bit is set and any lower
4445          * bit is set), or if the fractional part of signif is >= 0.5 and
4446          * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit
4447          * are set). This is equivalent to the desired HALF_EVEN rounding.
4448          */
4449         boolean increment = (twiceSignifFloor & 1) != 0
4450                 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
4451         int signifRounded = increment ? signifFloor + 1 : signifFloor;
4452         int bits = ((exponent + FloatConsts.EXP_BIAS))
4453                 << (FloatConsts.SIGNIFICAND_WIDTH - 1);
4454         bits += signifRounded;
4455         /*
4456          * If signifRounded == 2^24, we'd need to set all of the significand
4457          * bits to zero and add 1 to the exponent. This is exactly the behavior
4458          * we get from just adding signifRounded to bits directly. If the
4459          * exponent is Float.MAX_EXPONENT, we round up (correctly) to
4460          * Float.POSITIVE_INFINITY.
4461          */
4462         bits |= signum & FloatConsts.SIGN_BIT_MASK;
4463         return Float.intBitsToFloat(bits);
4464     }
4465 
4466     /**
4467      * Converts this BigInteger to a {@code double}.  This
4468      * conversion is similar to the
4469      * <i>narrowing primitive conversion</i> from {@code double} to
4470      * {@code float} as defined in
4471      * <cite>The Java Language Specification</cite>:
4472      * if this BigInteger has too great a magnitude
4473      * to represent as a {@code double}, it will be converted to
4474      * {@link Double#NEGATIVE_INFINITY} or {@link
4475      * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
4476      * the return value is finite, this conversion can lose
4477      * information about the precision of the BigInteger value.
4478      *
4479      * @return this BigInteger converted to a {@code double}.
4480      * @jls 5.1.3 Narrowing Primitive Conversion
4481      */
4482     public double doubleValue() {
4483         if (signum == 0) {
4484             return 0.0;
4485         }
4486 
4487         int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
4488 
4489         // exponent == floor(log2(abs(this))Double)
4490         if (exponent < Long.SIZE - 1) {
4491             return longValue();
4492         } else if (exponent > Double.MAX_EXPONENT) {
4493             return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
4494         }
4495 
4496         /*
4497          * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
4498          * one bit. To make rounding easier, we pick out the top
4499          * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
4500          * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1
4501          * bits, and signifFloor the top SIGNIFICAND_WIDTH.
4502          *
4503          * It helps to consider the real number signif = abs(this) *
4504          * 2^(SIGNIFICAND_WIDTH - 1 - exponent).
4505          */
4506         int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH;
4507 
4508         long twiceSignifFloor;
4509         // twiceSignifFloor will be == abs().shiftRight(shift).longValue()
4510         // We do the shift into a long directly to improve performance.
4511 
4512         int nBits = shift & 0x1f;
4513         int nBits2 = 32 - nBits;
4514 
4515         int highBits;
4516         int lowBits;
4517         if (nBits == 0) {
4518             highBits = mag[0];
4519             lowBits = mag[1];
4520         } else {
4521             highBits = mag[0] >>> nBits;
4522             lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits);
4523             if (highBits == 0) {
4524                 highBits = lowBits;
4525                 lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits);
4526             }
4527         }
4528 
4529         twiceSignifFloor = ((highBits & LONG_MASK) << 32)
4530                 | (lowBits & LONG_MASK);
4531 
4532         long signifFloor = twiceSignifFloor >> 1;
4533         signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit
4534 
4535         /*
4536          * We round up if either the fractional part of signif is strictly
4537          * greater than 0.5 (which is true if the 0.5 bit is set and any lower
4538          * bit is set), or if the fractional part of signif is >= 0.5 and
4539          * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit
4540          * are set). This is equivalent to the desired HALF_EVEN rounding.
4541          */
4542         boolean increment = (twiceSignifFloor & 1) != 0
4543                 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
4544         long signifRounded = increment ? signifFloor + 1 : signifFloor;
4545         long bits = (long) ((exponent + DoubleConsts.EXP_BIAS))
4546                 << (DoubleConsts.SIGNIFICAND_WIDTH - 1);
4547         bits += signifRounded;
4548         /*
4549          * If signifRounded == 2^53, we'd need to set all of the significand
4550          * bits to zero and add 1 to the exponent. This is exactly the behavior
4551          * we get from just adding signifRounded to bits directly. If the
4552          * exponent is Double.MAX_EXPONENT, we round up (correctly) to
4553          * Double.POSITIVE_INFINITY.
4554          */
4555         bits |= signum & DoubleConsts.SIGN_BIT_MASK;
4556         return Double.longBitsToDouble(bits);
4557     }
4558 
4559     /**
4560      * Returns a copy of the input array stripped of any leading zero bytes.
4561      */
4562     private static int[] stripLeadingZeroInts(int val[]) {
4563         int vlen = val.length;
4564         int keep;
4565 
4566         // Find first nonzero byte
4567         for (keep = 0; keep < vlen && val[keep] == 0; keep++)
4568             ;
4569         return java.util.Arrays.copyOfRange(val, keep, vlen);
4570     }
4571 
4572     /**
4573      * Returns the input array stripped of any leading zero bytes.
4574      * Since the source is trusted the copying may be skipped.
4575      */
4576     private static int[] trustedStripLeadingZeroInts(int val[]) {
4577         int vlen = val.length;
4578         int keep;
4579 
4580         // Find first nonzero byte
4581         for (keep = 0; keep < vlen && val[keep] == 0; keep++)
4582             ;
4583         return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen);
4584     }
4585 
4586     /**
4587      * Returns a copy of the input array stripped of any leading zero bytes.
4588      */
4589     private static int[] stripLeadingZeroBytes(byte a[], int off, int len) {
4590         int indexBound = off + len;
4591         int keep;
4592 
4593         // Find first nonzero byte
4594         for (keep = off; keep < indexBound && a[keep] == 0; keep++)
4595             ;
4596 
4597         // Allocate new array and copy relevant part of input array
4598         int intLength = ((indexBound - keep) + 3) >>> 2;
4599         int[] result = new int[intLength];
4600         int b = indexBound - 1;
4601         for (int i = intLength-1; i >= 0; i--) {
4602             result[i] = a[b--] & 0xff;
4603             int bytesRemaining = b - keep + 1;
4604             int bytesToTransfer = Math.min(3, bytesRemaining);
4605             for (int j=8; j <= (bytesToTransfer << 3); j += 8)
4606                 result[i] |= ((a[b--] & 0xff) << j);
4607         }
4608         return result;
4609     }
4610 
4611     /**
4612      * Takes an array a representing a negative 2's-complement number and
4613      * returns the minimal (no leading zero bytes) unsigned whose value is -a.
4614      */
4615     private static int[] makePositive(byte a[], int off, int len) {
4616         int keep, k;
4617         int indexBound = off + len;
4618 
4619         // Find first non-sign (0xff) byte of input
4620         for (keep=off; keep < indexBound && a[keep] == -1; keep++)
4621             ;
4622 
4623 
4624         /* Allocate output array.  If all non-sign bytes are 0x00, we must
4625          * allocate space for one extra output byte. */
4626         for (k=keep; k < indexBound && a[k] == 0; k++)
4627             ;
4628 
4629         int extraByte = (k == indexBound) ? 1 : 0;
4630         int intLength = ((indexBound - keep + extraByte) + 3) >>> 2;
4631         int result[] = new int[intLength];
4632 
4633         /* Copy one's complement of input into output, leaving extra
4634          * byte (if it exists) == 0x00 */
4635         int b = indexBound - 1;
4636         for (int i = intLength-1; i >= 0; i--) {
4637             result[i] = a[b--] & 0xff;
4638             int numBytesToTransfer = Math.min(3, b-keep+1);
4639             if (numBytesToTransfer < 0)
4640                 numBytesToTransfer = 0;
4641             for (int j=8; j <= 8*numBytesToTransfer; j += 8)
4642                 result[i] |= ((a[b--] & 0xff) << j);
4643 
4644             // Mask indicates which bits must be complemented
4645             int mask = -1 >>> (8*(3-numBytesToTransfer));
4646             result[i] = ~result[i] & mask;
4647         }
4648 
4649         // Add one to one's complement to generate two's complement
4650         for (int i=result.length-1; i >= 0; i--) {
4651             result[i] = (int)((result[i] & LONG_MASK) + 1);
4652             if (result[i] != 0)
4653                 break;
4654         }
4655 
4656         return result;
4657     }
4658 
4659     /**
4660      * Takes an array a representing a negative 2's-complement number and
4661      * returns the minimal (no leading zero ints) unsigned whose value is -a.
4662      */
4663     private static int[] makePositive(int a[]) {
4664         int keep, j;
4665 
4666         // Find first non-sign (0xffffffff) int of input
4667         for (keep=0; keep < a.length && a[keep] == -1; keep++)
4668             ;
4669 
4670         /* Allocate output array.  If all non-sign ints are 0x00, we must
4671          * allocate space for one extra output int. */
4672         for (j=keep; j < a.length && a[j] == 0; j++)
4673             ;
4674         int extraInt = (j == a.length ? 1 : 0);
4675         int result[] = new int[a.length - keep + extraInt];
4676 
4677         /* Copy one's complement of input into output, leaving extra
4678          * int (if it exists) == 0x00 */
4679         for (int i = keep; i < a.length; i++)
4680             result[i - keep + extraInt] = ~a[i];
4681 
4682         // Add one to one's complement to generate two's complement
4683         for (int i=result.length-1; ++result[i] == 0; i--)
4684             ;
4685 
4686         return result;
4687     }
4688 
4689     /*
4690      * The following two arrays are used for fast String conversions.  Both
4691      * are indexed by radix.  The first is the number of digits of the given
4692      * radix that can fit in a Java long without "going negative", i.e., the
4693      * highest integer n such that radix**n < 2**63.  The second is the
4694      * "long radix" that tears each number into "long digits", each of which
4695      * consists of the number of digits in the corresponding element in
4696      * digitsPerLong (longRadix[i] = i**digitPerLong[i]).  Both arrays have
4697      * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
4698      * used.
4699      */
4700     private static int digitsPerLong[] = {0, 0,
4701         62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
4702         14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
4703 
4704     private static BigInteger longRadix[] = {null, null,
4705         valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
4706         valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
4707         valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
4708         valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
4709         valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
4710         valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
4711         valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
4712         valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
4713         valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
4714         valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
4715         valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
4716         valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
4717         valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
4718         valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
4719         valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
4720         valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
4721         valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
4722         valueOf(0x41c21cb8e1000000L)};
4723 
4724     /*
4725      * These two arrays are the integer analogue of above.
4726      */
4727     private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11,
4728         11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
4729         6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};
4730 
4731     private static int intRadix[] = {0, 0,
4732         0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
4733         0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
4734         0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f,  0x10000000,
4735         0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
4736         0x6c20a40,  0x8d2d931,  0xb640000,  0xe8d4a51,  0x1269ae40,
4737         0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
4738         0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
4739     };
4740 
4741     /**
4742      * These routines provide access to the two's complement representation
4743      * of BigIntegers.
4744      */
4745 
4746     /**
4747      * Returns the length of the two's complement representation in ints,
4748      * including space for at least one sign bit.
4749      */
4750     private int intLength() {
4751         return (bitLength() >>> 5) + 1;
4752     }
4753 
4754     /* Returns sign bit */
4755     private int signBit() {
4756         return signum < 0 ? 1 : 0;
4757     }
4758 
4759     /* Returns an int of sign bits */
4760     private int signInt() {
4761         return signum < 0 ? -1 : 0;
4762     }
4763 
4764     /**
4765      * Returns the specified int of the little-endian two's complement
4766      * representation (int 0 is the least significant).  The int number can
4767      * be arbitrarily high (values are logically preceded by infinitely many
4768      * sign ints).
4769      */
4770     private int getInt(int n) {
4771         if (n < 0)
4772             return 0;
4773         if (n >= mag.length)
4774             return signInt();
4775 
4776         int magInt = mag[mag.length-n-1];
4777 
4778         return (signum >= 0 ? magInt :
4779                 (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
4780     }
4781 
4782     /**
4783      * Returns the index of the int that contains the first nonzero int in the
4784      * little-endian binary representation of the magnitude (int 0 is the
4785      * least significant). If the magnitude is zero, return value is undefined.
4786      *
4787      * <p>Note: never used for a BigInteger with a magnitude of zero.
4788      * @see #getInt
4789      */
4790     private int firstNonzeroIntNum() {
4791         int fn = firstNonzeroIntNumPlusTwo - 2;
4792         if (fn == -2) { // firstNonzeroIntNum not initialized yet
4793             // Search for the first nonzero int
4794             int i;
4795             int mlen = mag.length;
4796             for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
4797                 ;
4798             fn = mlen - i - 1;
4799             firstNonzeroIntNumPlusTwo = fn + 2; // offset by two to initialize
4800         }
4801         return fn;
4802     }
4803 
4804     /** use serialVersionUID from JDK 1.1. for interoperability */
4805     @java.io.Serial
4806     private static final long serialVersionUID = -8287574255936472291L;
4807 
4808     /**
4809      * Serializable fields for BigInteger.
4810      *
4811      * @serialField signum  int
4812      *              signum of this BigInteger
4813      * @serialField magnitude byte[]
4814      *              magnitude array of this BigInteger
4815      * @serialField bitCount  int
4816      *              appears in the serialized form for backward compatibility
4817      * @serialField bitLength int
4818      *              appears in the serialized form for backward compatibility
4819      * @serialField firstNonzeroByteNum int
4820      *              appears in the serialized form for backward compatibility
4821      * @serialField lowestSetBit int
4822      *              appears in the serialized form for backward compatibility
4823      */
4824     @java.io.Serial
4825     private static final ObjectStreamField[] serialPersistentFields = {
4826         new ObjectStreamField("signum", Integer.TYPE),
4827         new ObjectStreamField("magnitude", byte[].class),
4828         new ObjectStreamField("bitCount", Integer.TYPE),
4829         new ObjectStreamField("bitLength", Integer.TYPE),
4830         new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
4831         new ObjectStreamField("lowestSetBit", Integer.TYPE)
4832         };
4833 
4834     /**
4835      * Reconstitute the {@code BigInteger} instance from a stream (that is,
4836      * deserialize it). The magnitude is read in as an array of bytes
4837      * for historical reasons, but it is converted to an array of ints
4838      * and the byte array is discarded.
4839      * Note:
4840      * The current convention is to initialize the cache fields, bitCountPlusOne,
4841      * bitLengthPlusOne and lowestSetBitPlusTwo, to 0 rather than some other
4842      * marker value. Therefore, no explicit action to set these fields needs to
4843      * be taken in readObject because those fields already have a 0 value by
4844      * default since defaultReadObject is not being used.
4845      *
4846      * @param  s the stream being read.
4847      * @throws IOException if an I/O error occurs
4848      * @throws ClassNotFoundException if a serialized class cannot be loaded
4849      */
4850     @java.io.Serial
4851     private void readObject(java.io.ObjectInputStream s)
4852         throws java.io.IOException, ClassNotFoundException {
4853         // prepare to read the alternate persistent fields
4854         ObjectInputStream.GetField fields = s.readFields();
4855 
4856         // Read and validate the alternate persistent fields that we
4857         // care about, signum and magnitude
4858 
4859         // Read and validate signum
4860         int sign = fields.get("signum", -2);
4861         if (sign < -1 || sign > 1) {
4862             String message = "BigInteger: Invalid signum value";
4863             if (fields.defaulted("signum"))
4864                 message = "BigInteger: Signum not present in stream";
4865             throw new java.io.StreamCorruptedException(message);
4866         }
4867 
4868         // Read and validate magnitude
4869         byte[] magnitude = (byte[])fields.get("magnitude", null);
4870         magnitude = magnitude.clone(); // defensive copy
4871         int[] mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);
4872         if ((mag.length == 0) != (sign == 0)) {
4873             String message = "BigInteger: signum-magnitude mismatch";
4874             if (fields.defaulted("magnitude"))
4875                 message = "BigInteger: Magnitude not present in stream";
4876             throw new java.io.StreamCorruptedException(message);
4877         }
4878 
4879         // Equivalent to checkRange() on mag local without assigning
4880         // this.mag field
4881         if (mag.length > MAX_MAG_LENGTH ||
4882             (mag.length == MAX_MAG_LENGTH && mag[0] < 0)) {
4883             throw new java.io.StreamCorruptedException("BigInteger: Out of the supported range");
4884         }
4885 
4886         // Commit final fields via Unsafe
4887         UnsafeHolder.putSignAndMag(this, sign, mag);
4888     }
4889 
4890     /**
4891      * Serialization without data not supported for this class.
4892      */
4893     @java.io.Serial
4894     private void readObjectNoData()
4895         throws ObjectStreamException {
4896         throw new InvalidObjectException("Deserialized BigInteger objects need data");
4897     }
4898 
4899     // Support for resetting final fields while deserializing
4900     private static class UnsafeHolder {
4901         private static final sun.misc.Unsafe unsafe;
4902         private static final long signumOffset;
4903         private static final long magOffset;
4904         static {
4905             try {
4906                 unsafe = sun.misc.Unsafe.getUnsafe();
4907                 signumOffset = unsafe.objectFieldOffset
4908                     (BigInteger.class.getDeclaredField("signum"));
4909                 magOffset = unsafe.objectFieldOffset
4910                     (BigInteger.class.getDeclaredField("mag"));
4911             } catch (Exception ex) {
4912                 throw new ExceptionInInitializerError(ex);
4913             }
4914         }
4915 
4916         static void putSignAndMag(BigInteger bi, int sign, int[] magnitude) {
4917             unsafe.putIntVolatile(bi, signumOffset, sign);
4918             unsafe.putObjectVolatile(bi, magOffset, magnitude);
4919         }
4920     }
4921 
4922     /**
4923      * Save the {@code BigInteger} instance to a stream.  The magnitude of a
4924      * {@code BigInteger} is serialized as a byte array for historical reasons.
4925      * To maintain compatibility with older implementations, the integers
4926      * -1, -1, -2, and -2 are written as the values of the obsolete fields
4927      * {@code bitCount}, {@code bitLength}, {@code lowestSetBit}, and
4928      * {@code firstNonzeroByteNum}, respectively.  These values are compatible
4929      * with older implementations, but will be ignored by current
4930      * implementations.
4931      *
4932      * @param  s the stream to serialize to.
4933      * @throws IOException if an I/O error occurs
4934      */
4935     @java.io.Serial
4936     private void writeObject(ObjectOutputStream s) throws IOException {
4937         // set the values of the Serializable fields
4938         ObjectOutputStream.PutField fields = s.putFields();
4939         fields.put("signum", signum);
4940         fields.put("magnitude", magSerializedForm());
4941         // The values written for cached fields are compatible with older
4942         // versions, but are ignored in readObject so don't otherwise matter.
4943         // BEGIN Android-changed: Don't include the following fields.
4944         /*
4945         fields.put("bitCount", -1);
4946         fields.put("bitLength", -1);
4947         fields.put("lowestSetBit", -2);
4948         fields.put("firstNonzeroByteNum", -2);
4949         */
4950         // END Android-changed: Don't include the following fields.
4951 
4952         // save them
4953         s.writeFields();
4954     }
4955 
4956     /**
4957      * Returns the mag array as an array of bytes.
4958      */
4959     private byte[] magSerializedForm() {
4960         int len = mag.length;
4961 
4962         int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0]));
4963         int byteLen = (bitLen + 7) >>> 3;
4964         byte[] result = new byte[byteLen];
4965 
4966         for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;
4967              i >= 0; i--) {
4968             if (bytesCopied == 4) {
4969                 nextInt = mag[intIndex--];
4970                 bytesCopied = 1;
4971             } else {
4972                 nextInt >>>= 8;
4973                 bytesCopied++;
4974             }
4975             result[i] = (byte)nextInt;
4976         }
4977         return result;
4978     }
4979 
4980     /**
4981      * Converts this {@code BigInteger} to a {@code long}, checking
4982      * for lost information.  If the value of this {@code BigInteger}
4983      * is out of the range of the {@code long} type, then an
4984      * {@code ArithmeticException} is thrown.
4985      *
4986      * @return this {@code BigInteger} converted to a {@code long}.
4987      * @throws ArithmeticException if the value of {@code this} will
4988      * not exactly fit in a {@code long}.
4989      * @see BigInteger#longValue
4990      * @since  1.8
4991      */
4992     public long longValueExact() {
4993         if (mag.length <= 2 && bitLength() <= 63)
4994             return longValue();
4995         else
4996             throw new ArithmeticException("BigInteger out of long range");
4997     }
4998 
4999     /**
5000      * Converts this {@code BigInteger} to an {@code int}, checking
5001      * for lost information.  If the value of this {@code BigInteger}
5002      * is out of the range of the {@code int} type, then an
5003      * {@code ArithmeticException} is thrown.
5004      *
5005      * @return this {@code BigInteger} converted to an {@code int}.
5006      * @throws ArithmeticException if the value of {@code this} will
5007      * not exactly fit in an {@code int}.
5008      * @see BigInteger#intValue
5009      * @since  1.8
5010      */
5011     public int intValueExact() {
5012         if (mag.length <= 1 && bitLength() <= 31)
5013             return intValue();
5014         else
5015             throw new ArithmeticException("BigInteger out of int range");
5016     }
5017 
5018     /**
5019      * Converts this {@code BigInteger} to a {@code short}, checking
5020      * for lost information.  If the value of this {@code BigInteger}
5021      * is out of the range of the {@code short} type, then an
5022      * {@code ArithmeticException} is thrown.
5023      *
5024      * @return this {@code BigInteger} converted to a {@code short}.
5025      * @throws ArithmeticException if the value of {@code this} will
5026      * not exactly fit in a {@code short}.
5027      * @see BigInteger#shortValue
5028      * @since  1.8
5029      */
5030     public short shortValueExact() {
5031         if (mag.length <= 1 && bitLength() <= 31) {
5032             int value = intValue();
5033             if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE)
5034                 return shortValue();
5035         }
5036         throw new ArithmeticException("BigInteger out of short range");
5037     }
5038 
5039     /**
5040      * Converts this {@code BigInteger} to a {@code byte}, checking
5041      * for lost information.  If the value of this {@code BigInteger}
5042      * is out of the range of the {@code byte} type, then an
5043      * {@code ArithmeticException} is thrown.
5044      *
5045      * @return this {@code BigInteger} converted to a {@code byte}.
5046      * @throws ArithmeticException if the value of {@code this} will
5047      * not exactly fit in a {@code byte}.
5048      * @see BigInteger#byteValue
5049      * @since  1.8
5050      */
5051     public byte byteValueExact() {
5052         if (mag.length <= 1 && bitLength() <= 31) {
5053             int value = intValue();
5054             if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE)
5055                 return byteValue();
5056         }
5057         throw new ArithmeticException("BigInteger out of byte range");
5058     }
5059 }
5060