source: trunk/gcc/libjava/java/math/BigInteger.java

Last change on this file was 1392, checked in by bird, 21 years ago

This commit was generated by cvs2svn to compensate for changes in r1391,
which included commits to RCS files with non-trunk default branches.

  • Property cvs2svn:cvs-rev set to 1.1.1.2
  • Property svn:eol-style set to native
  • Property svn:executable set to *
File size: 55.9 KB
Line 
1/* java.math.BigInteger -- Arbitary precision integers
2 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
3
4This file is part of GNU Classpath.
5
6GNU Classpath is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation; either version 2, or (at your option)
9any later version.
10
11GNU Classpath is distributed in the hope that it will be useful, but
12WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Classpath; see the file COPYING. If not, write to the
18Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
1902111-1307 USA.
20
21Linking this library statically or dynamically with other modules is
22making a combined work based on this library. Thus, the terms and
23conditions of the GNU General Public License cover the whole
24combination.
25
26As a special exception, the copyright holders of this library give you
27permission to link this library with independent modules to produce an
28executable, regardless of the license terms of these independent
29modules, and to copy and distribute the resulting executable under
30terms of your choice, provided that you also meet, for each linked
31independent module, the terms and conditions of the license of that
32module. An independent module is a module which is not derived from
33or based on this library. If you modify this library, you may extend
34this exception to your version of the library, but you are not
35obligated to do so. If you do not wish to do so, delete this
36exception statement from your version. */
37
38package java.math;
39
40import gnu.java.math.MPN;
41import java.util.Random;
42import java.io.ObjectInputStream;
43import java.io.ObjectOutputStream;
44import java.io.IOException;
45
46/**
47 * @author Warren Levy <warrenl@cygnus.com>
48 * @date December 20, 1999.
49 */
50
51/**
52 * Written using on-line Java Platform 1.2 API Specification, as well
53 * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998) and
54 * "Applied Cryptography, Second Edition" by Bruce Schneier (Wiley, 1996).
55 *
56 * Based primarily on IntNum.java BitOps.java by Per Bothner <per@bothner.com>
57 * (found in Kawa 1.6.62).
58 *
59 * Status: Believed complete and correct.
60 */
61
62public class BigInteger extends Number implements Comparable
63{
64 /** All integers are stored in 2's-complement form.
65 * If words == null, the ival is the value of this BigInteger.
66 * Otherwise, the first ival elements of words make the value
67 * of this BigInteger, stored in little-endian order, 2's-complement form. */
68 transient private int ival;
69 transient private int[] words;
70
71 // Serialization fields.
72 private int bitCount = -1;
73 private int bitLength = -1;
74 private int firstNonzeroByteNum = -2;
75 private int lowestSetBit = -2;
76 private byte[] magnitude;
77 private int signum;
78 private static final long serialVersionUID = -8287574255936472291L;
79
80
81 /** We pre-allocate integers in the range minFixNum..maxFixNum. */
82 private static final int minFixNum = -100;
83 private static final int maxFixNum = 1024;
84 private static final int numFixNum = maxFixNum-minFixNum+1;
85 private static final BigInteger[] smallFixNums = new BigInteger[numFixNum];
86
87 static {
88 for (int i = numFixNum; --i >= 0; )
89 smallFixNums[i] = new BigInteger(i + minFixNum);
90 }
91
92 // JDK1.2
93 public static final BigInteger ZERO = smallFixNums[-minFixNum];
94
95 // JDK1.2
96 public static final BigInteger ONE = smallFixNums[1 - minFixNum];
97
98 /* Rounding modes: */
99 private static final int FLOOR = 1;
100 private static final int CEILING = 2;
101 private static final int TRUNCATE = 3;
102 private static final int ROUND = 4;
103
104 /** When checking the probability of primes, it is most efficient to
105 * first check the factoring of small primes, so we'll use this array.
106 */
107 private static final int[] primes =
108 { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
109 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
110 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
111 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 };
112
113 /** HAC (Handbook of Applied Cryptography), Alfred Menezes & al. Table 4.4. */
114 private static final int[] k =
115 {100,150,200,250,300,350,400,500,600,800,1250, Integer.MAX_VALUE};
116 private static final int[] t =
117 { 27, 18, 15, 12, 9, 8, 7, 6, 5, 4, 3, 2};
118
119 private BigInteger()
120 {
121 }
122
123 /* Create a new (non-shared) BigInteger, and initialize to an int. */
124 private BigInteger(int value)
125 {
126 ival = value;
127 }
128
129 public BigInteger(String val, int radix)
130 {
131 BigInteger result = valueOf(val, radix);
132 this.ival = result.ival;
133 this.words = result.words;
134 }
135
136 public BigInteger(String val)
137 {
138 this(val, 10);
139 }
140
141 /* Create a new (non-shared) BigInteger, and initialize from a byte array. */
142 public BigInteger(byte[] val)
143 {
144 if (val == null || val.length < 1)
145 throw new NumberFormatException();
146
147 words = byteArrayToIntArray(val, val[0] < 0 ? -1 : 0);
148 BigInteger result = make(words, words.length);
149 this.ival = result.ival;
150 this.words = result.words;
151 }
152
153 public BigInteger(int signum, byte[] magnitude)
154 {
155 if (magnitude == null || signum > 1 || signum < -1)
156 throw new NumberFormatException();
157
158 if (signum == 0)
159 {
160 int i;
161 for (i = magnitude.length - 1; i >= 0 && magnitude[i] == 0; --i)
162 ;
163 if (i >= 0)
164 throw new NumberFormatException();
165 return;
166 }
167
168 // Magnitude is always positive, so don't ever pass a sign of -1.
169 words = byteArrayToIntArray(magnitude, 0);
170 BigInteger result = make(words, words.length);
171 this.ival = result.ival;
172 this.words = result.words;
173
174 if (signum < 0)
175 setNegative();
176 }
177
178 public BigInteger(int numBits, Random rnd)
179 {
180 if (numBits < 0)
181 throw new IllegalArgumentException();
182
183 init(numBits, rnd);
184 }
185
186 private void init(int numBits, Random rnd)
187 {
188 int highbits = numBits & 31;
189 if (highbits > 0)
190 highbits = rnd.nextInt() >>> (32 - highbits);
191 int nwords = numBits / 32;
192
193 while (highbits == 0 && nwords > 0)
194 {
195 highbits = rnd.nextInt();
196 --nwords;
197 }
198 if (nwords == 0 && highbits >= 0)
199 {
200 ival = highbits;
201 }
202 else
203 {
204 ival = highbits < 0 ? nwords + 2 : nwords + 1;
205 words = new int[ival];
206 words[nwords] = highbits;
207 while (--nwords >= 0)
208 words[nwords] = rnd.nextInt();
209 }
210 }
211
212 public BigInteger(int bitLength, int certainty, Random rnd)
213 {
214 this(bitLength, rnd);
215
216 // Keep going until we find a probable prime.
217 while (true)
218 {
219 if (isProbablePrime(certainty))
220 return;
221
222 init(bitLength, rnd);
223 }
224 }
225
226 /**
227 * Return a BigInteger that is bitLength bits long with a
228 * probability < 2^-100 of being composite.
229 *
230 * @param bitLength length in bits of resulting number
231 * @param rnd random number generator to use
232 * @throws ArithmeticException if bitLength < 2
233 * @since 1.4
234 */
235 public static BigInteger probablePrime(int bitLength, Random rnd)
236 {
237 if (bitLength < 2)
238 throw new ArithmeticException();
239
240 return new BigInteger(bitLength, 100, rnd);
241 }
242
243 /** Return a (possibly-shared) BigInteger with a given long value. */
244 public static BigInteger valueOf(long val)
245 {
246 if (val >= minFixNum && val <= maxFixNum)
247 return smallFixNums[(int) val - minFixNum];
248 int i = (int) val;
249 if ((long) i == val)
250 return new BigInteger(i);
251 BigInteger result = alloc(2);
252 result.ival = 2;
253 result.words[0] = i;
254 result.words[1] = (int)(val >> 32);
255 return result;
256 }
257
258 /** Make a canonicalized BigInteger from an array of words.
259 * The array may be reused (without copying). */
260 private static BigInteger make(int[] words, int len)
261 {
262 if (words == null)
263 return valueOf(len);
264 len = BigInteger.wordsNeeded(words, len);
265 if (len <= 1)
266 return len == 0 ? ZERO : valueOf(words[0]);
267 BigInteger num = new BigInteger();
268 num.words = words;
269 num.ival = len;
270 return num;
271 }
272
273 /** Convert a big-endian byte array to a little-endian array of words. */
274 private static int[] byteArrayToIntArray(byte[] bytes, int sign)
275 {
276 // Determine number of words needed.
277 int[] words = new int[bytes.length/4 + 1];
278 int nwords = words.length;
279
280 // Create a int out of modulo 4 high order bytes.
281 int bptr = 0;
282 int word = sign;
283 for (int i = bytes.length % 4; i > 0; --i, bptr++)
284 word = (word << 8) | (bytes[bptr] & 0xff);
285 words[--nwords] = word;
286
287 // Elements remaining in byte[] are a multiple of 4.
288 while (nwords > 0)
289 words[--nwords] = bytes[bptr++] << 24 |
290 (bytes[bptr++] & 0xff) << 16 |
291 (bytes[bptr++] & 0xff) << 8 |
292 (bytes[bptr++] & 0xff);
293 return words;
294 }
295
296 /** Allocate a new non-shared BigInteger.
297 * @param nwords number of words to allocate
298 */
299 private static BigInteger alloc(int nwords)
300 {
301 BigInteger result = new BigInteger();
302 if (nwords > 1)
303 result.words = new int[nwords];
304 return result;
305 }
306
307 /** Change words.length to nwords.
308 * We allow words.length to be upto nwords+2 without reallocating.
309 */
310 private void realloc(int nwords)
311 {
312 if (nwords == 0)
313 {
314 if (words != null)
315 {
316 if (ival > 0)
317 ival = words[0];
318 words = null;
319 }
320 }
321 else if (words == null
322 || words.length < nwords
323 || words.length > nwords + 2)
324 {
325 int[] new_words = new int [nwords];
326 if (words == null)
327 {
328 new_words[0] = ival;
329 ival = 1;
330 }
331 else
332 {
333 if (nwords < ival)
334 ival = nwords;
335 System.arraycopy(words, 0, new_words, 0, ival);
336 }
337 words = new_words;
338 }
339 }
340
341 private final boolean isNegative()
342 {
343 return (words == null ? ival : words[ival - 1]) < 0;
344 }
345
346 public int signum()
347 {
348 int top = words == null ? ival : words[ival-1];
349 if (top == 0 && words == null)
350 return 0;
351 return top < 0 ? -1 : 1;
352 }
353
354 private static int compareTo(BigInteger x, BigInteger y)
355 {
356 if (x.words == null && y.words == null)
357 return x.ival < y.ival ? -1 : x.ival > y.ival ? 1 : 0;
358 boolean x_negative = x.isNegative();
359 boolean y_negative = y.isNegative();
360 if (x_negative != y_negative)
361 return x_negative ? -1 : 1;
362 int x_len = x.words == null ? 1 : x.ival;
363 int y_len = y.words == null ? 1 : y.ival;
364 if (x_len != y_len)
365 return (x_len > y_len) != x_negative ? 1 : -1;
366 return MPN.cmp(x.words, y.words, x_len);
367 }
368
369 // JDK1.2
370 public int compareTo(Object obj)
371 {
372 if (obj instanceof BigInteger)
373 return compareTo(this, (BigInteger) obj);
374 throw new ClassCastException();
375 }
376
377 public int compareTo(BigInteger val)
378 {
379 return compareTo(this, val);
380 }
381
382 public BigInteger min(BigInteger val)
383 {
384 return compareTo(this, val) < 0 ? this : val;
385 }
386
387 public BigInteger max(BigInteger val)
388 {
389 return compareTo(this, val) > 0 ? this : val;
390 }
391
392 private final boolean isZero()
393 {
394 return words == null && ival == 0;
395 }
396
397 private final boolean isOne()
398 {
399 return words == null && ival == 1;
400 }
401
402 /** Calculate how many words are significant in words[0:len-1].
403 * Returns the least value x such that x>0 && words[0:x-1]==words[0:len-1],
404 * when words is viewed as a 2's complement integer.
405 */
406 private static int wordsNeeded(int[] words, int len)
407 {
408 int i = len;
409 if (i > 0)
410 {
411 int word = words[--i];
412 if (word == -1)
413 {
414 while (i > 0 && (word = words[i - 1]) < 0)
415 {
416 i--;
417 if (word != -1) break;
418 }
419 }
420 else
421 {
422 while (word == 0 && i > 0 && (word = words[i - 1]) >= 0) i--;
423 }
424 }
425 return i + 1;
426 }
427
428 private BigInteger canonicalize()
429 {
430 if (words != null
431 && (ival = BigInteger.wordsNeeded(words, ival)) <= 1)
432 {
433 if (ival == 1)
434 ival = words[0];
435 words = null;
436 }
437 if (words == null && ival >= minFixNum && ival <= maxFixNum)
438 return smallFixNums[ival - minFixNum];
439 return this;
440 }
441
442 /** Add two ints, yielding a BigInteger. */
443 private static final BigInteger add(int x, int y)
444 {
445 return valueOf((long) x + (long) y);
446 }
447
448 /** Add a BigInteger and an int, yielding a new BigInteger. */
449 private static BigInteger add(BigInteger x, int y)
450 {
451 if (x.words == null)
452 return BigInteger.add(x.ival, y);
453 BigInteger result = new BigInteger(0);
454 result.setAdd(x, y);
455 return result.canonicalize();
456 }
457
458 /** Set this to the sum of x and y.
459 * OK if x==this. */
460 private void setAdd(BigInteger x, int y)
461 {
462 if (x.words == null)
463 {
464 set((long) x.ival + (long) y);
465 return;
466 }
467 int len = x.ival;
468 realloc(len + 1);
469 long carry = y;
470 for (int i = 0; i < len; i++)
471 {
472 carry += ((long) x.words[i] & 0xffffffffL);
473 words[i] = (int) carry;
474 carry >>= 32;
475 }
476 if (x.words[len - 1] < 0)
477 carry--;
478 words[len] = (int) carry;
479 ival = wordsNeeded(words, len + 1);
480 }
481
482 /** Destructively add an int to this. */
483 private final void setAdd(int y)
484 {
485 setAdd(this, y);
486 }
487
488 /** Destructively set the value of this to a long. */
489 private final void set(long y)
490 {
491 int i = (int) y;
492 if ((long) i == y)
493 {
494 ival = i;
495 words = null;
496 }
497 else
498 {
499 realloc(2);
500 words[0] = i;
501 words[1] = (int) (y >> 32);
502 ival = 2;
503 }
504 }
505
506 /** Destructively set the value of this to the given words.
507 * The words array is reused, not copied. */
508 private final void set(int[] words, int length)
509 {
510 this.ival = length;
511 this.words = words;
512 }
513
514 /** Destructively set the value of this to that of y. */
515 private final void set(BigInteger y)
516 {
517 if (y.words == null)
518 set(y.ival);
519 else if (this != y)
520 {
521 realloc(y.ival);
522 System.arraycopy(y.words, 0, words, 0, y.ival);
523 ival = y.ival;
524 }
525 }
526
527 /** Add two BigIntegers, yielding their sum as another BigInteger. */
528 private static BigInteger add(BigInteger x, BigInteger y, int k)
529 {
530 if (x.words == null && y.words == null)
531 return valueOf((long) k * (long) y.ival + (long) x.ival);
532 if (k != 1)
533 {
534 if (k == -1)
535 y = BigInteger.neg(y);
536 else
537 y = BigInteger.times(y, valueOf(k));
538 }
539 if (x.words == null)
540 return BigInteger.add(y, x.ival);
541 if (y.words == null)
542 return BigInteger.add(x, y.ival);
543 // Both are big
544 int len;
545 if (y.ival > x.ival)
546 { // Swap so x is longer then y.
547 BigInteger tmp = x; x = y; y = tmp;
548 }
549 BigInteger result = alloc(x.ival + 1);
550 int i = y.ival;
551 long carry = MPN.add_n(result.words, x.words, y.words, i);
552 long y_ext = y.words[i - 1] < 0 ? 0xffffffffL : 0;
553 for (; i < x.ival; i++)
554 {
555 carry += ((long) x.words[i] & 0xffffffffL) + y_ext;;
556 result.words[i] = (int) carry;
557 carry >>>= 32;
558 }
559 if (x.words[i - 1] < 0)
560 y_ext--;
561 result.words[i] = (int) (carry + y_ext);
562 result.ival = i+1;
563 return result.canonicalize();
564 }
565
566 public BigInteger add(BigInteger val)
567 {
568 return add(this, val, 1);
569 }
570
571 public BigInteger subtract(BigInteger val)
572 {
573 return add(this, val, -1);
574 }
575
576 private static final BigInteger times(BigInteger x, int y)
577 {
578 if (y == 0)
579 return ZERO;
580 if (y == 1)
581 return x;
582 int[] xwords = x.words;
583 int xlen = x.ival;
584 if (xwords == null)
585 return valueOf((long) xlen * (long) y);
586 boolean negative;
587 BigInteger result = BigInteger.alloc(xlen + 1);
588 if (xwords[xlen - 1] < 0)
589 {
590 negative = true;
591 negate(result.words, xwords, xlen);
592 xwords = result.words;
593 }
594 else
595 negative = false;
596 if (y < 0)
597 {
598 negative = !negative;
599 y = -y;
600 }
601 result.words[xlen] = MPN.mul_1(result.words, xwords, xlen, y);
602 result.ival = xlen + 1;
603 if (negative)
604 result.setNegative();
605 return result.canonicalize();
606 }
607
608 private static final BigInteger times(BigInteger x, BigInteger y)
609 {
610 if (y.words == null)
611 return times(x, y.ival);
612 if (x.words == null)
613 return times(y, x.ival);
614 boolean negative = false;
615 int[] xwords;
616 int[] ywords;
617 int xlen = x.ival;
618 int ylen = y.ival;
619 if (x.isNegative())
620 {
621 negative = true;
622 xwords = new int[xlen];
623 negate(xwords, x.words, xlen);
624 }
625 else
626 {
627 negative = false;
628 xwords = x.words;
629 }
630 if (y.isNegative())
631 {
632 negative = !negative;
633 ywords = new int[ylen];
634 negate(ywords, y.words, ylen);
635 }
636 else
637 ywords = y.words;
638 // Swap if x is shorter then y.
639 if (xlen < ylen)
640 {
641 int[] twords = xwords; xwords = ywords; ywords = twords;
642 int tlen = xlen; xlen = ylen; ylen = tlen;
643 }
644 BigInteger result = BigInteger.alloc(xlen+ylen);
645 MPN.mul(result.words, xwords, xlen, ywords, ylen);
646 result.ival = xlen+ylen;
647 if (negative)
648 result.setNegative();
649 return result.canonicalize();
650 }
651
652 public BigInteger multiply(BigInteger y)
653 {
654 return times(this, y);
655 }
656
657 private static void divide(long x, long y,
658 BigInteger quotient, BigInteger remainder,
659 int rounding_mode)
660 {
661 boolean xNegative, yNegative;
662 if (x < 0)
663 {
664 xNegative = true;
665 if (x == Long.MIN_VALUE)
666 {
667 divide(valueOf(x), valueOf(y),
668 quotient, remainder, rounding_mode);
669 return;
670 }
671 x = -x;
672 }
673 else
674 xNegative = false;
675
676 if (y < 0)
677 {
678 yNegative = true;
679 if (y == Long.MIN_VALUE)
680 {
681 if (rounding_mode == TRUNCATE)
682 { // x != Long.Min_VALUE implies abs(x) < abs(y)
683 if (quotient != null)
684 quotient.set(0);
685 if (remainder != null)
686 remainder.set(x);
687 }
688 else
689 divide(valueOf(x), valueOf(y),
690 quotient, remainder, rounding_mode);
691 return;
692 }
693 y = -y;
694 }
695 else
696 yNegative = false;
697
698 long q = x / y;
699 long r = x % y;
700 boolean qNegative = xNegative ^ yNegative;
701
702 boolean add_one = false;
703 if (r != 0)
704 {
705 switch (rounding_mode)
706 {
707 case TRUNCATE:
708 break;
709 case CEILING:
710 case FLOOR:
711 if (qNegative == (rounding_mode == FLOOR))
712 add_one = true;
713 break;
714 case ROUND:
715 add_one = r > ((y - (q & 1)) >> 1);
716 break;
717 }
718 }
719 if (quotient != null)
720 {
721 if (add_one)
722 q++;
723 if (qNegative)
724 q = -q;
725 quotient.set(q);
726 }
727 if (remainder != null)
728 {
729 // The remainder is by definition: X-Q*Y
730 if (add_one)
731 {
732 // Subtract the remainder from Y.
733 r = y - r;
734 // In this case, abs(Q*Y) > abs(X).
735 // So sign(remainder) = -sign(X).
736 xNegative = ! xNegative;
737 }
738 else
739 {
740 // If !add_one, then: abs(Q*Y) <= abs(X).
741 // So sign(remainder) = sign(X).
742 }
743 if (xNegative)
744 r = -r;
745 remainder.set(r);
746 }
747 }
748
749 /** Divide two integers, yielding quotient and remainder.
750 * @param x the numerator in the division
751 * @param y the denominator in the division
752 * @param quotient is set to the quotient of the result (iff quotient!=null)
753 * @param remainder is set to the remainder of the result
754 * (iff remainder!=null)
755 * @param rounding_mode one of FLOOR, CEILING, TRUNCATE, or ROUND.
756 */
757 private static void divide(BigInteger x, BigInteger y,
758 BigInteger quotient, BigInteger remainder,
759 int rounding_mode)
760 {
761 if ((x.words == null || x.ival <= 2)
762 && (y.words == null || y.ival <= 2))
763 {
764 long x_l = x.longValue();
765 long y_l = y.longValue();
766 if (x_l != Long.MIN_VALUE && y_l != Long.MIN_VALUE)
767 {
768 divide(x_l, y_l, quotient, remainder, rounding_mode);
769 return;
770 }
771 }
772
773 boolean xNegative = x.isNegative();
774 boolean yNegative = y.isNegative();
775 boolean qNegative = xNegative ^ yNegative;
776
777 int ylen = y.words == null ? 1 : y.ival;
778 int[] ywords = new int[ylen];
779 y.getAbsolute(ywords);
780 while (ylen > 1 && ywords[ylen - 1] == 0) ylen--;
781
782 int xlen = x.words == null ? 1 : x.ival;
783 int[] xwords = new int[xlen+2];
784 x.getAbsolute(xwords);
785 while (xlen > 1 && xwords[xlen-1] == 0) xlen--;
786
787 int qlen, rlen;
788
789 int cmpval = MPN.cmp(xwords, xlen, ywords, ylen);
790 if (cmpval < 0) // abs(x) < abs(y)
791 { // quotient = 0; remainder = num.
792 int[] rwords = xwords; xwords = ywords; ywords = rwords;
793 rlen = xlen; qlen = 1; xwords[0] = 0;
794 }
795 else if (cmpval == 0) // abs(x) == abs(y)
796 {
797 xwords[0] = 1; qlen = 1; // quotient = 1
798 ywords[0] = 0; rlen = 1; // remainder = 0;
799 }
800 else if (ylen == 1)
801 {
802 qlen = xlen;
803 // Need to leave room for a word of leading zeros if dividing by 1
804 // and the dividend has the high bit set. It might be safe to
805 // increment qlen in all cases, but it certainly is only necessary
806 // in the following case.
807 if (ywords[0] == 1 && xwords[xlen-1] < 0)
808 qlen++;
809 rlen = 1;
810 ywords[0] = MPN.divmod_1(xwords, xwords, xlen, ywords[0]);
811 }
812 else // abs(x) > abs(y)
813 {
814 // Normalize the denominator, i.e. make its most significant bit set by
815 // shifting it normalization_steps bits to the left. Also shift the
816 // numerator the same number of steps (to keep the quotient the same!).
817
818 int nshift = MPN.count_leading_zeros(ywords[ylen - 1]);
819 if (nshift != 0)
820 {
821 // Shift up the denominator setting the most significant bit of
822 // the most significant word.
823 MPN.lshift(ywords, 0, ywords, ylen, nshift);
824
825 // Shift up the numerator, possibly introducing a new most
826 // significant word.
827 int x_high = MPN.lshift(xwords, 0, xwords, xlen, nshift);
828 xwords[xlen++] = x_high;
829 }
830
831 if (xlen == ylen)
832 xwords[xlen++] = 0;
833 MPN.divide(xwords, xlen, ywords, ylen);
834 rlen = ylen;
835 MPN.rshift0 (ywords, xwords, 0, rlen, nshift);
836
837 qlen = xlen + 1 - ylen;
838 if (quotient != null)
839 {
840 for (int i = 0; i < qlen; i++)
841 xwords[i] = xwords[i+ylen];
842 }
843 }
844
845 if (ywords[rlen-1] < 0)
846 {
847 ywords[rlen] = 0;
848 rlen++;
849 }
850
851 // Now the quotient is in xwords, and the remainder is in ywords.
852
853 boolean add_one = false;
854 if (rlen > 1 || ywords[0] != 0)
855 { // Non-zero remainder i.e. in-exact quotient.
856 switch (rounding_mode)
857 {
858 case TRUNCATE:
859 break;
860 case CEILING:
861 case FLOOR:
862 if (qNegative == (rounding_mode == FLOOR))
863 add_one = true;
864 break;
865 case ROUND:
866 // int cmp = compareTo(remainder<<1, abs(y));
867 BigInteger tmp = remainder == null ? new BigInteger() : remainder;
868 tmp.set(ywords, rlen);
869 tmp = shift(tmp, 1);
870 if (yNegative)
871 tmp.setNegative();
872 int cmp = compareTo(tmp, y);
873 // Now cmp == compareTo(sign(y)*(remainder<<1), y)
874 if (yNegative)
875 cmp = -cmp;
876 add_one = (cmp == 1) || (cmp == 0 && (xwords[0]&1) != 0);
877 }
878 }
879 if (quotient != null)
880 {
881 quotient.set(xwords, qlen);
882 if (qNegative)
883 {
884 if (add_one) // -(quotient + 1) == ~(quotient)
885 quotient.setInvert();
886 else
887 quotient.setNegative();
888 }
889 else if (add_one)
890 quotient.setAdd(1);
891 }
892 if (remainder != null)
893 {
894 // The remainder is by definition: X-Q*Y
895 remainder.set(ywords, rlen);
896 if (add_one)
897 {
898 // Subtract the remainder from Y:
899 // abs(R) = abs(Y) - abs(orig_rem) = -(abs(orig_rem) - abs(Y)).
900 BigInteger tmp;
901 if (y.words == null)
902 {
903 tmp = remainder;
904 tmp.set(yNegative ? ywords[0] + y.ival : ywords[0] - y.ival);
905 }
906 else
907 tmp = BigInteger.add(remainder, y, yNegative ? 1 : -1);
908 // Now tmp <= 0.
909 // In this case, abs(Q) = 1 + floor(abs(X)/abs(Y)).
910 // Hence, abs(Q*Y) > abs(X).
911 // So sign(remainder) = -sign(X).
912 if (xNegative)
913 remainder.setNegative(tmp);
914 else
915 remainder.set(tmp);
916 }
917 else
918 {
919 // If !add_one, then: abs(Q*Y) <= abs(X).
920 // So sign(remainder) = sign(X).
921 if (xNegative)
922 remainder.setNegative();
923 }
924 }
925 }
926
927 public BigInteger divide(BigInteger val)
928 {
929 if (val.isZero())
930 throw new ArithmeticException("divisor is zero");
931
932 BigInteger quot = new BigInteger();
933 divide(this, val, quot, null, TRUNCATE);
934 return quot.canonicalize();
935 }
936
937 public BigInteger remainder(BigInteger val)
938 {
939 if (val.isZero())
940 throw new ArithmeticException("divisor is zero");
941
942 BigInteger rem = new BigInteger();
943 divide(this, val, null, rem, TRUNCATE);
944 return rem.canonicalize();
945 }
946
947 public BigInteger[] divideAndRemainder(BigInteger val)
948 {
949 if (val.isZero())
950 throw new ArithmeticException("divisor is zero");
951
952 BigInteger[] result = new BigInteger[2];
953 result[0] = new BigInteger();
954 result[1] = new BigInteger();
955 divide(this, val, result[0], result[1], TRUNCATE);
956 result[0].canonicalize();
957 result[1].canonicalize();
958 return result;
959 }
960
961 public BigInteger mod(BigInteger m)
962 {
963 if (m.isNegative() || m.isZero())
964 throw new ArithmeticException("non-positive modulus");
965
966 BigInteger rem = new BigInteger();
967 divide(this, m, null, rem, FLOOR);
968 return rem.canonicalize();
969 }
970
971 /** Calculate the integral power of a BigInteger.
972 * @param exponent the exponent (must be non-negative)
973 */
974 public BigInteger pow(int exponent)
975 {
976 if (exponent <= 0)
977 {
978 if (exponent == 0)
979 return ONE;
980 throw new ArithmeticException("negative exponent");
981 }
982 if (isZero())
983 return this;
984 int plen = words == null ? 1 : ival; // Length of pow2.
985 int blen = ((bitLength() * exponent) >> 5) + 2 * plen;
986 boolean negative = isNegative() && (exponent & 1) != 0;
987 int[] pow2 = new int [blen];
988 int[] rwords = new int [blen];
989 int[] work = new int [blen];
990 getAbsolute(pow2); // pow2 = abs(this);
991 int rlen = 1;
992 rwords[0] = 1; // rwords = 1;
993 for (;;) // for (i = 0; ; i++)
994 {
995 // pow2 == this**(2**i)
996 // prod = this**(sum(j=0..i-1, (exponent>>j)&1))
997 if ((exponent & 1) != 0)
998 { // r *= pow2
999 MPN.mul(work, pow2, plen, rwords, rlen);
1000 int[] temp = work; work = rwords; rwords = temp;
1001 rlen += plen;
1002 while (rwords[rlen - 1] == 0) rlen--;
1003 }
1004 exponent >>= 1;
1005 if (exponent == 0)
1006 break;
1007 // pow2 *= pow2;
1008 MPN.mul(work, pow2, plen, pow2, plen);
1009 int[] temp = work; work = pow2; pow2 = temp; // swap to avoid a copy
1010 plen *= 2;
1011 while (pow2[plen - 1] == 0) plen--;
1012 }
1013 if (rwords[rlen - 1] < 0)
1014 rlen++;
1015 if (negative)
1016 negate(rwords, rwords, rlen);
1017 return BigInteger.make(rwords, rlen);
1018 }
1019
1020 private static final int[] euclidInv(int a, int b, int prevDiv)
1021 {
1022 if (b == 0)
1023 throw new ArithmeticException("not invertible");
1024
1025 if (b == 1)
1026 // Success: values are indeed invertible!
1027 // Bottom of the recursion reached; start unwinding.
1028 return new int[] { -prevDiv, 1 };
1029
1030 int[] xy = euclidInv(b, a % b, a / b); // Recursion happens here.
1031 a = xy[0]; // use our local copy of 'a' as a work var
1032 xy[0] = a * -prevDiv + xy[1];
1033 xy[1] = a;
1034 return xy;
1035 }
1036
1037 private static final void euclidInv(BigInteger a, BigInteger b,
1038 BigInteger prevDiv, BigInteger[] xy)
1039 {
1040 if (b.isZero())
1041 throw new ArithmeticException("not invertible");
1042
1043 if (b.isOne())
1044 {
1045 // Success: values are indeed invertible!
1046 // Bottom of the recursion reached; start unwinding.
1047 xy[0] = neg(prevDiv);
1048 xy[1] = ONE;
1049 return;
1050 }
1051
1052 // Recursion happens in the following conditional!
1053
1054 // If a just contains an int, then use integer math for the rest.
1055 if (a.words == null)
1056 {
1057 int[] xyInt = euclidInv(b.ival, a.ival % b.ival, a.ival / b.ival);
1058 xy[0] = new BigInteger(xyInt[0]);
1059 xy[1] = new BigInteger(xyInt[1]);
1060 }
1061 else
1062 {
1063 BigInteger rem = new BigInteger();
1064 BigInteger quot = new BigInteger();
1065 divide(a, b, quot, rem, FLOOR);
1066 // quot and rem may not be in canonical form. ensure
1067 rem.canonicalize();
1068 quot.canonicalize();
1069 euclidInv(b, rem, quot, xy);
1070 }
1071
1072 BigInteger t = xy[0];
1073 xy[0] = add(xy[1], times(t, prevDiv), -1);
1074 xy[1] = t;
1075 }
1076
1077 public BigInteger modInverse(BigInteger y)
1078 {
1079 if (y.isNegative() || y.isZero())
1080 throw new ArithmeticException("non-positive modulo");
1081
1082 // Degenerate cases.
1083 if (y.isOne())
1084 return ZERO;
1085 if (isOne())
1086 return ONE;
1087
1088 // Use Euclid's algorithm as in gcd() but do this recursively
1089 // rather than in a loop so we can use the intermediate results as we
1090 // unwind from the recursion.
1091 // Used http://www.math.nmsu.edu/~crypto/EuclideanAlgo.html as reference.
1092 BigInteger result = new BigInteger();
1093 boolean swapped = false;
1094
1095 if (y.words == null)
1096 {
1097 // The result is guaranteed to be less than the modulus, y (which is
1098 // an int), so simplify this by working with the int result of this
1099 // modulo y. Also, if this is negative, make it positive via modulo
1100 // math. Note that BigInteger.mod() must be used even if this is
1101 // already an int as the % operator would provide a negative result if
1102 // this is negative, BigInteger.mod() never returns negative values.
1103 int xval = (words != null || isNegative()) ? mod(y).ival : ival;
1104 int yval = y.ival;
1105
1106 // Swap values so x > y.
1107 if (yval > xval)
1108 {
1109 int tmp = xval; xval = yval; yval = tmp;
1110 swapped = true;
1111 }
1112 // Normally, the result is in the 2nd element of the array, but
1113 // if originally x < y, then x and y were swapped and the result
1114 // is in the 1st element of the array.
1115 result.ival =
1116 euclidInv(yval, xval % yval, xval / yval)[swapped ? 0 : 1];
1117
1118 // Result can't be negative, so make it positive by adding the
1119 // original modulus, y.ival (not the possibly "swapped" yval).
1120 if (result.ival < 0)
1121 result.ival += y.ival;
1122 }
1123 else
1124 {
1125 // As above, force this to be a positive value via modulo math.
1126 BigInteger x = isNegative() ? this.mod(y) : this;
1127
1128 // Swap values so x > y.
1129 if (x.compareTo(y) < 0)
1130 {
1131 result = x; x = y; y = result; // use 'result' as a work var
1132 swapped = true;
1133 }
1134 // As above (for ints), result will be in the 2nd element unless
1135 // the original x and y were swapped.
1136 BigInteger rem = new BigInteger();
1137 BigInteger quot = new BigInteger();
1138 divide(x, y, quot, rem, FLOOR);
1139 // quot and rem may not be in canonical form. ensure
1140 rem.canonicalize();
1141 quot.canonicalize();
1142 BigInteger[] xy = new BigInteger[2];
1143 euclidInv(y, rem, quot, xy);
1144 result = swapped ? xy[0] : xy[1];
1145
1146 // Result can't be negative, so make it positive by adding the
1147 // original modulus, y (which is now x if they were swapped).
1148 if (result.isNegative())
1149 result = add(result, swapped ? x : y, 1);
1150 }
1151
1152 return result;
1153 }
1154
1155 public BigInteger modPow(BigInteger exponent, BigInteger m)
1156 {
1157 if (m.isNegative() || m.isZero())
1158 throw new ArithmeticException("non-positive modulo");
1159
1160 if (exponent.isNegative())
1161 return modInverse(m);
1162 if (exponent.isOne())
1163 return mod(m);
1164
1165 // To do this naively by first raising this to the power of exponent
1166 // and then performing modulo m would be extremely expensive, especially
1167 // for very large numbers. The solution is found in Number Theory
1168 // where a combination of partial powers and moduli can be done easily.
1169 //
1170 // We'll use the algorithm for Additive Chaining which can be found on
1171 // p. 244 of "Applied Cryptography, Second Edition" by Bruce Schneier.
1172 BigInteger s = ONE;
1173 BigInteger t = this;
1174 BigInteger u = exponent;
1175
1176 while (!u.isZero())
1177 {
1178 if (u.and(ONE).isOne())
1179 s = times(s, t).mod(m);
1180 u = u.shiftRight(1);
1181 t = times(t, t).mod(m);
1182 }
1183
1184 return s;
1185 }
1186
1187 /** Calculate Greatest Common Divisor for non-negative ints. */
1188 private static final int gcd(int a, int b)
1189 {
1190 // Euclid's algorithm, copied from libg++.
1191 int tmp;
1192 if (b > a)
1193 {
1194 tmp = a; a = b; b = tmp;
1195 }
1196 for(;;)
1197 {
1198 if (b == 0)
1199 return a;
1200 if (b == 1)
1201 return b;
1202 tmp = b;
1203 b = a % b;
1204 a = tmp;
1205 }
1206 }
1207
1208 public BigInteger gcd(BigInteger y)
1209 {
1210 int xval = ival;
1211 int yval = y.ival;
1212 if (words == null)
1213 {
1214 if (xval == 0)
1215 return abs(y);
1216 if (y.words == null
1217 && xval != Integer.MIN_VALUE && yval != Integer.MIN_VALUE)
1218 {
1219 if (xval < 0)
1220 xval = -xval;
1221 if (yval < 0)
1222 yval = -yval;
1223 return valueOf(gcd(xval, yval));
1224 }
1225 xval = 1;
1226 }
1227 if (y.words == null)
1228 {
1229 if (yval == 0)
1230 return abs(this);
1231 yval = 1;
1232 }
1233 int len = (xval > yval ? xval : yval) + 1;
1234 int[] xwords = new int[len];
1235 int[] ywords = new int[len];
1236 getAbsolute(xwords);
1237 y.getAbsolute(ywords);
1238 len = MPN.gcd(xwords, ywords, len);
1239 BigInteger result = new BigInteger(0);
1240 result.ival = len;
1241 result.words = xwords;
1242 return result.canonicalize();
1243 }
1244
1245 /**
1246 * <p>Returns <code>true</code> if this BigInteger is probably prime,
1247 * <code>false</code> if it's definitely composite. If <code>certainty</code>
1248 * is <code><= 0</code>, <code>true</code> is returned.</p>
1249 *
1250 * @param certainty a measure of the uncertainty that the caller is willing
1251 * to tolerate: if the call returns <code>true</code> the probability that
1252 * this BigInteger is prime exceeds <code>(1 - 1/2<sup>certainty</sup>)</code>.
1253 * The execution time of this method is proportional to the value of this
1254 * parameter.
1255 * @return <code>true</code> if this BigInteger is probably prime,
1256 * <code>false</code> if it's definitely composite.
1257 */
1258 public boolean isProbablePrime(int certainty)
1259 {
1260 if (certainty < 1)
1261 return true;
1262
1263 /** We'll use the Rabin-Miller algorithm for doing a probabilistic
1264 * primality test. It is fast, easy and has faster decreasing odds of a
1265 * composite passing than with other tests. This means that this
1266 * method will actually have a probability much greater than the
1267 * 1 - .5^certainty specified in the JCL (p. 117), but I don't think
1268 * anyone will complain about better performance with greater certainty.
1269 *
1270 * The Rabin-Miller algorithm can be found on pp. 259-261 of "Applied
1271 * Cryptography, Second Edition" by Bruce Schneier.
1272 */
1273
1274 // First rule out small prime factors
1275 BigInteger rem = new BigInteger();
1276 int i;
1277 for (i = 0; i < primes.length; i++)
1278 {
1279 if (words == null && ival == primes[i])
1280 return true;
1281
1282 divide(this, smallFixNums[primes[i] - minFixNum], null, rem, TRUNCATE);
1283 if (rem.canonicalize().isZero())
1284 return false;
1285 }
1286
1287 // Now perform the Rabin-Miller test.
1288
1289 // Set b to the number of times 2 evenly divides (this - 1).
1290 // I.e. 2^b is the largest power of 2 that divides (this - 1).
1291 BigInteger pMinus1 = add(this, -1);
1292 int b = pMinus1.getLowestSetBit();
1293
1294 // Set m such that this = 1 + 2^b * m.
1295 BigInteger m = pMinus1.divide(valueOf(2L << b - 1));
1296
1297 // The HAC (Handbook of Applied Cryptography), Alfred Menezes & al. Note
1298 // 4.49 (controlling the error probability) gives the number of trials
1299 // for an error probability of 1/2**80, given the number of bits in the
1300 // number to test. we shall use these numbers as is if/when 'certainty'
1301 // is less or equal to 80, and twice as much if it's greater.
1302 int bits = this.bitLength();
1303 for (i = 0; i < k.length; i++)
1304 if (bits <= k[i])
1305 break;
1306 int trials = t[i];
1307 if (certainty > 80)
1308 trials *= 2;
1309 BigInteger z;
1310 for (int t = 0; t < trials; t++)
1311 {
1312 // The HAC (Handbook of Applied Cryptography), Alfred Menezes & al.
1313 // Remark 4.28 states: "...A strategy that is sometimes employed
1314 // is to fix the bases a to be the first few primes instead of
1315 // choosing them at random.
1316 z = smallFixNums[primes[t] - minFixNum].modPow(m, this);
1317 if (z.isOne() || z.equals(pMinus1))
1318 continue; // Passes the test; may be prime.
1319
1320 for (i = 0; i < b; )
1321 {
1322 if (z.isOne())
1323 return false;
1324 i++;
1325 if (z.equals(pMinus1))
1326 break; // Passes the test; may be prime.
1327
1328 z = z.modPow(valueOf(2), this);
1329 }
1330
1331 if (i == b && !z.equals(pMinus1))
1332 return false;
1333 }
1334 return true;
1335 }
1336
1337 private void setInvert()
1338 {
1339 if (words == null)
1340 ival = ~ival;
1341 else
1342 {
1343 for (int i = ival; --i >= 0; )
1344 words[i] = ~words[i];
1345 }
1346 }
1347
1348 private void setShiftLeft(BigInteger x, int count)
1349 {
1350 int[] xwords;
1351 int xlen;
1352 if (x.words == null)
1353 {
1354 if (count < 32)
1355 {
1356 set((long) x.ival << count);
1357 return;
1358 }
1359 xwords = new int[1];
1360 xwords[0] = x.ival;
1361 xlen = 1;
1362 }
1363 else
1364 {
1365 xwords = x.words;
1366 xlen = x.ival;
1367 }
1368 int word_count = count >> 5;
1369 count &= 31;
1370 int new_len = xlen + word_count;
1371 if (count == 0)
1372 {
1373 realloc(new_len);
1374 for (int i = xlen; --i >= 0; )
1375 words[i+word_count] = xwords[i];
1376 }
1377 else
1378 {
1379 new_len++;
1380 realloc(new_len);
1381 int shift_out = MPN.lshift(words, word_count, xwords, xlen, count);
1382 count = 32 - count;
1383 words[new_len-1] = (shift_out << count) >> count; // sign-extend.
1384 }
1385 ival = new_len;
1386 for (int i = word_count; --i >= 0; )
1387 words[i] = 0;
1388 }
1389
1390 private void setShiftRight(BigInteger x, int count)
1391 {
1392 if (x.words == null)
1393 set(count < 32 ? x.ival >> count : x.ival < 0 ? -1 : 0);
1394 else if (count == 0)
1395 set(x);
1396 else
1397 {
1398 boolean neg = x.isNegative();
1399 int word_count = count >> 5;
1400 count &= 31;
1401 int d_len = x.ival - word_count;
1402 if (d_len <= 0)
1403 set(neg ? -1 : 0);
1404 else
1405 {
1406 if (words == null || words.length < d_len)
1407 realloc(d_len);
1408 MPN.rshift0 (words, x.words, word_count, d_len, count);
1409 ival = d_len;
1410 if (neg)
1411 words[d_len-1] |= -2 << (31 - count);
1412 }
1413 }
1414 }
1415
1416 private void setShift(BigInteger x, int count)
1417 {
1418 if (count > 0)
1419 setShiftLeft(x, count);
1420 else
1421 setShiftRight(x, -count);
1422 }
1423
1424 private static BigInteger shift(BigInteger x, int count)
1425 {
1426 if (x.words == null)
1427 {
1428 if (count <= 0)
1429 return valueOf(count > -32 ? x.ival >> (-count) : x.ival < 0 ? -1 : 0);
1430 if (count < 32)
1431 return valueOf((long) x.ival << count);
1432 }
1433 if (count == 0)
1434 return x;
1435 BigInteger result = new BigInteger(0);
1436 result.setShift(x, count);
1437 return result.canonicalize();
1438 }
1439
1440 public BigInteger shiftLeft(int n)
1441 {
1442 return shift(this, n);
1443 }
1444
1445 public BigInteger shiftRight(int n)
1446 {
1447 return shift(this, -n);
1448 }
1449
1450 private void format(int radix, StringBuffer buffer)
1451 {
1452 if (words == null)
1453 buffer.append(Integer.toString(ival, radix));
1454 else if (ival <= 2)
1455 buffer.append(Long.toString(longValue(), radix));
1456 else
1457 {
1458 boolean neg = isNegative();
1459 int[] work;
1460 if (neg || radix != 16)
1461 {
1462 work = new int[ival];
1463 getAbsolute(work);
1464 }
1465 else
1466 work = words;
1467 int len = ival;
1468
1469 if (radix == 16)
1470 {
1471 if (neg)
1472 buffer.append('-');
1473 int buf_start = buffer.length();
1474 for (int i = len; --i >= 0; )
1475 {
1476 int word = work[i];
1477 for (int j = 8; --j >= 0; )
1478 {
1479 int hex_digit = (word >> (4 * j)) & 0xF;
1480 // Suppress leading zeros:
1481 if (hex_digit > 0 || buffer.length() > buf_start)
1482 buffer.append(Character.forDigit(hex_digit, 16));
1483 }
1484 }
1485 }
1486 else
1487 {
1488 int i = buffer.length();
1489 for (;;)
1490 {
1491 int digit = MPN.divmod_1(work, work, len, radix);
1492 buffer.append(Character.forDigit(digit, radix));
1493 while (len > 0 && work[len-1] == 0) len--;
1494 if (len == 0)
1495 break;
1496 }
1497 if (neg)
1498 buffer.append('-');
1499 /* Reverse buffer. */
1500 int j = buffer.length() - 1;
1501 while (i < j)
1502 {
1503 char tmp = buffer.charAt(i);
1504 buffer.setCharAt(i, buffer.charAt(j));
1505 buffer.setCharAt(j, tmp);
1506 i++; j--;
1507 }
1508 }
1509 }
1510 }
1511
1512 public String toString()
1513 {
1514 return toString(10);
1515 }
1516
1517 public String toString(int radix)
1518 {
1519 if (words == null)
1520 return Integer.toString(ival, radix);
1521 if (ival <= 2)
1522 return Long.toString(longValue(), radix);
1523 int buf_size = ival * (MPN.chars_per_word(radix) + 1);
1524 StringBuffer buffer = new StringBuffer(buf_size);
1525 format(radix, buffer);
1526 return buffer.toString();
1527 }
1528
1529 public int intValue()
1530 {
1531 if (words == null)
1532 return ival;
1533 return words[0];
1534 }
1535
1536 public long longValue()
1537 {
1538 if (words == null)
1539 return ival;
1540 if (ival == 1)
1541 return words[0];
1542 return ((long)words[1] << 32) + ((long)words[0] & 0xffffffffL);
1543 }
1544
1545 public int hashCode()
1546 {
1547 // FIXME: May not match hashcode of JDK.
1548 return words == null ? ival : (words[0] + words[ival - 1]);
1549 }
1550
1551 /* Assumes x and y are both canonicalized. */
1552 private static boolean equals(BigInteger x, BigInteger y)
1553 {
1554 if (x.words == null && y.words == null)
1555 return x.ival == y.ival;
1556 if (x.words == null || y.words == null || x.ival != y.ival)
1557 return false;
1558 for (int i = x.ival; --i >= 0; )
1559 {
1560 if (x.words[i] != y.words[i])
1561 return false;
1562 }
1563 return true;
1564 }
1565
1566 /* Assumes this and obj are both canonicalized. */
1567 public boolean equals(Object obj)
1568 {
1569 if (obj == null || ! (obj instanceof BigInteger))
1570 return false;
1571 return equals(this, (BigInteger) obj);
1572 }
1573
1574 private static BigInteger valueOf(String s, int radix)
1575 throws NumberFormatException
1576 {
1577 int len = s.length();
1578 // Testing (len < MPN.chars_per_word(radix)) would be more accurate,
1579 // but slightly more expensive, for little practical gain.
1580 if (len <= 15 && radix <= 16)
1581 return valueOf(Long.parseLong(s, radix));
1582
1583 int byte_len = 0;
1584 byte[] bytes = new byte[len];
1585 boolean negative = false;
1586 for (int i = 0; i < len; i++)
1587 {
1588 char ch = s.charAt(i);
1589 if (ch == '-')
1590 negative = true;
1591 else if (ch == '_' || (byte_len == 0 && (ch == ' ' || ch == '\t')))
1592 continue;
1593 else
1594 {
1595 int digit = Character.digit(ch, radix);
1596 if (digit < 0)
1597 break;
1598 bytes[byte_len++] = (byte) digit;
1599 }
1600 }
1601 return valueOf(bytes, byte_len, negative, radix);
1602 }
1603
1604 private static BigInteger valueOf(byte[] digits, int byte_len,
1605 boolean negative, int radix)
1606 {
1607 int chars_per_word = MPN.chars_per_word(radix);
1608 int[] words = new int[byte_len / chars_per_word + 1];
1609 int size = MPN.set_str(words, digits, byte_len, radix);
1610 if (size == 0)
1611 return ZERO;
1612 if (words[size-1] < 0)
1613 words[size++] = 0;
1614 if (negative)
1615 negate(words, words, size);
1616 return make(words, size);
1617 }
1618
1619 public double doubleValue()
1620 {
1621 if (words == null)
1622 return (double) ival;
1623 if (ival <= 2)
1624 return (double) longValue();
1625 if (isNegative())
1626 return neg(this).roundToDouble(0, true, false);
1627 return roundToDouble(0, false, false);
1628 }
1629
1630 public float floatValue()
1631 {
1632 return (float) doubleValue();
1633 }
1634
1635 /** Return true if any of the lowest n bits are one.
1636 * (false if n is negative). */
1637 private boolean checkBits(int n)
1638 {
1639 if (n <= 0)
1640 return false;
1641 if (words == null)
1642 return n > 31 || ((ival & ((1 << n) - 1)) != 0);
1643 int i;
1644 for (i = 0; i < (n >> 5) ; i++)
1645 if (words[i] != 0)
1646 return true;
1647 return (n & 31) != 0 && (words[i] & ((1 << (n & 31)) - 1)) != 0;
1648 }
1649
1650 /** Convert a semi-processed BigInteger to double.
1651 * Number must be non-negative. Multiplies by a power of two, applies sign,
1652 * and converts to double, with the usual java rounding.
1653 * @param exp power of two, positive or negative, by which to multiply
1654 * @param neg true if negative
1655 * @param remainder true if the BigInteger is the result of a truncating
1656 * division that had non-zero remainder. To ensure proper rounding in
1657 * this case, the BigInteger must have at least 54 bits. */
1658 private double roundToDouble(int exp, boolean neg, boolean remainder)
1659 {
1660 // Compute length.
1661 int il = bitLength();
1662
1663 // Exponent when normalized to have decimal point directly after
1664 // leading one. This is stored excess 1023 in the exponent bit field.
1665 exp += il - 1;
1666
1667 // Gross underflow. If exp == -1075, we let the rounding
1668 // computation determine whether it is minval or 0 (which are just
1669 // 0x0000 0000 0000 0001 and 0x0000 0000 0000 0000 as bit
1670 // patterns).
1671 if (exp < -1075)
1672 return neg ? -0.0 : 0.0;
1673
1674 // gross overflow
1675 if (exp > 1023)
1676 return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
1677
1678 // number of bits in mantissa, including the leading one.
1679 // 53 unless it's denormalized
1680 int ml = (exp >= -1022 ? 53 : 53 + exp + 1022);
1681
1682 // Get top ml + 1 bits. The extra one is for rounding.
1683 long m;
1684 int excess_bits = il - (ml + 1);
1685 if (excess_bits > 0)
1686 m = ((words == null) ? ival >> excess_bits
1687 : MPN.rshift_long(words, ival, excess_bits));
1688 else
1689 m = longValue() << (- excess_bits);
1690
1691 // Special rounding for maxval. If the number exceeds maxval by
1692 // any amount, even if it's less than half a step, it overflows.
1693 if (exp == 1023 && ((m >> 1) == (1L << 53) - 1))
1694 {
1695 if (remainder || checkBits(il - ml))
1696 return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
1697 else
1698 return neg ? - Double.MAX_VALUE : Double.MAX_VALUE;
1699 }
1700
1701 // Normal round-to-even rule: round up if the bit dropped is a one, and
1702 // the bit above it or any of the bits below it is a one.
1703 if ((m & 1) == 1
1704 && ((m & 2) == 2 || remainder || checkBits(excess_bits)))
1705 {
1706 m += 2;
1707 // Check if we overflowed the mantissa
1708 if ((m & (1L << 54)) != 0)
1709 {
1710 exp++;
1711 // renormalize
1712 m >>= 1;
1713 }
1714 // Check if a denormalized mantissa was just rounded up to a
1715 // normalized one.
1716 else if (ml == 52 && (m & (1L << 53)) != 0)
1717 exp++;
1718 }
1719
1720 // Discard the rounding bit
1721 m >>= 1;
1722
1723 long bits_sign = neg ? (1L << 63) : 0;
1724 exp += 1023;
1725 long bits_exp = (exp <= 0) ? 0 : ((long)exp) << 52;
1726 long bits_mant = m & ~(1L << 52);
1727 return Double.longBitsToDouble(bits_sign | bits_exp | bits_mant);
1728 }
1729
1730 /** Copy the abolute value of this into an array of words.
1731 * Assumes words.length >= (this.words == null ? 1 : this.ival).
1732 * Result is zero-extended, but need not be a valid 2's complement number.
1733 */
1734 private void getAbsolute(int[] words)
1735 {
1736 int len;
1737 if (this.words == null)
1738 {
1739 len = 1;
1740 words[0] = this.ival;
1741 }
1742 else
1743 {
1744 len = this.ival;
1745 for (int i = len; --i >= 0; )
1746 words[i] = this.words[i];
1747 }
1748 if (words[len - 1] < 0)
1749 negate(words, words, len);
1750 for (int i = words.length; --i > len; )
1751 words[i] = 0;
1752 }
1753
1754 /** Set dest[0:len-1] to the negation of src[0:len-1].
1755 * Return true if overflow (i.e. if src is -2**(32*len-1)).
1756 * Ok for src==dest. */
1757 private static boolean negate(int[] dest, int[] src, int len)
1758 {
1759 long carry = 1;
1760 boolean negative = src[len-1] < 0;
1761 for (int i = 0; i < len; i++)
1762 {
1763 carry += ((long) (~src[i]) & 0xffffffffL);
1764 dest[i] = (int) carry;
1765 carry >>= 32;
1766 }
1767 return (negative && dest[len-1] < 0);
1768 }
1769
1770 /** Destructively set this to the negative of x.
1771 * It is OK if x==this.*/
1772 private void setNegative(BigInteger x)
1773 {
1774 int len = x.ival;
1775 if (x.words == null)
1776 {
1777 if (len == Integer.MIN_VALUE)
1778 set(- (long) len);
1779 else
1780 set(-len);
1781 return;
1782 }
1783 realloc(len + 1);
1784 if (negate(words, x.words, len))
1785 words[len++] = 0;
1786 ival = len;
1787 }
1788
1789 /** Destructively negate this. */
1790 private final void setNegative()
1791 {
1792 setNegative(this);
1793 }
1794
1795 private static BigInteger abs(BigInteger x)
1796 {
1797 return x.isNegative() ? neg(x) : x;
1798 }
1799
1800 public BigInteger abs()
1801 {
1802 return abs(this);
1803 }
1804
1805 private static BigInteger neg(BigInteger x)
1806 {
1807 if (x.words == null && x.ival != Integer.MIN_VALUE)
1808 return valueOf(- x.ival);
1809 BigInteger result = new BigInteger(0);
1810 result.setNegative(x);
1811 return result.canonicalize();
1812 }
1813
1814 public BigInteger negate()
1815 {
1816 return neg(this);
1817 }
1818
1819 /** Calculates ceiling(log2(this < 0 ? -this : this+1))
1820 * See Common Lisp: the Language, 2nd ed, p. 361.
1821 */
1822 public int bitLength()
1823 {
1824 if (words == null)
1825 return MPN.intLength(ival);
1826 return MPN.intLength(words, ival);
1827 }
1828
1829 public byte[] toByteArray()
1830 {
1831 // Determine number of bytes needed. The method bitlength returns
1832 // the size without the sign bit, so add one bit for that and then
1833 // add 7 more to emulate the ceil function using integer math.
1834 byte[] bytes = new byte[(bitLength() + 1 + 7) / 8];
1835 int nbytes = bytes.length;
1836
1837 int wptr = 0;
1838 int word;
1839
1840 // Deal with words array until one word or less is left to process.
1841 // If BigInteger is an int, then it is in ival and nbytes will be <= 4.
1842 while (nbytes > 4)
1843 {
1844 word = words[wptr++];
1845 for (int i = 4; i > 0; --i, word >>= 8)
1846 bytes[--nbytes] = (byte) word;
1847 }
1848
1849 // Deal with the last few bytes. If BigInteger is an int, use ival.
1850 word = (words == null) ? ival : words[wptr];
1851 for ( ; nbytes > 0; word >>= 8)
1852 bytes[--nbytes] = (byte) word;
1853
1854 return bytes;
1855 }
1856
1857 /** Return the boolean opcode (for bitOp) for swapped operands.
1858 * I.e. bitOp(swappedOp(op), x, y) == bitOp(op, y, x).
1859 */
1860 private static int swappedOp(int op)
1861 {
1862 return
1863 "\000\001\004\005\002\003\006\007\010\011\014\015\012\013\016\017"
1864 .charAt(op);
1865 }
1866
1867 /** Do one the the 16 possible bit-wise operations of two BigIntegers. */
1868 private static BigInteger bitOp(int op, BigInteger x, BigInteger y)
1869 {
1870 switch (op)
1871 {
1872 case 0: return ZERO;
1873 case 1: return x.and(y);
1874 case 3: return x;
1875 case 5: return y;
1876 case 15: return valueOf(-1);
1877 }
1878 BigInteger result = new BigInteger();
1879 setBitOp(result, op, x, y);
1880 return result.canonicalize();
1881 }
1882
1883 /** Do one the the 16 possible bit-wise operations of two BigIntegers. */
1884 private static void setBitOp(BigInteger result, int op,
1885 BigInteger x, BigInteger y)
1886 {
1887 if (y.words == null) ;
1888 else if (x.words == null || x.ival < y.ival)
1889 {
1890 BigInteger temp = x; x = y; y = temp;
1891 op = swappedOp(op);
1892 }
1893 int xi;
1894 int yi;
1895 int xlen, ylen;
1896 if (y.words == null)
1897 {
1898 yi = y.ival;
1899 ylen = 1;
1900 }
1901 else
1902 {
1903 yi = y.words[0];
1904 ylen = y.ival;
1905 }
1906 if (x.words == null)
1907 {
1908 xi = x.ival;
1909 xlen = 1;
1910 }
1911 else
1912 {
1913 xi = x.words[0];
1914 xlen = x.ival;
1915 }
1916 if (xlen > 1)
1917 result.realloc(xlen);
1918 int[] w = result.words;
1919 int i = 0;
1920 // Code for how to handle the remainder of x.
1921 // 0: Truncate to length of y.
1922 // 1: Copy rest of x.
1923 // 2: Invert rest of x.
1924 int finish = 0;
1925 int ni;
1926 switch (op)
1927 {
1928 case 0: // clr
1929 ni = 0;
1930 break;
1931 case 1: // and
1932 for (;;)
1933 {
1934 ni = xi & yi;
1935 if (i+1 >= ylen) break;
1936 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1937 }
1938 if (yi < 0) finish = 1;
1939 break;
1940 case 2: // andc2
1941 for (;;)
1942 {
1943 ni = xi & ~yi;
1944 if (i+1 >= ylen) break;
1945 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1946 }
1947 if (yi >= 0) finish = 1;
1948 break;
1949 case 3: // copy x
1950 ni = xi;
1951 finish = 1; // Copy rest
1952 break;
1953 case 4: // andc1
1954 for (;;)
1955 {
1956 ni = ~xi & yi;
1957 if (i+1 >= ylen) break;
1958 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1959 }
1960 if (yi < 0) finish = 2;
1961 break;
1962 case 5: // copy y
1963 for (;;)
1964 {
1965 ni = yi;
1966 if (i+1 >= ylen) break;
1967 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1968 }
1969 break;
1970 case 6: // xor
1971 for (;;)
1972 {
1973 ni = xi ^ yi;
1974 if (i+1 >= ylen) break;
1975 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1976 }
1977 finish = yi < 0 ? 2 : 1;
1978 break;
1979 case 7: // ior
1980 for (;;)
1981 {
1982 ni = xi | yi;
1983 if (i+1 >= ylen) break;
1984 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1985 }
1986 if (yi >= 0) finish = 1;
1987 break;
1988 case 8: // nor
1989 for (;;)
1990 {
1991 ni = ~(xi | yi);
1992 if (i+1 >= ylen) break;
1993 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1994 }
1995 if (yi >= 0) finish = 2;
1996 break;
1997 case 9: // eqv [exclusive nor]
1998 for (;;)
1999 {
2000 ni = ~(xi ^ yi);
2001 if (i+1 >= ylen) break;
2002 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
2003 }
2004 finish = yi >= 0 ? 2 : 1;
2005 break;
2006 case 10: // c2
2007 for (;;)
2008 {
2009 ni = ~yi;
2010 if (i+1 >= ylen) break;
2011 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
2012 }
2013 break;
2014 case 11: // orc2
2015 for (;;)
2016 {
2017 ni = xi | ~yi;
2018 if (i+1 >= ylen) break;
2019 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
2020 }
2021 if (yi < 0) finish = 1;
2022 break;
2023 case 12: // c1
2024 ni = ~xi;
2025 finish = 2;
2026 break;
2027 case 13: // orc1
2028 for (;;)
2029 {
2030 ni = ~xi | yi;
2031 if (i+1 >= ylen) break;
2032 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
2033 }
2034 if (yi >= 0) finish = 2;
2035 break;
2036 case 14: // nand
2037 for (;;)
2038 {
2039 ni = ~(xi & yi);
2040 if (i+1 >= ylen) break;
2041 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
2042 }
2043 if (yi < 0) finish = 2;
2044 break;
2045 default:
2046 case 15: // set
2047 ni = -1;
2048 break;
2049 }
2050 // Here i==ylen-1; w[0]..w[i-1] have the correct result;
2051 // and ni contains the correct result for w[i+1].
2052 if (i+1 == xlen)
2053 finish = 0;
2054 switch (finish)
2055 {
2056 case 0:
2057 if (i == 0 && w == null)
2058 {
2059 result.ival = ni;
2060 return;
2061 }
2062 w[i++] = ni;
2063 break;
2064 case 1: w[i] = ni; while (++i < xlen) w[i] = x.words[i]; break;
2065 case 2: w[i] = ni; while (++i < xlen) w[i] = ~x.words[i]; break;
2066 }
2067 result.ival = i;
2068 }
2069
2070 /** Return the logical (bit-wise) "and" of a BigInteger and an int. */
2071 private static BigInteger and(BigInteger x, int y)
2072 {
2073 if (x.words == null)
2074 return valueOf(x.ival & y);
2075 if (y >= 0)
2076 return valueOf(x.words[0] & y);
2077 int len = x.ival;
2078 int[] words = new int[len];
2079 words[0] = x.words[0] & y;
2080 while (--len > 0)
2081 words[len] = x.words[len];
2082 return make(words, x.ival);
2083 }
2084
2085 /** Return the logical (bit-wise) "and" of two BigIntegers. */
2086 public BigInteger and(BigInteger y)
2087 {
2088 if (y.words == null)
2089 return and(this, y.ival);
2090 else if (words == null)
2091 return and(y, ival);
2092
2093 BigInteger x = this;
2094 if (ival < y.ival)
2095 {
2096 BigInteger temp = this; x = y; y = temp;
2097 }
2098 int i;
2099 int len = y.isNegative() ? x.ival : y.ival;
2100 int[] words = new int[len];
2101 for (i = 0; i < y.ival; i++)
2102 words[i] = x.words[i] & y.words[i];
2103 for ( ; i < len; i++)
2104 words[i] = x.words[i];
2105 return make(words, len);
2106 }
2107
2108 /** Return the logical (bit-wise) "(inclusive) or" of two BigIntegers. */
2109 public BigInteger or(BigInteger y)
2110 {
2111 return bitOp(7, this, y);
2112 }
2113
2114 /** Return the logical (bit-wise) "exclusive or" of two BigIntegers. */
2115 public BigInteger xor(BigInteger y)
2116 {
2117 return bitOp(6, this, y);
2118 }
2119
2120 /** Return the logical (bit-wise) negation of a BigInteger. */
2121 public BigInteger not()
2122 {
2123 return bitOp(12, this, ZERO);
2124 }
2125
2126 public BigInteger andNot(BigInteger val)
2127 {
2128 return and(val.not());
2129 }
2130
2131 public BigInteger clearBit(int n)
2132 {
2133 if (n < 0)
2134 throw new ArithmeticException();
2135
2136 return and(ONE.shiftLeft(n).not());
2137 }
2138
2139 public BigInteger setBit(int n)
2140 {
2141 if (n < 0)
2142 throw new ArithmeticException();
2143
2144 return or(ONE.shiftLeft(n));
2145 }
2146
2147 public boolean testBit(int n)
2148 {
2149 if (n < 0)
2150 throw new ArithmeticException();
2151
2152 return !and(ONE.shiftLeft(n)).isZero();
2153 }
2154
2155 public BigInteger flipBit(int n)
2156 {
2157 if (n < 0)
2158 throw new ArithmeticException();
2159
2160 return xor(ONE.shiftLeft(n));
2161 }
2162
2163 public int getLowestSetBit()
2164 {
2165 if (isZero())
2166 return -1;
2167
2168 if (words == null)
2169 return MPN.findLowestBit(ival);
2170 else
2171 return MPN.findLowestBit(words);
2172 }
2173
2174 // bit4count[I] is number of '1' bits in I.
2175 private static final byte[] bit4_count = { 0, 1, 1, 2, 1, 2, 2, 3,
2176 1, 2, 2, 3, 2, 3, 3, 4};
2177
2178 private static int bitCount(int i)
2179 {
2180 int count = 0;
2181 while (i != 0)
2182 {
2183 count += bit4_count[i & 15];
2184 i >>>= 4;
2185 }
2186 return count;
2187 }
2188
2189 private static int bitCount(int[] x, int len)
2190 {
2191 int count = 0;
2192 while (--len >= 0)
2193 count += bitCount(x[len]);
2194 return count;
2195 }
2196
2197 /** Count one bits in a BigInteger.
2198 * If argument is negative, count zero bits instead. */
2199 public int bitCount()
2200 {
2201 int i, x_len;
2202 int[] x_words = words;
2203 if (x_words == null)
2204 {
2205 x_len = 1;
2206 i = bitCount(ival);
2207 }
2208 else
2209 {
2210 x_len = ival;
2211 i = bitCount(x_words, x_len);
2212 }
2213 return isNegative() ? x_len * 32 - i : i;
2214 }
2215
2216 private void readObject(ObjectInputStream s)
2217 throws IOException, ClassNotFoundException
2218 {
2219 s.defaultReadObject();
2220 words = byteArrayToIntArray(magnitude, signum < 0 ? -1 : 0);
2221 BigInteger result = make(words, words.length);
2222 this.ival = result.ival;
2223 this.words = result.words;
2224 }
2225
2226 private void writeObject(ObjectOutputStream s)
2227 throws IOException, ClassNotFoundException
2228 {
2229 signum = signum();
2230 magnitude = toByteArray();
2231 s.defaultWriteObject();
2232 }
2233}
Note: See TracBrowser for help on using the repository browser.