-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBigInteger.java
More file actions
2678 lines (2412 loc) · 71.6 KB
/
Copy pathBigInteger.java
File metadata and controls
2678 lines (2412 loc) · 71.6 KB
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
/* java.math.BigInteger -- Arbitary precision integers
Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2005, 2006, 2007, 2010
Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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 for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.math;
import gnu.classpath.Configuration;
import gnu.java.lang.CPStringBuilder;
import gnu.java.math.GMP;
import gnu.java.math.MPN;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Random;
import java.util.logging.Logger;
/**
* Written using on-line Java Platform 1.2 API Specification, as well
* as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998) and
* "Applied Cryptography, Second Edition" by Bruce Schneier (Wiley, 1996).
*
* Based primarily on IntNum.java BitOps.java by Per Bothner (per@bothner.com)
* (found in Kawa 1.6.62).
*
* @author Warren Levy (warrenl@cygnus.com)
* @date December 20, 1999.
* @status believed complete and correct.
*/
public class BigInteger extends Number implements Comparable<BigInteger>
{
private static final Logger log = Configuration.DEBUG ?
Logger.getLogger(BigInteger.class.getName()) : null;
/** All integers are stored in 2's-complement form.
* If words == null, the ival is the value of this BigInteger.
* Otherwise, the first ival elements of words make the value
* of this BigInteger, stored in little-endian order, 2's-complement form. */
private transient int ival;
private transient int[] words;
// Serialization fields.
// the first three, although not used in the code, are present for
// compatibility with older RI versions of this class. DO NOT REMOVE.
private int bitCount = -1;
private int bitLength = -1;
private int lowestSetBit = -2;
private byte[] magnitude;
private int signum;
private static final long serialVersionUID = -8287574255936472291L;
/** We pre-allocate integers in the range minFixNum..maxFixNum.
* Note that we must at least preallocate 0, 1, and 10. */
private static final int minFixNum = -100;
private static final int maxFixNum = 1024;
private static final int numFixNum = maxFixNum-minFixNum+1;
private static final BigInteger[] smallFixNums;
/** The alter-ego GMP instance for this. */
private transient GMP mpz;
private static final boolean USING_NATIVE = Configuration.WANT_NATIVE_BIG_INTEGER
&& initializeLibrary();
static
{
if (USING_NATIVE)
{
smallFixNums = null;
ZERO = valueOf(0L);
ONE = valueOf(1L);
TEN = valueOf(10L);
}
else
{
smallFixNums = new BigInteger[numFixNum];
for (int i = numFixNum; --i >= 0; )
smallFixNums[i] = new BigInteger(i + minFixNum);
ZERO = smallFixNums[-minFixNum];
ONE = smallFixNums[1 - minFixNum];
TEN = smallFixNums[10 - minFixNum];
}
}
/**
* The constant zero as a BigInteger.
* @since 1.2
*/
public static final BigInteger ZERO;
/**
* The constant one as a BigInteger.
* @since 1.2
*/
public static final BigInteger ONE;
/**
* The constant ten as a BigInteger.
* @since 1.5
*/
public static final BigInteger TEN;
/* Rounding modes: */
private static final int FLOOR = 1;
private static final int CEILING = 2;
private static final int TRUNCATE = 3;
private static final int ROUND = 4;
/** When checking the probability of primes, it is most efficient to
* first check the factoring of small primes, so we'll use this array.
*/
private static final int[] primes =
{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 };
/** HAC (Handbook of Applied Cryptography), Alfred Menezes & al. Table 4.4. */
private static final int[] k =
{100,150,200,250,300,350,400,500,600,800,1250, Integer.MAX_VALUE};
private static final int[] t =
{ 27, 18, 15, 12, 9, 8, 7, 6, 5, 4, 3, 2};
private BigInteger()
{
super();
if (USING_NATIVE)
mpz = new GMP();
}
/* Create a new (non-shared) BigInteger, and initialize to an int. */
private BigInteger(int value)
{
super();
ival = value;
}
public BigInteger(String s, int radix)
{
this();
int len = s.length();
int i, digit;
boolean negative;
byte[] bytes;
char ch = s.charAt(0);
if (ch == '-')
{
negative = true;
i = 1;
bytes = new byte[len - 1];
}
else
{
negative = false;
i = 0;
bytes = new byte[len];
}
int byte_len = 0;
for ( ; i < len; i++)
{
ch = s.charAt(i);
digit = Character.digit(ch, radix);
if (digit < 0)
throw new NumberFormatException("Invalid character at position #" + i);
bytes[byte_len++] = (byte) digit;
}
if (USING_NATIVE)
{
bytes = null;
if (mpz.fromString(s, radix) != 0)
throw new NumberFormatException("String \"" + s
+ "\" is NOT a valid number in base "
+ radix);
}
else
{
BigInteger result;
// Testing (len < MPN.chars_per_word(radix)) would be more accurate,
// but slightly more expensive, for little practical gain.
if (len <= 15 && radix <= 16)
result = valueOf(Long.parseLong(s, radix));
else
result = valueOf(bytes, byte_len, negative, radix);
this.ival = result.ival;
this.words = result.words;
}
}
public BigInteger(String val)
{
this(val, 10);
}
/* Create a new (non-shared) BigInteger, and initialize from a byte array. */
public BigInteger(byte[] val)
{
this();
if (val == null || val.length < 1)
throw new NumberFormatException();
if (USING_NATIVE)
mpz.fromByteArray(val);
else
{
words = byteArrayToIntArray(val, val[0] < 0 ? -1 : 0);
BigInteger result = make(words, words.length);
this.ival = result.ival;
this.words = result.words;
}
}
public BigInteger(int signum, byte[] magnitude)
{
this();
if (magnitude == null || signum > 1 || signum < -1)
throw new NumberFormatException();
if (signum == 0)
{
int i;
for (i = magnitude.length - 1; i >= 0 && magnitude[i] == 0; --i)
;
if (i >= 0)
throw new NumberFormatException();
return;
}
if (USING_NATIVE)
mpz.fromSignedMagnitude(magnitude, signum == -1);
else
{
// Magnitude is always positive, so don't ever pass a sign of -1.
words = byteArrayToIntArray(magnitude, 0);
BigInteger result = make(words, words.length);
this.ival = result.ival;
this.words = result.words;
if (signum < 0)
setNegative();
}
}
public BigInteger(int numBits, Random rnd)
{
this();
if (numBits < 0)
throw new IllegalArgumentException();
init(numBits, rnd);
}
private void init(int numBits, Random rnd)
{
if (USING_NATIVE)
{
int length = (numBits + 7) / 8;
byte[] magnitude = new byte[length];
rnd.nextBytes(magnitude);
int discardedBitCount = numBits % 8;
if (discardedBitCount != 0)
{
discardedBitCount = 8 - discardedBitCount;
magnitude[0] = (byte)((magnitude[0] & 0xFF) >>> discardedBitCount);
}
mpz.fromSignedMagnitude(magnitude, false);
magnitude = null;
return;
}
int highbits = numBits & 31;
// minimum number of bytes to store the above number of bits
int highBitByteCount = (highbits + 7) / 8;
// number of bits to discard from the last byte
int discardedBitCount = highbits % 8;
if (discardedBitCount != 0)
discardedBitCount = 8 - discardedBitCount;
byte[] highBitBytes = new byte[highBitByteCount];
if (highbits > 0)
{
rnd.nextBytes(highBitBytes);
highbits = (highBitBytes[highBitByteCount - 1] & 0xFF) >>> discardedBitCount;
for (int i = highBitByteCount - 2; i >= 0; i--)
highbits = (highbits << 8) | (highBitBytes[i] & 0xFF);
}
int nwords = numBits / 32;
while (highbits == 0 && nwords > 0)
{
highbits = rnd.nextInt();
--nwords;
}
if (nwords == 0 && highbits >= 0)
{
ival = highbits;
}
else
{
ival = highbits < 0 ? nwords + 2 : nwords + 1;
words = new int[ival];
words[nwords] = highbits;
while (--nwords >= 0)
words[nwords] = rnd.nextInt();
}
}
public BigInteger(int bitLength, int certainty, Random rnd)
{
this();
BigInteger result = new BigInteger();
while (true)
{
result.init(bitLength, rnd);
result = result.setBit(bitLength - 1);
if (result.isProbablePrime(certainty))
break;
}
if (USING_NATIVE)
mpz.fromBI(result.mpz);
else
{
this.ival = result.ival;
this.words = result.words;
}
}
/**
* Return a BigInteger that is bitLength bits long with a
* probability < 2^-100 of being composite.
*
* @param bitLength length in bits of resulting number
* @param rnd random number generator to use
* @throws ArithmeticException if bitLength < 2
* @since 1.4
*/
public static BigInteger probablePrime(int bitLength, Random rnd)
{
if (bitLength < 2)
throw new ArithmeticException();
return new BigInteger(bitLength, 100, rnd);
}
/** Return a (possibly-shared) BigInteger with a given long value. */
public static BigInteger valueOf(long val)
{
if (USING_NATIVE)
{
BigInteger result = new BigInteger();
result.mpz.fromLong(val);
return result;
}
if (val >= minFixNum && val <= maxFixNum)
return smallFixNums[(int) val - minFixNum];
int i = (int) val;
if ((long) i == val)
return new BigInteger(i);
BigInteger result = alloc(2);
result.ival = 2;
result.words[0] = i;
result.words[1] = (int)(val >> 32);
return result;
}
/**
* @return <code>true</code> if the GMP-based native implementation library
* was successfully loaded. Returns <code>false</code> otherwise.
*/
private static boolean initializeLibrary()
{
boolean result;
try
{
System.loadLibrary("javamath");
GMP.natInitializeLibrary();
result = true;
}
catch (Throwable x)
{
result = false;
if (Configuration.DEBUG)
{
log.info("Unable to use native BigInteger: " + x);
log.info("Will use a pure Java implementation instead");
}
}
return result;
}
/** Make a canonicalized BigInteger from an array of words.
* The array may be reused (without copying). */
private static BigInteger make(int[] words, int len)
{
if (words == null)
return valueOf(len);
len = BigInteger.wordsNeeded(words, len);
if (len <= 1)
return len == 0 ? ZERO : valueOf(words[0]);
BigInteger num = new BigInteger();
num.words = words;
num.ival = len;
return num;
}
/** Convert a big-endian byte array to a little-endian array of words. */
private static int[] byteArrayToIntArray(byte[] bytes, int sign)
{
// Determine number of words needed.
int[] words = new int[bytes.length/4 + 1];
int nwords = words.length;
// Create a int out of modulo 4 high order bytes.
int bptr = 0;
int word = sign;
for (int i = bytes.length % 4; i > 0; --i, bptr++)
word = (word << 8) | (bytes[bptr] & 0xff);
words[--nwords] = word;
// Elements remaining in byte[] are a multiple of 4.
while (nwords > 0)
words[--nwords] = bytes[bptr++] << 24 |
(bytes[bptr++] & 0xff) << 16 |
(bytes[bptr++] & 0xff) << 8 |
(bytes[bptr++] & 0xff);
return words;
}
/** Allocate a new non-shared BigInteger.
* @param nwords number of words to allocate
*/
private static BigInteger alloc(int nwords)
{
BigInteger result = new BigInteger();
if (nwords > 1)
result.words = new int[nwords];
return result;
}
/** Change words.length to nwords.
* We allow words.length to be upto nwords+2 without reallocating.
*/
private void realloc(int nwords)
{
if (nwords == 0)
{
if (words != null)
{
if (ival > 0)
ival = words[0];
words = null;
}
}
else if (words == null
|| words.length < nwords
|| words.length > nwords + 2)
{
int[] new_words = new int [nwords];
if (words == null)
{
new_words[0] = ival;
ival = 1;
}
else
{
if (nwords < ival)
ival = nwords;
System.arraycopy(words, 0, new_words, 0, ival);
}
words = new_words;
}
}
private boolean isNegative()
{
return (words == null ? ival : words[ival - 1]) < 0;
}
public int signum()
{
if (USING_NATIVE)
return mpz.compare(ZERO.mpz);
if (ival == 0 && words == null)
return 0;
int top = words == null ? ival : words[ival-1];
return top < 0 ? -1 : 1;
}
private static int compareTo(BigInteger x, BigInteger y)
{
if (USING_NATIVE)
{
int dummy = y.signum; // force NPE check
return x.mpz.compare(y.mpz);
}
if (x.words == null && y.words == null)
return x.ival < y.ival ? -1 : x.ival > y.ival ? 1 : 0;
boolean x_negative = x.isNegative();
boolean y_negative = y.isNegative();
if (x_negative != y_negative)
return x_negative ? -1 : 1;
int x_len = x.words == null ? 1 : x.ival;
int y_len = y.words == null ? 1 : y.ival;
if (x_len != y_len)
return (x_len > y_len) != x_negative ? 1 : -1;
return MPN.cmp(x.words, y.words, x_len);
}
/** @since 1.2 */
public int compareTo(BigInteger val)
{
return compareTo(this, val);
}
public BigInteger min(BigInteger val)
{
return compareTo(this, val) < 0 ? this : val;
}
public BigInteger max(BigInteger val)
{
return compareTo(this, val) > 0 ? this : val;
}
private boolean isZero()
{
return words == null && ival == 0;
}
private boolean isOne()
{
return words == null && ival == 1;
}
/** Calculate how many words are significant in words[0:len-1].
* Returns the least value x such that x>0 && words[0:x-1]==words[0:len-1],
* when words is viewed as a 2's complement integer.
*/
private static int wordsNeeded(int[] words, int len)
{
int i = len;
if (i > 0)
{
int word = words[--i];
if (word == -1)
{
while (i > 0 && (word = words[i - 1]) < 0)
{
i--;
if (word != -1) break;
}
}
else
{
while (word == 0 && i > 0 && (word = words[i - 1]) >= 0) i--;
}
}
return i + 1;
}
private BigInteger canonicalize()
{
if (words != null
&& (ival = BigInteger.wordsNeeded(words, ival)) <= 1)
{
if (ival == 1)
ival = words[0];
words = null;
}
if (words == null && ival >= minFixNum && ival <= maxFixNum)
return smallFixNums[ival - minFixNum];
return this;
}
/** Add two ints, yielding a BigInteger. */
private static BigInteger add(int x, int y)
{
return valueOf((long) x + (long) y);
}
/** Add a BigInteger and an int, yielding a new BigInteger. */
private static BigInteger add(BigInteger x, int y)
{
if (x.words == null)
return BigInteger.add(x.ival, y);
BigInteger result = new BigInteger(0);
result.setAdd(x, y);
return result.canonicalize();
}
/** Set this to the sum of x and y.
* OK if x==this. */
private void setAdd(BigInteger x, int y)
{
if (x.words == null)
{
set((long) x.ival + (long) y);
return;
}
int len = x.ival;
realloc(len + 1);
long carry = y;
for (int i = 0; i < len; i++)
{
carry += ((long) x.words[i] & 0xffffffffL);
words[i] = (int) carry;
carry >>= 32;
}
if (x.words[len - 1] < 0)
carry--;
words[len] = (int) carry;
ival = wordsNeeded(words, len + 1);
}
/** Destructively add an int to this. */
private void setAdd(int y)
{
setAdd(this, y);
}
/** Destructively set the value of this to a long. */
private void set(long y)
{
int i = (int) y;
if ((long) i == y)
{
ival = i;
words = null;
}
else
{
realloc(2);
words[0] = i;
words[1] = (int) (y >> 32);
ival = 2;
}
}
/** Destructively set the value of this to the given words.
* The words array is reused, not copied. */
private void set(int[] words, int length)
{
this.ival = length;
this.words = words;
}
/** Destructively set the value of this to that of y. */
private void set(BigInteger y)
{
if (y.words == null)
set(y.ival);
else if (this != y)
{
realloc(y.ival);
System.arraycopy(y.words, 0, words, 0, y.ival);
ival = y.ival;
}
}
/** Add two BigIntegers, yielding their sum as another BigInteger. */
private static BigInteger add(BigInteger x, BigInteger y, int k)
{
if (x.words == null && y.words == null)
return valueOf((long) k * (long) y.ival + (long) x.ival);
if (k != 1)
{
if (k == -1)
y = BigInteger.neg(y);
else
y = BigInteger.times(y, valueOf(k));
}
if (x.words == null)
return BigInteger.add(y, x.ival);
if (y.words == null)
return BigInteger.add(x, y.ival);
// Both are big
if (y.ival > x.ival)
{ // Swap so x is longer then y.
BigInteger tmp = x; x = y; y = tmp;
}
BigInteger result = alloc(x.ival + 1);
int i = y.ival;
long carry = MPN.add_n(result.words, x.words, y.words, i);
long y_ext = y.words[i - 1] < 0 ? 0xffffffffL : 0;
for (; i < x.ival; i++)
{
carry += ((long) x.words[i] & 0xffffffffL) + y_ext;
result.words[i] = (int) carry;
carry >>>= 32;
}
if (x.words[i - 1] < 0)
y_ext--;
result.words[i] = (int) (carry + y_ext);
result.ival = i+1;
return result.canonicalize();
}
public BigInteger add(BigInteger val)
{
if (USING_NATIVE)
{
int dummy = val.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.add(val.mpz, result.mpz);
return result;
}
return add(this, val, 1);
}
public BigInteger subtract(BigInteger val)
{
if (USING_NATIVE)
{
int dummy = val.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.subtract(val.mpz, result.mpz);
return result;
}
return add(this, val, -1);
}
private static BigInteger times(BigInteger x, int y)
{
if (y == 0)
return ZERO;
if (y == 1)
return x;
int[] xwords = x.words;
int xlen = x.ival;
if (xwords == null)
return valueOf((long) xlen * (long) y);
boolean negative;
BigInteger result = BigInteger.alloc(xlen + 1);
if (xwords[xlen - 1] < 0)
{
negative = true;
negate(result.words, xwords, xlen);
xwords = result.words;
}
else
negative = false;
if (y < 0)
{
negative = !negative;
y = -y;
}
result.words[xlen] = MPN.mul_1(result.words, xwords, xlen, y);
result.ival = xlen + 1;
if (negative)
result.setNegative();
return result.canonicalize();
}
private static BigInteger times(BigInteger x, BigInteger y)
{
if (y.words == null)
return times(x, y.ival);
if (x.words == null)
return times(y, x.ival);
boolean negative = false;
int[] xwords;
int[] ywords;
int xlen = x.ival;
int ylen = y.ival;
if (x.isNegative())
{
negative = true;
xwords = new int[xlen];
negate(xwords, x.words, xlen);
}
else
{
negative = false;
xwords = x.words;
}
if (y.isNegative())
{
negative = !negative;
ywords = new int[ylen];
negate(ywords, y.words, ylen);
}
else
ywords = y.words;
// Swap if x is shorter then y.
if (xlen < ylen)
{
int[] twords = xwords; xwords = ywords; ywords = twords;
int tlen = xlen; xlen = ylen; ylen = tlen;
}
BigInteger result = BigInteger.alloc(xlen+ylen);
MPN.mul(result.words, xwords, xlen, ywords, ylen);
result.ival = xlen+ylen;
if (negative)
result.setNegative();
return result.canonicalize();
}
public BigInteger multiply(BigInteger y)
{
if (USING_NATIVE)
{
int dummy = y.signum; // force NPE check
BigInteger result = new BigInteger();
mpz.multiply(y.mpz, result.mpz);
return result;
}
return times(this, y);
}
private static void divide(long x, long y,
BigInteger quotient, BigInteger remainder,
int rounding_mode)
{
boolean xNegative, yNegative;
if (x < 0)
{
xNegative = true;
if (x == Long.MIN_VALUE)
{
divide(valueOf(x), valueOf(y),
quotient, remainder, rounding_mode);
return;
}
x = -x;
}
else
xNegative = false;
if (y < 0)
{
yNegative = true;
if (y == Long.MIN_VALUE)
{
if (rounding_mode == TRUNCATE)
{ // x != Long.Min_VALUE implies abs(x) < abs(y)
if (quotient != null)
quotient.set(0);
if (remainder != null)
remainder.set(x);
}
else
divide(valueOf(x), valueOf(y),
quotient, remainder, rounding_mode);
return;
}
y = -y;
}
else
yNegative = false;
long q = x / y;
long r = x % y;
boolean qNegative = xNegative ^ yNegative;
boolean add_one = false;
if (r != 0)
{
switch (rounding_mode)
{
case TRUNCATE:
break;
case CEILING:
case FLOOR:
if (qNegative == (rounding_mode == FLOOR))
add_one = true;
break;
case ROUND:
add_one = r > ((y - (q & 1)) >> 1);
break;
}
}
if (quotient != null)
{
if (add_one)
q++;
if (qNegative)
q = -q;
quotient.set(q);
}
if (remainder != null)
{
// The remainder is by definition: X-Q*Y
if (add_one)
{
// Subtract the remainder from Y.
r = y - r;
// In this case, abs(Q*Y) > abs(X).
// So sign(remainder) = -sign(X).
xNegative = ! xNegative;
}
else
{
// If !add_one, then: abs(Q*Y) <= abs(X).
// So sign(remainder) = sign(X).
}
if (xNegative)
r = -r;
remainder.set(r);
}
}
/** Divide two integers, yielding quotient and remainder.
* @param x the numerator in the division
* @param y the denominator in the division
* @param quotient is set to the quotient of the result (iff quotient!=null)
* @param remainder is set to the remainder of the result
* (iff remainder!=null)
* @param rounding_mode one of FLOOR, CEILING, TRUNCATE, or ROUND.
*/
private static void divide(BigInteger x, BigInteger y,
BigInteger quotient, BigInteger remainder,
int rounding_mode)
{
if ((x.words == null || x.ival <= 2)
&& (y.words == null || y.ival <= 2))
{
long x_l = x.longValue();
long y_l = y.longValue();
if (x_l != Long.MIN_VALUE && y_l != Long.MIN_VALUE)
{
divide(x_l, y_l, quotient, remainder, rounding_mode);
return;
}
}
boolean xNegative = x.isNegative();
boolean yNegative = y.isNegative();
boolean qNegative = xNegative ^ yNegative;
int ylen = y.words == null ? 1 : y.ival;
int[] ywords = new int[ylen];
y.getAbsolute(ywords);
while (ylen > 1 && ywords[ylen - 1] == 0) ylen--;
int xlen = x.words == null ? 1 : x.ival;
int[] xwords = new int[xlen+2];
x.getAbsolute(xwords);
while (xlen > 1 && xwords[xlen-1] == 0) xlen--;
int qlen, rlen;
int cmpval = MPN.cmp(xwords, xlen, ywords, ylen);
if (cmpval < 0) // abs(x) < abs(y)
{ // quotient = 0; remainder = num.
int[] rwords = xwords; xwords = ywords; ywords = rwords;
rlen = xlen; qlen = 1; xwords[0] = 0;
}
else if (cmpval == 0) // abs(x) == abs(y)