-
Notifications
You must be signed in to change notification settings - Fork 668
/
BigInteger.java
4948 lines (4361 loc) · 187 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, 2018, 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 jdk.internal.HotSpotIntrinsicCandidate;
import jdk.internal.math.DoubleConsts;
import jdk.internal.math.FloatConsts;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* 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>.
*
* @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
*/
/*
* 大整数
*
* BigInteger将符号位和数值分开存储,其存储数据的基本原理是将数据切割成不同的分段后存入数组
*
* 注:该对象本身是不可变的,类似String,在运算之后会产生一个新对象
*/
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.
*/
// BigInteger符号位,用-1、0、1分别表示该数值为负数、0、正数
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.
*/
// BigInteger数值
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;
/**
* Initialize static constant array when class is loaded.
*/
private static final int MAX_CONSTANT = 16;
private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
/**
* The cache of powers of each radix. This allows us to not have to
* recalculate powers of radix^(2^n) more than once. This speeds
* Schoenhage recursive base conversion significantly.
*/
private static volatile BigInteger[][] powerCache;
/** The cache of logarithms of radices for base conversion. */
private static final double[] logCache;
/** The natural log of 2. This is used in computing cache indices. */
private static final double LOG_TWO = Math.log(2.0);
/**
* The BigInteger constant zero.
*
* @since 1.2
*/
// 代表0
public static final BigInteger ZERO = new BigInteger(new int[0], 0);
/**
* The BigInteger constant one.
*
* @since 1.2
*/
// 代表1
public static final BigInteger ONE = valueOf(1);
/**
* The BigInteger constant two.
*
* @since 9
*/
// 代表2
public static final BigInteger TWO = valueOf(2);
/**
* The BigInteger constant -1. (Not exported.)
*/
// 代表-1
private static final BigInteger NEGATIVE_ONE = valueOf(-1);
/**
* The BigInteger constant ten.
*
* @since 1.5
*/
// 代表10
public static final BigInteger TEN = valueOf(10);
// bitsPerDigit in the given radix times 1024 Rounded up to avoid underallocation.
/*
* 假设拥有n位的radix进制数字至少需要m个2进制位才能表示,那么:
* radix^n - 1 = 2^m -1
* 解上述方程得:m = ln(radix)/ln(2) * n
* 其中,m就是bitsPerDigit[radix]的含义
* 这里为了对计算结果取整,将n扩大为1024
*
* 比如bitsPerDigit[10]==3402,这意味着一个1024位的10进制数字至少需要3402个二进制位才能表示
*/
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
};
/**
* These two arrays are the integer analogue of above.
*/
// 用一个int表示9个十进制数字组成的序列是安全的,该参数作为大数的分组依据
private static int digitsPerInt[] = {0, 0,
30, 19, 15, 13, 11, 11,
10, 9,
9, 8, 8, 8, 8, 7,
7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 5
};
private static int intRadix[] = {0, 0,
0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000,
0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40,
0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
};
/**
* The following two arrays are used for fast String conversions. Both
* are indexed by radix. The first is the number of digits of the given
* radix that can fit in a Java long without "going negative", i.e., the
* highest integer n such that radix**n < 2**63. The second is the
* "long radix" that tears each number into "long digits", each of which
* consists of the number of digits in the corresponding element in
* digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have
* nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
* used.
*/
private static int digitsPerLong[] = {0, 0,
62, 39, 31, 27, 24, 22,
20, 19,
18, 18, 17, 17, 16, 16,
15, 15, 15, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12,
12, 12, 12, 12, 12};
private static BigInteger longRadix[] = {null, null,
valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
valueOf(0x41c21cb8e1000000L)
};
private static final BigInteger SMALL_PRIME_PRODUCT
= valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
// 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;
static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793, Integer.MAX_VALUE}; // Sentinel
/* zero[i] is a string of i consecutive zeros. */
private static String zeros[] = new String[64];
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = -8287574255936472291L;
/**
* Serializable fields for BigInteger.
*
* @serialField signum int
* signum of this BigInteger
* @serialField magnitude byte[]
* magnitude array of this BigInteger
* @serialField bitCount int
* appears in the serialized form for backward compatibility
* @serialField bitLength int
* appears in the serialized form for backward compatibility
* @serialField firstNonzeroByteNum int
* appears in the serialized form for backward compatibility
* @serialField lowestSetBit int
* appears in the serialized form for backward compatibility
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("signum", Integer.TYPE),
new ObjectStreamField("magnitude", byte[].class),
new ObjectStreamField("bitCount", Integer.TYPE),
new ObjectStreamField("bitLength", Integer.TYPE),
new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
new ObjectStreamField("lowestSetBit", Integer.TYPE)
};
static {
zeros[63] = "000000000000000000000000000000000000000000000000000000000000000";
for(int i = 0; i<63; i++)
zeros[i] = zeros[63].substring(0, i);
}
static {
for(int i = 1; i<=MAX_CONSTANT; i++) {
int[] magnitude = new int[1];
magnitude[0] = i;
posConst[i] = new BigInteger(magnitude, 1);
negConst[i] = new BigInteger(magnitude, -1);
}
/*
* Initialize the cache of radix^(2^x) values used for base conversion
* with just the very first value. Additional values will be created
* on demand.
*/
powerCache = new BigInteger[Character.MAX_RADIX + 1][];
logCache = new double[Character.MAX_RADIX + 1];
for(int i = Character.MIN_RADIX; i<=Character.MAX_RADIX; i++) {
powerCache[i] = new BigInteger[]{BigInteger.valueOf(i)};
logCache[i] = Math.log(i);
}
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* 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 {@code
* 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.
* @see Character#digit
*/
// ▶ 1 将radix进制形式的val解析为BigInteger
public BigInteger(String val, int radix) {
int cursor = 0;
int 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");
// 记录数据时正数还是负数
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++;
}
// 字符串中只有0
if(cursor == len) {
signum = 0; // 符号位设置为0
mag = ZERO.mag;
return;
}
// 记录当前数字有多少位
numDigits = len - cursor;
signum = sign; // 符号位,-1? 0? 1?
/*
* Pre-allocate array of expected size. May be too large but can never be too small. Typically exact.
*
* 计算当前的数字需要多少个二进制位才能表示(后面多加了一个1)
*/
long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1;
if(numBits + 31 >= (1L << 32)) {
// 限制了BigInteger能表示的数字范围
reportOverflow();
}
/*
* 计算numBits个二进制位至少需要用几个int表示
* (因为二进制位很长时,需要分段表示,每段用一个int表示)
* numBits在上面多加了1,此处又加了31,这相当于:
* 假设原始的数字表示成n个二进制位,那么这里需要使用的int数量就是n/32+1
*/
int numWords = (int) (numBits + 31) >>> 5;
// 为存储当前数字分配数组空间,该数组暂称作:[大数数组]
int[] magnitude = new int[numWords];
/*
* Process first (potentially short) digit group
*
* 对大数进行分割,初计算第一组数字的长度。
* 分割大数时,需要确定一个分割量,比如对于10进制数,这个分割量就是9(参见digitsPerInt[10])
* 这意味着每9个10进制数字会被分为一组。
* 原因是一个int可以安全地表示9位的十进制数,但表示10位十进制数是不安全的(最大2147483647最小-2147483648)
*
* 值得注意的是,numWords是按一个int代表32个二进制位计算出来的
* 但此处又让一个int表示9个十进制位,即一个int最多表示30个二进制
* 显然按目前这么个表示法,[大数数组]空间是不够用的
* 所以,在后续运算中,会继续往当前分组所代表的数字上累加数据,直到每个[大数数组]中的元素被充分利用。
* 累加时发生的溢出会累积到下一个元素上。
*
* 假设有十进制数字12|345678901|234567890,那么此刻firstGroupLen=20%9=2
*/
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");
}
/* 处理剩余数字 */
/*
* 以10进制数字举例
* 分组时按每9个十进制为一组,其最大表示的值为999,999,999
* 那么此处的superRadix就是1,000,000,000
*/
int superRadix = intRadix[radix];
int groupVal = 0;
while(cursor<len) {
// 截取下一组数字
group = val.substring(cursor, cursor += digitsPerInt[radix]);
// 解析当前这组数字为int
groupVal = Integer.parseInt(group, radix);
if(groupVal<0) {
// 比如10进制数字,一组数字是9位,而9位的十进制数字放到int里不可能为负,也就是说不可能溢出
throw new NumberFormatException("Illegal digit");
}
// 将各分组数据按照一定的规则存入[大数数组]
destructiveMulAdd(magnitude, superRadix, groupVal);
}
/* Required for cases where the array was overallocated. */
// 压缩数组val,只保留有效元素
mag = trustedStripLeadingZeroInts(magnitude);
if(mag.length >= MAX_MAG_LENGTH) {
// 再次限制BigInteger能表示的数字范围
checkRange();
}
}
/**
* Translates the decimal String representation of a BigInteger into a
* BigInteger. The String representation consists of an optional minus
* sign followed by a sequence of one or more decimal digits. The
* character-to-digit mapping is provided by {@code 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.
* @see Character#digit
*/
// ▶ 1-1 将10进制形式的val解析为BigInteger
public BigInteger(String val) {
this(val, 10);
}
/**
* 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
*/
// ▶ 2 将val中[off, off+len)范围存储的二进制位导入BigInteger
public BigInteger(byte[] val, int off, int len) {
if(val.length == 0) {
throw new NumberFormatException("Zero length BigInteger");
} else if((off<0) || (off >= val.length) || (len<0) || (len>val.length - off)) { // 0 <= off < val.length
throw new IndexOutOfBoundsException();
}
if(val[off]<0) {
// 负数需要存储绝对值的二进制的位
mag = makePositive(val, off, len);
signum = -1;
} else {
// 将数组a的二进制位从高到低依次存储到int数组中(剥离前导0)
mag = stripLeadingZeroBytes(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.
*/
// ▶ 2-1 将val中存储的二进制位导入BigInteger
public BigInteger(byte[] val) {
this(val, 0, val.length);
}
/**
* 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
*/
/*
* ▶ 3 将magnitude中[off, off+len)范围存储的二进制位导入BigInteger
* 这里的signum取1或者-1来控制正负,magnitude代表存储的值
*/
public BigInteger(int signum, byte[] magnitude, int off, int len) {
if(signum<-1 || signum>1) {
throw (new NumberFormatException("Invalid signum value"));
} else if((off<0) || (len<0) || (len>0 && ((off >= magnitude.length) || (len>magnitude.length - off)))) {
// 0 <= off < magnitude.length
throw new IndexOutOfBoundsException();
}
// 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.
*/
// ▶ 3-1 将magnitude中存储的二进制位导入BigInteger,signum是符号位
public BigInteger(int signum, byte[] magnitude) {
this(signum, magnitude, 0, magnitude.length);
}
/**
* 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()
*/
// ▶ 3-1-1 随机生成numBits个二进制位后导入BigInteger,符号位为1
public BigInteger(int numBits, Random rnd) {
this(1, randomBits(numBits, rnd));
}
/**
* Constructs a randomly generated positive BigInteger that is probably prime, with the specified bitLength.
*
* @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 - 2^(-certainty)).
* 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.
* @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.
* @see #bitLength()
*/
// ▶ 5 (可能)随机生成一个拥有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;
}
/**
* 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.
*/
// ▶ 6
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();
}
}
/**
* This internal constructor differs from its public cousin
* with the arguments reversed in two ways: it assumes that its
* arguments are correct, and it doesn't copy the magnitude array.
*/
// ▶ 7
BigInteger(int[] magnitude, int signum) {
this.signum = (magnitude.length == 0 ? 0 : signum);
this.mag = magnitude;
if(mag.length >= MAX_MAG_LENGTH) {
checkRange();
}
}
/**
* 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.
*/
// ▶ 8
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();
}
}
/**
* 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.
*/
// ▶ 9
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();
}
}
/**
* This private constructor is for internal use and assumes that its
* arguments are correct. The {@code magnitude} array is assumed to be
* unchanged for the duration of the constructor call.