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