-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathBigInteger.java
5161 lines (4602 loc) · 191 KB
/
BigInteger.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* Portions Copyright (c) 1995 Colin Plumb. All rights reserved.
*/
package java.math;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.ObjectStreamException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ThreadLocalRandom;
import jdk.internal.math.DoubleConsts;
import jdk.internal.math.FloatConsts;
import jdk.internal.util.ArraysSupport;
import jdk.internal.vm.annotation.ForceInline;
import jdk.internal.vm.annotation.IntrinsicCandidate;
import jdk.internal.vm.annotation.Stable;
/**
* Immutable arbitrary-precision integers. All operations behave as if
* BigIntegers were represented in two's-complement notation (like Java's
* primitive integer types). BigInteger provides analogues to all of Java's
* primitive integer operators, and all relevant methods from java.lang.Math.
* Additionally, BigInteger provides operations for modular arithmetic, GCD
* calculation, primality testing, prime generation, bit manipulation,
* and a few other miscellaneous operations.
*
* <p>Semantics of arithmetic operations exactly mimic those of Java's integer
* arithmetic operators, as defined in <i>The Java Language Specification</i>.
* For example, division by zero throws an {@code ArithmeticException}, and
* division of a negative by a positive yields a negative (or zero) remainder.
*
* <p>Semantics of shift operations extend those of Java's shift operators
* to allow for negative shift distances. A right-shift with a negative
* shift distance results in a left shift, and vice-versa. The unsigned
* right shift operator ({@code >>>}) is omitted since this operation
* only makes sense for a fixed sized word and not for a
* representation conceptually having an infinite number of leading
* virtual sign bits.
*
* <p>Semantics of bitwise logical operations exactly mimic those of Java's
* bitwise integer operators. The binary operators ({@code and},
* {@code or}, {@code xor}) implicitly perform sign extension on the shorter
* of the two operands prior to performing the operation.
*
* <p>Comparison operations perform signed integer comparisons, analogous to
* those performed by Java's relational and equality operators.
*
* <p>Modular arithmetic operations are provided to compute residues, perform
* exponentiation, and compute multiplicative inverses. These methods always
* return a non-negative result, between {@code 0} and {@code (modulus - 1)},
* inclusive.
*
* <p>Bit operations operate on a single bit of the two's-complement
* representation of their operand. If necessary, the operand is sign-extended
* so that it contains the designated bit. None of the single-bit
* operations can produce a BigInteger with a different sign from the
* BigInteger being operated on, as they affect only a single bit, and the
* arbitrarily large abstraction provided by this class ensures that conceptually
* there are infinitely many "virtual sign bits" preceding each BigInteger.
*
* <p>For the sake of brevity and clarity, pseudo-code is used throughout the
* descriptions of BigInteger methods. The pseudo-code expression
* {@code (i + j)} is shorthand for "a BigInteger whose value is
* that of the BigInteger {@code i} plus that of the BigInteger {@code j}."
* The pseudo-code expression {@code (i == j)} is shorthand for
* "{@code true} if and only if the BigInteger {@code i} represents the same
* value as the BigInteger {@code j}." Other pseudo-code expressions are
* interpreted similarly.
*
* <p>All methods and constructors in this class throw
* {@code NullPointerException} when passed
* a null object reference for any input parameter.
*
* BigInteger must support values in the range
* -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
* +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive)
* and may support values outside of that range.
*
* An {@code ArithmeticException} is thrown when a BigInteger
* constructor or method would generate a value outside of the
* supported range.
*
* The range of probable prime values is limited and may be less than
* the full supported positive range of {@code BigInteger}.
* The range must be at least 1 to 2<sup>500000000</sup>.
*
* @apiNote
* <span id="algorithmicComplexity">As {@code BigInteger} values are
* arbitrary precision integers, the algorithmic complexity of the
* methods of this class varies and may be superlinear in the size of
* the input. For example, a method like {@link intValue()} would be
* expected to run in <i>O</i>(1), that is constant time, since with
* the current internal representation only a fixed-size component of
* the {@code BigInteger} needs to be accessed to perform the
* conversion to {@code int}. In contrast, a method like {@link not()}
* would be expected to run in <i>O</i>(<i>n</i>) time where <i>n</i>
* is the size of the {@code BigInteger} in bits, that is, to run in
* time proportional to the size of the input. For multiplying two
* {@code BigInteger} values of size <i>n</i>, a naive multiplication
* algorithm would run in time <i>O</i>(<i>n<sup>2</sup></i>) and
* theoretical results indicate a multiplication algorithm for numbers
* using this category of representation must run in <em>at least</em>
* <i>O</i>(<i>n</i> log <i>n</i>). Common multiplication
* algorithms between the bounds of the naive and theoretical cases
* include the Karatsuba multiplication
* (<i>O</i>(<i>n<sup>1.585</sup></i>)) and 3-way Toom-Cook
* multiplication (<i>O</i>(<i>n<sup>1.465</sup></i>)).</span>
*
* <p>A particular implementation of {@link multiply(BigInteger)
* multiply} is free to switch between different algorithms for
* different inputs, such as to improve actual running time to produce
* the product by using simpler algorithms for smaller inputs even if
* the simpler algorithm has a larger asymptotic complexity.
*
* <p>Operations may also allocate and compute on intermediate
* results, potentially those allocations may be as large as in
* proportion to the running time of the algorithm.
*
* <p>Users of {@code BigInteger} concerned with bounding the running
* time or space of operations can screen out {@code BigInteger}
* values above a chosen magnitude.
*
* @implNote
* In the reference implementation, BigInteger constructors and
* operations throw {@code ArithmeticException} when the result is out
* of the supported range of
* -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to
* +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive).
*
* @see BigDecimal
* @jls 4.2.2 Integer Operations
* @author Josh Bloch
* @author Michael McCloskey
* @author Alan Eliasen
* @author Timothy Buktu
* @since 1.1
*/
public class BigInteger extends Number implements Comparable<BigInteger> {
/**
* The signum of this BigInteger: -1 for negative, 0 for zero, or
* 1 for positive. Note that the BigInteger zero <em>must</em> have
* a signum of 0. This is necessary to ensures that there is exactly one
* representation for each BigInteger value.
*/
final int signum;
/**
* The magnitude of this BigInteger, in <i>big-endian</i> order: the
* zeroth element of this array is the most-significant int of the
* magnitude. The magnitude must be "minimal" in that the most-significant
* int ({@code mag[0]}) must be non-zero. This is necessary to
* ensure that there is exactly one representation for each BigInteger
* value. Note that this implies that the BigInteger zero has a
* zero-length mag array.
*/
final int[] mag;
// The following fields are stable variables. A stable variable's value
// changes at most once from the default zero value to a non-zero stable
// value. A stable value is calculated lazily on demand.
/**
* One plus the bitCount of this BigInteger. This is a stable variable.
*
* @see #bitCount
*/
private int bitCountPlusOne;
/**
* One plus the bitLength of this BigInteger. This is a stable variable.
* (either value is acceptable).
*
* @see #bitLength()
*/
private int bitLengthPlusOne;
/**
* Two plus the lowest set bit of this BigInteger. This is a stable variable.
*
* @see #getLowestSetBit
*/
private int lowestSetBitPlusTwo;
/**
* Two plus the index of the lowest-order int in the magnitude of this
* BigInteger that contains a nonzero int. This is a stable variable. The
* least significant int has int-number 0, the next int in order of
* increasing significance has int-number 1, and so forth.
*
* <p>Note: never used for a BigInteger with a magnitude of zero.
*
* @see #firstNonzeroIntNum()
*/
private int firstNonzeroIntNumPlusTwo;
/**
* This mask is used to obtain the value of an int as if it were unsigned.
*/
static final long LONG_MASK = 0xffffffffL;
/**
* This constant limits {@code mag.length} of BigIntegers to the supported
* range.
*/
private static final int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26)
/**
* Bit lengths larger than this constant can cause overflow in searchLen
* calculation and in BitSieve.singleSearch method.
*/
private static final int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;
/**
* The threshold value for using Karatsuba multiplication. If the number
* of ints in both mag arrays are greater than this number, then
* Karatsuba multiplication will be used. This value is found
* experimentally to work well.
*/
private static final int KARATSUBA_THRESHOLD = 80;
/**
* The threshold value for using 3-way Toom-Cook multiplication.
* If the number of ints in each mag array is greater than the
* Karatsuba threshold, and the number of ints in at least one of
* the mag arrays is greater than this threshold, then Toom-Cook
* multiplication will be used.
*/
private static final int TOOM_COOK_THRESHOLD = 240;
/**
* The threshold value for using Karatsuba squaring. If the number
* of ints in the number are larger than this value,
* Karatsuba squaring will be used. This value is found
* experimentally to work well.
*/
private static final int KARATSUBA_SQUARE_THRESHOLD = 128;
/**
* The threshold value for using Toom-Cook squaring. If the number
* of ints in the number are larger than this value,
* Toom-Cook squaring will be used. This value is found
* experimentally to work well.
*/
private static final int TOOM_COOK_SQUARE_THRESHOLD = 216;
/**
* The threshold value for using Burnikel-Ziegler division. If the number
* of ints in the divisor are larger than this value, Burnikel-Ziegler
* division may be used. This value is found experimentally to work well.
*/
static final int BURNIKEL_ZIEGLER_THRESHOLD = 80;
/**
* The offset value for using Burnikel-Ziegler division. If the number
* of ints in the divisor exceeds the Burnikel-Ziegler threshold, and the
* number of ints in the dividend is greater than the number of ints in the
* divisor plus this value, Burnikel-Ziegler division will be used. This
* value is found experimentally to work well.
*/
static final int BURNIKEL_ZIEGLER_OFFSET = 40;
/**
* The threshold value for using Schoenhage recursive base conversion. If
* the number of ints in the number are larger than this value,
* the Schoenhage algorithm will be used. In practice, it appears that the
* Schoenhage routine is faster for any threshold down to 2, and is
* relatively flat for thresholds between 2-25, so this choice may be
* varied within this range for very small effect.
*/
private static final int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20;
/**
* The threshold value for using squaring code to perform multiplication
* of a {@code BigInteger} instance by itself. If the number of ints in
* the number are larger than this value, {@code multiply(this)} will
* return {@code square()}.
*/
private static final int MULTIPLY_SQUARE_THRESHOLD = 20;
/**
* The threshold for using an intrinsic version of
* implMontgomeryXXX to perform Montgomery multiplication. If the
* number of ints in the number is more than this value we do not
* use the intrinsic.
*/
private static final int MONTGOMERY_INTRINSIC_THRESHOLD = 512;
// Constructors
/**
* Translates a byte sub-array containing the two's-complement binary
* representation of a BigInteger into a BigInteger. The sub-array is
* specified via an offset into the array and a length. The sub-array is
* assumed to be in <i>big-endian</i> byte-order: the most significant
* byte is the element at index {@code off}. The {@code val} array is
* assumed to be unchanged for the duration of the constructor call.
*
* An {@code IndexOutOfBoundsException} is thrown if the length of the array
* {@code val} is non-zero and either {@code off} is negative, {@code len}
* is negative, or {@code off+len} is greater than the length of
* {@code val}.
*
* @param val byte array containing a sub-array which is the big-endian
* two's-complement binary representation of a BigInteger.
* @param off the start offset of the binary representation.
* @param len the number of bytes to use.
* @throws NumberFormatException {@code val} is zero bytes long.
* @throws IndexOutOfBoundsException if the provided array offset and
* length would cause an index into the byte array to be
* negative or greater than or equal to the array length.
* @since 9
*/
public BigInteger(byte[] val, int off, int len) {
if (val.length == 0) {
throw new NumberFormatException("Zero length BigInteger");
}
Objects.checkFromIndexSize(off, len, val.length);
if (len == 0) {
mag = ZERO.mag;
signum = ZERO.signum;
return;
}
int b = val[off];
if (b < 0) {
mag = makePositive(b, val, off, len);
signum = -1;
} else {
mag = stripLeadingZeroBytes(b, val, off, len);
signum = (mag.length == 0 ? 0 : 1);
}
if (mag.length >= MAX_MAG_LENGTH) {
checkRange();
}
}
/**
* Translates a byte array containing the two's-complement binary
* representation of a BigInteger into a BigInteger. The input array is
* assumed to be in <i>big-endian</i> byte-order: the most significant
* byte is in the zeroth element. The {@code val} array is assumed to be
* unchanged for the duration of the constructor call.
*
* @param val big-endian two's-complement binary representation of a
* BigInteger.
* @throws NumberFormatException {@code val} is zero bytes long.
*/
public BigInteger(byte[] val) {
this(val, 0, val.length);
}
/**
* This private constructor translates an int array containing the
* two's-complement binary representation of a BigInteger into a
* BigInteger. The input array is assumed to be in <i>big-endian</i>
* int-order: the most significant int is in the zeroth element. The
* {@code val} array is assumed to be unchanged for the duration of
* the constructor call.
*/
private BigInteger(int[] val) {
if (val.length == 0)
throw new NumberFormatException("Zero length BigInteger");
if (val[0] < 0) {
mag = makePositive(val);
signum = -1;
} else {
mag = trustedStripLeadingZeroInts(val);
signum = (mag.length == 0 ? 0 : 1);
}
if (mag.length >= MAX_MAG_LENGTH) {
checkRange();
}
}
/**
* Translates the sign-magnitude representation of a BigInteger into a
* BigInteger. The sign is represented as an integer signum value: -1 for
* negative, 0 for zero, or 1 for positive. The magnitude is a sub-array of
* a byte array in <i>big-endian</i> byte-order: the most significant byte
* is the element at index {@code off}. A zero value of the length
* {@code len} is permissible, and will result in a BigInteger value of 0,
* whether signum is -1, 0 or 1. The {@code magnitude} array is assumed to
* be unchanged for the duration of the constructor call.
*
* An {@code IndexOutOfBoundsException} is thrown if the length of the array
* {@code magnitude} is non-zero and either {@code off} is negative,
* {@code len} is negative, or {@code off+len} is greater than the length of
* {@code magnitude}.
*
* @param signum signum of the number (-1 for negative, 0 for zero, 1
* for positive).
* @param magnitude big-endian binary representation of the magnitude of
* the number.
* @param off the start offset of the binary representation.
* @param len the number of bytes to use.
* @throws NumberFormatException {@code signum} is not one of the three
* legal values (-1, 0, and 1), or {@code signum} is 0 and
* {@code magnitude} contains one or more non-zero bytes.
* @throws IndexOutOfBoundsException if the provided array offset and
* length would cause an index into the byte array to be
* negative or greater than or equal to the array length.
* @since 9
*/
public BigInteger(int signum, byte[] magnitude, int off, int len) {
if (signum < -1 || signum > 1) {
throw(new NumberFormatException("Invalid signum value"));
}
Objects.checkFromIndexSize(off, len, magnitude.length);
// stripLeadingZeroBytes() returns a zero length array if len == 0
this.mag = stripLeadingZeroBytes(magnitude, off, len);
if (this.mag.length == 0) {
this.signum = 0;
} else {
if (signum == 0)
throw(new NumberFormatException("signum-magnitude mismatch"));
this.signum = signum;
}
if (mag.length >= MAX_MAG_LENGTH) {
checkRange();
}
}
/**
* Translates the sign-magnitude representation of a BigInteger into a
* BigInteger. The sign is represented as an integer signum value: -1 for
* negative, 0 for zero, or 1 for positive. The magnitude is a byte array
* in <i>big-endian</i> byte-order: the most significant byte is the
* zeroth element. A zero-length magnitude array is permissible, and will
* result in a BigInteger value of 0, whether signum is -1, 0 or 1. The
* {@code magnitude} array is assumed to be unchanged for the duration of
* the constructor call.
*
* @param signum signum of the number (-1 for negative, 0 for zero, 1
* for positive).
* @param magnitude big-endian binary representation of the magnitude of
* the number.
* @throws NumberFormatException {@code signum} is not one of the three
* legal values (-1, 0, and 1), or {@code signum} is 0 and
* {@code magnitude} contains one or more non-zero bytes.
*/
public BigInteger(int signum, byte[] magnitude) {
this(signum, magnitude, 0, magnitude.length);
}
/**
* A constructor for internal use that translates the sign-magnitude
* representation of a BigInteger into a BigInteger. It checks the
* arguments and copies the magnitude so this constructor would be
* safe for external use. The {@code magnitude} array is assumed to be
* unchanged for the duration of the constructor call.
*/
private BigInteger(int signum, int[] magnitude) {
this.mag = stripLeadingZeroInts(magnitude);
if (signum < -1 || signum > 1)
throw(new NumberFormatException("Invalid signum value"));
if (this.mag.length == 0) {
this.signum = 0;
} else {
if (signum == 0)
throw(new NumberFormatException("signum-magnitude mismatch"));
this.signum = signum;
}
if (mag.length >= MAX_MAG_LENGTH) {
checkRange();
}
}
/**
* Translates the String representation of a BigInteger in the
* specified radix into a BigInteger. The String representation
* consists of an optional minus or plus sign followed by a
* sequence of one or more digits in the specified radix. The
* character-to-digit mapping is provided by {@link
* Character#digit(char, int) Character.digit}. The String may
* not contain any extraneous characters (whitespace, for
* example).
*
* @param val String representation of BigInteger.
* @param radix radix to be used in interpreting {@code val}.
* @throws NumberFormatException {@code val} is not a valid representation
* of a BigInteger in the specified radix, or {@code radix} is
* outside the range from {@link Character#MIN_RADIX} to
* {@link Character#MAX_RADIX}, inclusive.
*/
public BigInteger(String val, int radix) {
int cursor = 0, numDigits;
final int len = val.length();
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
throw new NumberFormatException("Radix out of range");
if (len == 0)
throw new NumberFormatException("Zero length BigInteger");
// Check for at most one leading sign
int sign = 1;
int index1 = val.lastIndexOf('-');
int index2 = val.lastIndexOf('+');
if (index1 >= 0) {
if (index1 != 0 || index2 >= 0) {
throw new NumberFormatException("Illegal embedded sign character");
}
sign = -1;
cursor = 1;
} else if (index2 >= 0) {
if (index2 != 0) {
throw new NumberFormatException("Illegal embedded sign character");
}
cursor = 1;
}
if (cursor == len)
throw new NumberFormatException("Zero length BigInteger");
// Skip leading zeros and compute number of digits in magnitude
while (cursor < len &&
Character.digit(val.charAt(cursor), radix) == 0) {
cursor++;
}
if (cursor == len) {
signum = 0;
mag = ZERO.mag;
return;
}
numDigits = len - cursor;
signum = sign;
// Pre-allocate array of expected size. May be too large but can
// never be too small. Typically exact.
long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1;
if (numBits + 31 >= (1L << 32)) {
reportOverflow();
}
int numWords = (int) (numBits + 31) >>> 5;
int[] magnitude = new int[numWords];
// Process first (potentially short) digit group
int firstGroupLen = numDigits % digitsPerInt[radix];
if (firstGroupLen == 0)
firstGroupLen = digitsPerInt[radix];
String group = val.substring(cursor, cursor += firstGroupLen);
magnitude[numWords - 1] = Integer.parseInt(group, radix);
if (magnitude[numWords - 1] < 0)
throw new NumberFormatException("Illegal digit");
// Process remaining digit groups
int superRadix = intRadix[radix];
int groupVal = 0;
while (cursor < len) {
group = val.substring(cursor, cursor += digitsPerInt[radix]);
groupVal = Integer.parseInt(group, radix);
if (groupVal < 0)
throw new NumberFormatException("Illegal digit");
destructiveMulAdd(magnitude, superRadix, groupVal);
}
// Required for cases where the array was overallocated.
mag = trustedStripLeadingZeroInts(magnitude);
if (mag.length >= MAX_MAG_LENGTH) {
checkRange();
}
}
/*
* Constructs a new BigInteger using a char array with radix=10.
* Sign is precalculated outside and not allowed in the val. The {@code val}
* array is assumed to be unchanged for the duration of the constructor
* call.
*/
BigInteger(char[] val, int sign, int len) {
int cursor = 0, numDigits;
// Skip leading zeros and compute number of digits in magnitude
while (cursor < len && Character.digit(val[cursor], 10) == 0) {
cursor++;
}
if (cursor == len) {
signum = 0;
mag = ZERO.mag;
return;
}
numDigits = len - cursor;
signum = sign;
// Pre-allocate array of expected size
int numWords;
if (len < 10) {
numWords = 1;
} else {
long numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1;
if (numBits + 31 >= (1L << 32)) {
reportOverflow();
}
numWords = (int) (numBits + 31) >>> 5;
}
int[] magnitude = new int[numWords];
// Process first (potentially short) digit group
int firstGroupLen = numDigits % digitsPerInt[10];
if (firstGroupLen == 0)
firstGroupLen = digitsPerInt[10];
magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen);
// Process remaining digit groups
while (cursor < len) {
int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
destructiveMulAdd(magnitude, intRadix[10], groupVal);
}
mag = trustedStripLeadingZeroInts(magnitude);
if (mag.length >= MAX_MAG_LENGTH) {
checkRange();
}
}
// Create an integer with the digits between the two indexes
// Assumes start < end. The result may be negative, but it
// is to be treated as an unsigned value.
private int parseInt(char[] source, int start, int end) {
int result = Character.digit(source[start++], 10);
if (result == -1)
throw new NumberFormatException(new String(source));
for (int index = start; index < end; index++) {
int nextVal = Character.digit(source[index], 10);
if (nextVal == -1)
throw new NumberFormatException(new String(source));
result = 10*result + nextVal;
}
return result;
}
// bitsPerDigit in the given radix times 1024
// Rounded up to avoid underallocation.
private static long bitsPerDigit[] = { 0, 0,
1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
5253, 5295};
// Multiply x array times word y in place, and add word z
private static void destructiveMulAdd(int[] x, int y, int z) {
// Perform the multiplication word by word
long ylong = y & LONG_MASK;
long zlong = z & LONG_MASK;
int len = x.length;
long product = 0;
long carry = 0;
for (int i = len-1; i >= 0; i--) {
product = ylong * (x[i] & LONG_MASK) + carry;
x[i] = (int)product;
carry = product >>> 32;
}
// Perform the addition
long sum = (x[len-1] & LONG_MASK) + zlong;
x[len-1] = (int)sum;
carry = sum >>> 32;
for (int i = len-2; i >= 0; i--) {
sum = (x[i] & LONG_MASK) + carry;
x[i] = (int)sum;
carry = sum >>> 32;
}
}
/**
* Translates the decimal String representation of a BigInteger
* into a BigInteger. The String representation consists of an
* optional minus or plus sign followed by a sequence of one or
* more decimal digits. The character-to-digit mapping is
* provided by {@link Character#digit(char, int)
* Character.digit}. The String may not contain any extraneous
* characters (whitespace, for example).
*
* @param val decimal String representation of BigInteger.
* @throws NumberFormatException {@code val} is not a valid representation
* of a BigInteger.
*/
public BigInteger(String val) {
this(val, 10);
}
/**
* Constructs a randomly generated BigInteger, uniformly distributed over
* the range 0 to (2<sup>{@code numBits}</sup> - 1), inclusive.
* The uniformity of the distribution assumes that a fair source of random
* bits is provided in {@code rnd}. Note that this constructor always
* constructs a non-negative BigInteger.
*
* @param numBits maximum bitLength of the new BigInteger.
* @param rnd source of randomness to be used in computing the new
* BigInteger.
* @throws IllegalArgumentException {@code numBits} is negative.
* @see #bitLength()
*/
public BigInteger(int numBits, Random rnd) {
byte[] magnitude = randomBits(numBits, rnd);
try {
// stripLeadingZeroBytes() returns a zero length array if len == 0
this.mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length);
if (this.mag.length == 0) {
this.signum = 0;
} else {
this.signum = 1;
}
if (mag.length >= MAX_MAG_LENGTH) {
checkRange();
}
} finally {
Arrays.fill(magnitude, (byte)0);
}
}
private static byte[] randomBits(int numBits, Random rnd) {
if (numBits < 0)
throw new IllegalArgumentException("numBits must be non-negative");
int numBytes = (int)(((long)numBits+7)/8); // avoid overflow
byte[] randomBits = new byte[numBytes];
// Generate random bytes and mask out any excess bits
if (numBytes > 0) {
rnd.nextBytes(randomBits);
int excessBits = 8*numBytes - numBits;
randomBits[0] &= (byte)((1 << (8-excessBits)) - 1);
}
return randomBits;
}
/**
* Constructs a randomly generated positive BigInteger that is probably
* prime, with the specified bitLength.
*
* @apiNote It is recommended that the {@link #probablePrime probablePrime}
* method be used in preference to this constructor unless there
* is a compelling need to specify a certainty.
*
* @param bitLength bitLength of the returned BigInteger.
* @param certainty a measure of the uncertainty that the caller is
* willing to tolerate. The probability that the new BigInteger
* represents a prime number will exceed
* (1 - 1/2<sup>{@code certainty}</sup>). The execution time of
* this constructor is proportional to the value of this parameter.
* @param rnd source of random bits used to select candidates to be
* tested for primality.
* @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.
* @see #bitLength()
*/
public BigInteger(int bitLength, int certainty, Random rnd) {
BigInteger prime;
if (bitLength < 2)
throw new ArithmeticException("bitLength < 2");
prime = (bitLength < SMALL_PRIME_THRESHOLD
? smallPrime(bitLength, certainty, rnd)
: largePrime(bitLength, certainty, rnd));
signum = 1;
mag = prime.mag;
}
// Minimum size in bits that the requested prime number has
// before we use the large prime number generating algorithms.
// The cutoff of 95 was chosen empirically for best performance.
private static final int SMALL_PRIME_THRESHOLD = 95;
// Certainty required to meet the spec of probablePrime
private static final int DEFAULT_PRIME_CERTAINTY = 100;
/**
* Returns a positive BigInteger that is probably prime, with the
* specified bitLength. The probability that a BigInteger returned
* by this method is composite does not exceed 2<sup>-100</sup>.
*
* @param bitLength bitLength of the returned BigInteger.
* @param rnd source of random bits used to select candidates to be
* tested for primality.
* @return a BigInteger of {@code bitLength} bits that is probably prime
* @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large.
* @see #bitLength()
* @since 1.4
*/
public static BigInteger probablePrime(int bitLength, Random rnd) {
if (bitLength < 2)
throw new ArithmeticException("bitLength < 2");
return (bitLength < SMALL_PRIME_THRESHOLD ?
smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
}
/**
* Find a random number of the specified bitLength that is probably prime.
* This method is used for smaller primes, its performance degrades on
* larger bitlengths.
*
* This method assumes bitLength > 1.
*/
private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
int magLen = (bitLength + 31) >>> 5;
int temp[] = new int[magLen];
int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int
int highMask = (highBit << 1) - 1; // Bits to keep in high int
while (true) {
// Construct a candidate
for (int i=0; i < magLen; i++)
temp[i] = rnd.nextInt();
temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length
if (bitLength > 2)
temp[magLen-1] |= 1; // Make odd if bitlen > 2
BigInteger p = new BigInteger(temp, 1);
// Do cheap "pre-test" if applicable
if (bitLength > 6) {
long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
(r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
(r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
continue; // Candidate is composite; try another
}
// All candidates of bitLength 2 and 3 are prime by this point
if (bitLength < 4)
return p;
// Do expensive test if we survive pre-test (or it's inapplicable)
if (p.primeToCertainty(certainty, rnd))
return p;
}
}
private static final BigInteger SMALL_PRIME_PRODUCT
= valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
/**
* Find a random number of the specified bitLength that is probably prime.
* This method is more appropriate for larger bitlengths since it uses
* a sieve to eliminate most composites before using a more expensive
* test.
*/
private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
BigInteger p;
p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
p.mag[p.mag.length-1] &= 0xfffffffe;
// Use a sieve length likely to contain the next prime number
int searchLen = getPrimeSearchLen(bitLength);
BitSieve searchSieve = new BitSieve(p, searchLen);
BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);
while ((candidate == null) || (candidate.bitLength() != bitLength)) {
p = p.add(BigInteger.valueOf(2*searchLen));
if (p.bitLength() != bitLength)
p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
p.mag[p.mag.length-1] &= 0xfffffffe;
searchSieve = new BitSieve(p, searchLen);
candidate = searchSieve.retrieve(p, certainty, rnd);
}
return candidate;
}
/**
* Returns the first integer greater than this {@code BigInteger} that
* is probably prime. The probability that the number returned by this
* method is composite does not exceed 2<sup>-100</sup>. This method will
* never skip over a prime when searching: if it returns {@code p}, there
* is no prime {@code q} such that {@code this < q < p}.
*
* @return the first integer greater than this {@code BigInteger} that
* is probably prime.
* @throws ArithmeticException {@code this < 0} or {@code this} is too large.
* @implNote Due to the nature of the underlying algorithm,
* and depending on the size of {@code this},
* this method could consume a large amount of memory, up to
* exhaustion of available heap space, or could run for a long time.
* @since 1.5
*/
public BigInteger nextProbablePrime() {
if (this.signum < 0)
throw new ArithmeticException("start < 0: " + this);
// Handle trivial cases
if ((this.signum == 0) || this.equals(ONE))
return TWO;
BigInteger result = this.add(ONE);
// Fastpath for small numbers
if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
// Ensure an odd number
if (!result.testBit(0))
result = result.add(ONE);
while (true) {
// Do cheap "pre-test" if applicable
if (result.bitLength() > 6) {
long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
(r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
(r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {
result = result.add(TWO);
continue; // Candidate is composite; try another
}
}
// All candidates of bitLength 2 and 3 are prime by this point
if (result.bitLength() < 4)
return result;
// The expensive test
if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))
return result;
result = result.add(TWO);
}
}
// Start at previous even number
if (result.testBit(0))
result = result.subtract(ONE);
// Looking for the next large prime
int searchLen = getPrimeSearchLen(result.bitLength());
while (true) {
BitSieve searchSieve = new BitSieve(result, searchLen);
BigInteger candidate = searchSieve.retrieve(result,
DEFAULT_PRIME_CERTAINTY, null);
if (candidate != null)
return candidate;
result = result.add(BigInteger.valueOf(2 * searchLen));
}
}
private static int getPrimeSearchLen(int bitLength) {
if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) {
throw new ArithmeticException("Prime search implementation restriction on bitLength");
}
return bitLength / 20 * 64;
}
/**
* Returns {@code true} if this BigInteger is probably prime,
* {@code false} if it's definitely composite.
*
* This method assumes bitLength > 2.
*
* @param certainty a measure of the uncertainty that the caller is
* willing to tolerate: if the call returns {@code true}
* the probability that this BigInteger is prime exceeds
* <code>(1 - 1/2<sup>certainty</sup>)</code>. The execution time of
* this method is proportional to the value of this parameter.
* @return {@code true} if this BigInteger is probably prime,
* {@code false} if it's definitely composite.
*/