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