1 // BigInteger.java -- an arbitrary-precision integer
3 /* Copyright (C) 1999, 2000 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
12 import gnu.gcj.math.*;
13 import java.util.Random;
16 * @author Warren Levy <warrenl@cygnus.com>
17 * @date December 20, 1999.
21 * Written using on-line Java Platform 1.2 API Specification, as well
22 * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998) and
23 * "Applied Cryptography, Second Edition" by Bruce Schneier (Wiley, 1996).
26 * Based primarily on IntNum.java BitOps.java by Per Bothner <per@bothner.com>
27 * (found in Kawa 1.6.62).
29 * Status: Believed complete and correct.
32 public class BigInteger extends Number implements Comparable
34 /** All integers are stored in 2's-complement form.
35 * If words == null, the ival is the value of this BigInteger.
36 * Otherwise, the first ival elements of words make the value
37 * of this BigInteger, stored in little-endian order, 2's-complement form. */
42 /** We pre-allocate integers in the range minFixNum..maxFixNum. */
43 private static final int minFixNum = -100;
44 private static final int maxFixNum = 1024;
45 private static final int numFixNum = maxFixNum-minFixNum+1;
46 private static final BigInteger[] smallFixNums = new BigInteger[numFixNum];
49 for (int i = numFixNum; --i >= 0; )
50 smallFixNums[i] = new BigInteger(i + minFixNum);
54 public static final BigInteger ZERO = smallFixNums[-minFixNum];
57 public static final BigInteger ONE = smallFixNums[1 - minFixNum];
60 private static final int FLOOR = 1;
61 private static final int CEILING = 2;
62 private static final int TRUNCATE = 3;
63 private static final int ROUND = 4;
65 /** When checking the probability of primes, it is most efficient to
66 * first check the factoring of small primes, so we'll use this array.
68 private static final int[] primes =
69 { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
70 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
71 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
72 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 };
78 /* Create a new (non-shared) BigInteger, and initialize to an int. */
79 private BigInteger(int value)
84 public BigInteger(String val, int radix)
86 BigInteger result = valueOf(val, radix);
87 this.ival = result.ival;
88 this.words = result.words;
91 public BigInteger(String val)
96 /* Create a new (non-shared) BigInteger, and initialize from a byte array. */
97 public BigInteger(byte[] val)
99 if (val == null || val.length < 1)
100 throw new NumberFormatException();
102 words = byteArrayToIntArray(val, val[0] < 0 ? -1 : 0);
103 BigInteger result = make(words, words.length);
104 this.ival = result.ival;
105 this.words = result.words;
108 public BigInteger(int signum, byte[] magnitude)
110 if (magnitude == null || signum > 1 || signum < -1)
111 throw new NumberFormatException();
116 for (i = magnitude.length - 1; i >= 0 && magnitude[i] == 0; --i)
119 throw new NumberFormatException();
123 // Magnitude is always positive, so don't ever pass a sign of -1.
124 words = byteArrayToIntArray(magnitude, 0);
125 BigInteger result = make(words, words.length);
126 this.ival = result.ival;
127 this.words = result.words;
133 public BigInteger(int numBits, Random rnd)
136 throw new IllegalArgumentException();
138 // Result is always positive so tack on an extra zero word, it will be
139 // canonicalized out later if necessary.
140 int nwords = numBits / 32 + 2;
141 words = new int[nwords];
143 words[--nwords] = rnd.nextInt() >>> (numBits % 32);
144 while (--nwords >= 0)
145 words[nwords] = rnd.nextInt();
147 BigInteger result = make(words, words.length);
148 this.ival = result.ival;
149 this.words = result.words;
152 public BigInteger(int bitLength, int certainty, Random rnd)
154 this(bitLength, rnd);
156 // Keep going until we find a probable prime.
159 if (isProbablePrime(certainty))
162 BigInteger next = new BigInteger(bitLength, rnd);
163 this.ival = next.ival;
164 this.words = next.words;
168 /** Return a (possibly-shared) BigInteger with a given long value. */
169 private static BigInteger make(long value)
171 if (value >= minFixNum && value <= maxFixNum)
172 return smallFixNums[(int)value - minFixNum];
174 if ((long)i == value)
175 return new BigInteger(i);
176 BigInteger result = alloc(2);
179 result.words[1] = (int) (value >> 32);
183 // FIXME: Could simply rename 'make' method above as valueOf while
184 // changing all instances of 'make'. Don't do this until this class
185 // is done as the Kawa class this is based on has 'make' methods
186 // with other parameters; wait to see if they are used in BigInteger.
187 public static BigInteger valueOf(long val)
192 /** Make a canonicalized BigInteger from an array of words.
193 * The array may be reused (without copying). */
194 private static BigInteger make(int[] words, int len)
198 len = BigInteger.wordsNeeded(words, len);
200 return len == 0 ? ZERO : make(words[0]);
201 BigInteger num = new BigInteger();
207 /** Convert a big-endian byte array to a little-endian array of words. */
208 private static int[] byteArrayToIntArray(byte[] bytes, int sign)
210 // Determine number of words needed.
211 int[] words = new int[(bytes.length + 3) / 4 + 1];
212 int nwords = words.length;
214 // For simplicity, tack on an extra word of sign at the front,
215 // it will be canonicalized out later. */
216 words[--nwords] = sign;
218 // Create a int out of modulo 4 high order bytes.
221 for (int i = bytes.length % 4; i > 0; --i, bptr++)
222 word = (word << 8) | (((int) bytes[bptr]) & 0xff);
223 words[--nwords] = word;
225 // Elements remaining in byte[] are a multiple of 4.
227 words[--nwords] = bytes[bptr++] << 24 |
228 (((int) bytes[bptr++]) & 0xff) << 16 |
229 (((int) bytes[bptr++]) & 0xff) << 8 |
230 (((int) bytes[bptr++]) & 0xff);
234 /** Allocate a new non-shared BigInteger.
235 * @param nwords number of words to allocate
237 private static BigInteger alloc(int nwords)
240 return new BigInteger();
241 BigInteger result = new BigInteger();
242 result.words = new int[nwords];
246 /** Change words.length to nwords.
247 * We allow words.length to be upto nwords+2 without reallocating.
249 private void realloc(int nwords)
260 else if (words == null
261 || words.length < nwords
262 || words.length > nwords + 2)
264 int[] new_words = new int [nwords];
274 System.arraycopy(words, 0, new_words, 0, ival);
280 private final boolean isNegative()
282 return (words == null ? ival : words[ival - 1]) < 0;
287 int top = words == null ? ival : words[ival-1];
288 if (top == 0 && words == null)
290 return top < 0 ? -1 : 1;
293 private static int compareTo(BigInteger x, BigInteger y)
295 if (x.words == null && y.words == null)
296 return x.ival < y.ival ? -1 : x.ival > y.ival ? 1 : 0;
297 boolean x_negative = x.isNegative();
298 boolean y_negative = y.isNegative();
299 if (x_negative != y_negative)
300 return x_negative ? -1 : 1;
301 int x_len = x.words == null ? 1 : x.ival;
302 int y_len = y.words == null ? 1 : y.ival;
304 return (x_len > y_len) != x_negative ? 1 : -1;
305 return MPN.cmp(x.words, y.words, x_len);
309 public int compareTo(Object obj)
311 if (obj instanceof BigInteger)
312 return compareTo(this, (BigInteger) obj);
313 throw new ClassCastException();
316 public int compareTo(BigInteger val)
318 return compareTo(this, val);
321 public BigInteger min(BigInteger val)
323 return compareTo(this, val) < 0 ? this : val;
326 public BigInteger max(BigInteger val)
328 return compareTo(this, val) > 0 ? this : val;
331 private final boolean isOdd()
333 int low = words == null ? ival : words[0];
334 return (low & 1) != 0;
337 private final boolean isZero()
339 return words == null && ival == 0;
342 private final boolean isOne()
344 return words == null && ival == 1;
347 private final boolean isMinusOne()
349 return words == null && ival == -1;
352 /** Calculate how many words are significant in words[0:len-1].
353 * Returns the least value x such that x>0 && words[0:x-1]==words[0:len-1],
354 * when words is viewed as a 2's complement integer.
356 private static int wordsNeeded(int[] words, int len)
361 int word = words[--i];
364 while (i > 0 && (word = words[i - 1]) < 0)
367 if (word != -1) break;
372 while (word == 0 && i > 0 && (word = words[i - 1]) >= 0) i--;
378 private BigInteger canonicalize()
381 && (ival = BigInteger.wordsNeeded(words, ival)) <= 1)
387 if (words == null && ival >= minFixNum && ival <= maxFixNum)
388 return smallFixNums[(int) ival - minFixNum];
392 /** Add two ints, yielding a BigInteger. */
393 private static final BigInteger add(int x, int y)
395 return BigInteger.make((long) x + (long) y);
398 /** Add a BigInteger and an int, yielding a new BigInteger. */
399 private static BigInteger add(BigInteger x, int y)
402 return BigInteger.add(x.ival, y);
403 BigInteger result = new BigInteger(0);
405 return result.canonicalize();
408 /** Set this to the sum of x and y.
410 private void setAdd(BigInteger x, int y)
414 set((long) x.ival + (long) y);
420 for (int i = 0; i < len; i++)
422 carry += ((long) x.words[i] & 0xffffffffL);
423 words[i] = (int) carry;
426 if (x.words[len - 1] < 0)
428 words[len] = (int) carry;
429 ival = wordsNeeded(words, len + 1);
432 /** Destructively add an int to this. */
433 private final void setAdd(int y)
438 /** Destructively set the value of this to a long. */
439 private final void set(long y)
451 words[1] = (int) (y >> 32);
456 /** Destructively set the value of this to the given words.
457 * The words array is reused, not copied. */
458 private final void set(int[] words, int length)
464 /** Destructively set the value of this to that of y. */
465 private final void set(BigInteger y)
472 System.arraycopy(y.words, 0, words, 0, y.ival);
477 /** Add two BigIntegers, yielding their sum as another BigInteger. */
478 private static BigInteger add(BigInteger x, BigInteger y, int k)
480 if (x.words == null && y.words == null)
481 return BigInteger.make((long) k * (long) y.ival + (long) x.ival);
485 y = BigInteger.neg(y);
487 y = BigInteger.times(y, BigInteger.make(k));
490 return BigInteger.add(y, x.ival);
492 return BigInteger.add(x, y.ival);
496 { // Swap so x is longer then y.
497 BigInteger tmp = x; x = y; y = tmp;
499 BigInteger result = alloc(x.ival + 1);
501 long carry = MPN.add_n(result.words, x.words, y.words, i);
502 long y_ext = y.words[i - 1] < 0 ? 0xffffffffL : 0;
503 for (; i < x.ival; i++)
505 carry += ((long) x.words[i] & 0xffffffffL) + y_ext;;
506 result.words[i] = (int) carry;
509 if (x.words[i - 1] < 0)
511 result.words[i] = (int) (carry + y_ext);
513 return result.canonicalize();
516 public BigInteger add(BigInteger val)
518 return add(this, val, 1);
521 public BigInteger subtract(BigInteger val)
523 return add(this, val, -1);
526 private static final BigInteger times(BigInteger x, int y)
532 int[] xwords = x.words;
535 return BigInteger.make((long) xlen * (long) y);
537 BigInteger result = BigInteger.alloc(xlen + 1);
538 if (xwords[xlen - 1] < 0)
541 negate(result.words, xwords, xlen);
542 xwords = result.words;
548 negative = !negative;
551 result.words[xlen] = MPN.mul_1(result.words, xwords, xlen, y);
552 result.ival = xlen + 1;
554 result.setNegative();
555 return result.canonicalize();
558 private static final BigInteger times(BigInteger x, BigInteger y)
561 return times(x, y.ival);
563 return times(y, x.ival);
564 boolean negative = false;
572 xwords = new int[xlen];
573 negate(xwords, x.words, xlen);
582 negative = !negative;
583 ywords = new int[ylen];
584 negate(ywords, y.words, ylen);
588 // Swap if x is shorter then y.
591 int[] twords = xwords; xwords = ywords; ywords = twords;
592 int tlen = xlen; xlen = ylen; ylen = tlen;
594 BigInteger result = BigInteger.alloc(xlen+ylen);
595 MPN.mul(result.words, xwords, xlen, ywords, ylen);
596 result.ival = xlen+ylen;
598 result.setNegative();
599 return result.canonicalize();
602 public BigInteger multiply(BigInteger y)
604 return times(this, y);
607 private static void divide(long x, long y,
608 BigInteger quotient, BigInteger remainder,
611 boolean xNegative, yNegative;
615 if (x == Long.MIN_VALUE)
617 divide(BigInteger.make(x), BigInteger.make(y),
618 quotient, remainder, rounding_mode);
629 if (y == Long.MIN_VALUE)
631 if (rounding_mode == TRUNCATE)
632 { // x != Long.Min_VALUE implies abs(x) < abs(y)
633 if (quotient != null)
635 if (remainder != null)
639 divide(BigInteger.make(x), BigInteger.make(y),
640 quotient, remainder, rounding_mode);
650 boolean qNegative = xNegative ^ yNegative;
652 boolean add_one = false;
655 switch (rounding_mode)
661 if (qNegative == (rounding_mode == FLOOR))
665 add_one = r > ((y - (q & 1)) >> 1);
669 if (quotient != null)
677 if (remainder != null)
679 // The remainder is by definition: X-Q*Y
682 // Subtract the remainder from Y.
684 // In this case, abs(Q*Y) > abs(X).
685 // So sign(remainder) = -sign(X).
686 xNegative = ! xNegative;
690 // If !add_one, then: abs(Q*Y) <= abs(X).
691 // So sign(remainder) = sign(X).
699 /** Divide two integers, yielding quotient and remainder.
700 * @param x the numerator in the division
701 * @param y the denominator in the division
702 * @param quotient is set to the quotient of the result (iff quotient!=null)
703 * @param remainder is set to the remainder of the result
704 * (iff remainder!=null)
705 * @param rounding_mode one of FLOOR, CEILING, TRUNCATE, or ROUND.
707 private static void divide(BigInteger x, BigInteger y,
708 BigInteger quotient, BigInteger remainder,
711 if ((x.words == null || x.ival <= 2)
712 && (y.words == null || y.ival <= 2))
714 long x_l = x.longValue();
715 long y_l = y.longValue();
716 if (x_l != Long.MIN_VALUE && y_l != Long.MIN_VALUE)
718 divide(x_l, y_l, quotient, remainder, rounding_mode);
723 boolean xNegative = x.isNegative();
724 boolean yNegative = y.isNegative();
725 boolean qNegative = xNegative ^ yNegative;
727 int ylen = y.words == null ? 1 : y.ival;
728 int[] ywords = new int[ylen];
729 y.getAbsolute(ywords);
730 while (ylen > 1 && ywords[ylen - 1] == 0) ylen--;
732 int xlen = x.words == null ? 1 : x.ival;
733 int[] xwords = new int[xlen+2];
734 x.getAbsolute(xwords);
735 while (xlen > 1 && xwords[xlen-1] == 0) xlen--;
739 int cmpval = MPN.cmp(xwords, xlen, ywords, ylen);
740 if (cmpval < 0) // abs(x) < abs(y)
741 { // quotient = 0; remainder = num.
742 int[] rwords = xwords; xwords = ywords; ywords = rwords;
743 rlen = xlen; qlen = 1; xwords[0] = 0;
745 else if (cmpval == 0) // abs(x) == abs(y)
747 xwords[0] = 1; qlen = 1; // quotient = 1
748 ywords[0] = 0; rlen = 1; // remainder = 0;
754 ywords[0] = MPN.divmod_1(xwords, xwords, xlen, ywords[0]);
756 else // abs(x) > abs(y)
758 // Normalize the denominator, i.e. make its most significant bit set by
759 // shifting it normalization_steps bits to the left. Also shift the
760 // numerator the same number of steps (to keep the quotient the same!).
762 int nshift = MPN.count_leading_zeros(ywords[ylen - 1]);
765 // Shift up the denominator setting the most significant bit of
766 // the most significant word.
767 MPN.lshift(ywords, 0, ywords, ylen, nshift);
769 // Shift up the numerator, possibly introducing a new most
771 int x_high = MPN.lshift(xwords, 0, xwords, xlen, nshift);
772 xwords[xlen++] = x_high;
777 MPN.divide(xwords, xlen, ywords, ylen);
779 if (remainder != null || rounding_mode != TRUNCATE)
782 System.arraycopy(xwords, 0, ywords, 0, rlen);
784 MPN.rshift(ywords, xwords, 0, rlen, nshift);
787 qlen = xlen + 1 - ylen;
788 if (quotient != null)
790 for (int i = 0; i < qlen; i++)
791 xwords[i] = xwords[i+ylen];
795 // Now the quotient is in xwords, and the remainder is in ywords.
797 boolean add_one = false;
798 if (rlen > 1 || ywords[0] != 0)
799 { // Non-zero remainder i.e. in-exact quotient.
800 switch (rounding_mode)
806 if (qNegative == (rounding_mode == FLOOR))
810 // int cmp = compareTo(remainder<<1, abs(y));
811 BigInteger tmp = remainder == null ? new BigInteger() : remainder;
812 tmp.set(ywords, rlen);
816 int cmp = compareTo(tmp, y);
817 // Now cmp == compareTo(sign(y)*(remainder<<1), y)
820 add_one = (cmp == 1) || (cmp == 0 && (xwords[0]&1) != 0);
823 if (quotient != null)
825 quotient.set(xwords, qlen);
828 if (add_one) // -(quotient + 1) == ~(quotient)
829 quotient.setInvert();
831 quotient.setNegative();
836 if (remainder != null)
838 // The remainder is by definition: X-Q*Y
839 remainder.set(ywords, rlen);
842 // Subtract the remainder from Y:
843 // abs(R) = abs(Y) - abs(orig_rem) = -(abs(orig_rem) - abs(Y)).
848 tmp.set(yNegative ? ywords[0] + y.ival : ywords[0] - y.ival);
851 tmp = BigInteger.add(remainder, y, yNegative ? 1 : -1);
853 // In this case, abs(Q) = 1 + floor(abs(X)/abs(Y)).
854 // Hence, abs(Q*Y) > abs(X).
855 // So sign(remainder) = -sign(X).
857 remainder.setNegative(tmp);
863 // If !add_one, then: abs(Q*Y) <= abs(X).
864 // So sign(remainder) = sign(X).
866 remainder.setNegative();
871 public BigInteger divide(BigInteger val)
874 throw new ArithmeticException("divisor is zero");
876 BigInteger quot = new BigInteger();
877 divide(this, val, quot, null, TRUNCATE);
878 return quot.canonicalize();
881 public BigInteger remainder(BigInteger val)
884 throw new ArithmeticException("divisor is zero");
886 BigInteger rem = new BigInteger();
887 divide(this, val, null, rem, TRUNCATE);
888 return rem.canonicalize();
891 public BigInteger[] divideAndRemainder(BigInteger val)
894 throw new ArithmeticException("divisor is zero");
896 BigInteger[] result = new BigInteger[2];
897 result[0] = new BigInteger();
898 result[1] = new BigInteger();
899 divide(this, val, result[0], result[1], TRUNCATE);
900 result[0].canonicalize();
901 result[1].canonicalize();
905 public BigInteger mod(BigInteger m)
907 if (m.isNegative() || m.isZero())
908 throw new ArithmeticException("non-positive modulus");
910 BigInteger rem = new BigInteger();
911 divide(this, m, null, rem, FLOOR);
912 return rem.canonicalize();
915 /** Calculate power for BigInteger exponents.
916 * @param y exponent assumed to be non-negative. */
917 private BigInteger pow(BigInteger y)
922 return y.isOdd () ? this : ONE;
923 if (y.words == null && y.ival >= 0)
926 // Assume exponent is non-negative.
930 // Implemented by repeated squaring and multiplication.
931 BigInteger pow2 = this;
933 for (;;) // for (i = 0; ; i++)
936 // prod = x**(sum(j=0..i-1, (y>>j)&1))
938 r = r == null ? pow2 : times(r, pow2); // r *= pow2
939 y = BigInteger.shift(y, -1);
943 pow2 = times(pow2, pow2);
945 return r == null ? ONE : r;
948 /** Calculate the integral power of a BigInteger.
949 * @param exponent the exponent (must be non-negative)
951 public BigInteger pow(int exponent)
958 throw new ArithmeticException("negative exponent");
962 int plen = words == null ? 1 : ival; // Length of pow2.
963 int blen = ((bitLength() * exponent) >> 5) + 2 * plen;
964 boolean negative = isNegative() && (exponent & 1) != 0;
965 int[] pow2 = new int [blen];
966 int[] rwords = new int [blen];
967 int[] work = new int [blen];
968 getAbsolute(pow2); // pow2 = abs(this);
970 rwords[0] = 1; // rwords = 1;
971 for (;;) // for (i = 0; ; i++)
973 // pow2 == this**(2**i)
974 // prod = this**(sum(j=0..i-1, (exponent>>j)&1))
975 if ((exponent & 1) != 0)
977 MPN.mul(work, pow2, plen, rwords, rlen);
978 int[] temp = work; work = rwords; rwords = temp;
980 while (rwords[rlen - 1] == 0) rlen--;
986 MPN.mul(work, pow2, plen, pow2, plen);
987 int[] temp = work; work = pow2; pow2 = temp; // swap to avoid a copy
989 while (pow2[plen - 1] == 0) plen--;
991 if (rwords[rlen - 1] < 0)
994 negate(rwords, rwords, rlen);
995 return BigInteger.make(rwords, rlen);
998 private static final int[] euclidInv(int a, int b, int prevDiv)
1000 // Storage for return values, plus one slot for a temp int (see below).
1004 throw new ArithmeticException("not invertible");
1007 // Success: values are indeed invertible!
1008 // Bottom of the recursion reached; start unwinding.
1015 xy = euclidInv(b, a % b, a / b); // Recursion happens here.
1017 // xy[2] is just temp storage for intermediate results in the following
1018 // calculation. This saves us a bit of space over having an int
1019 // allocated at every level of this recursive method.
1021 xy[0] = xy[2] * -prevDiv + xy[1];
1026 private static final BigInteger[]
1027 euclidInv(BigInteger a, BigInteger b, BigInteger prevDiv)
1029 // FIXME: This method could be more efficient memory-wise and should be
1030 // modified as such since it is recursive.
1032 // Storage for return values, plus one slot for a temp int (see below).
1036 throw new ArithmeticException("not invertible");
1039 // Success: values are indeed invertible!
1040 // Bottom of the recursion reached; start unwinding.
1041 xy = new BigInteger[3];
1042 xy[0] = neg(prevDiv);
1047 // Recursion happens in the following conditional!
1049 // If a just contains an int, then use integer math for the rest.
1050 if (a.words == null)
1052 int[] xyInt = euclidInv(b.ival, a.ival % b.ival, a.ival / b.ival);
1053 xy = new BigInteger[3];
1054 xy[0] = new BigInteger(xyInt[0]);
1055 xy[1] = new BigInteger(xyInt[1]);
1059 BigInteger rem = new BigInteger();
1060 BigInteger quot = new BigInteger();
1061 divide(a, b, quot, rem, FLOOR);
1062 xy = euclidInv(b, rem, quot);
1065 // xy[2] is just temp storage for intermediate results in the following
1066 // calculation. This saves us a bit of space over having a BigInteger
1067 // allocated at every level of this recursive method.
1069 xy[0] = add(xy[1], times(xy[2], prevDiv), -1);
1074 public BigInteger modInverse(BigInteger y)
1076 if (y.isNegative() || y.isZero())
1077 throw new ArithmeticException("non-positive modulo");
1079 // Degenerate cases.
1085 // Use Euclid's algorithm as in gcd() but do this recursively
1086 // rather than in a loop so we can use the intermediate results as we
1087 // unwind from the recursion.
1088 // Used http://www.math.nmsu.edu/~crypto/EuclideanAlgo.html as reference.
1089 BigInteger result = new BigInteger();
1092 boolean swapped = false;
1094 if (y.words == null)
1096 // The result is guaranteed to be less than the modulus, y (which is
1097 // an int), so simplify this by working with the int result of this
1098 // modulo y. Also, if this is negative, make it positive via modulo
1099 // math. Note that BigInteger.mod() must be used even if this is
1100 // already an int as the % operator would provide a negative result if
1101 // this is negative, BigInteger.mod() never returns negative values.
1102 if (words != null || isNegative())
1105 // Swap values so x > y.
1108 int tmp = xval; xval = yval; yval = tmp;
1111 // Normally, the result is in the 2nd element of the array, but
1112 // if originally x < y, then x and y were swapped and the result
1113 // is in the 1st element of the array.
1115 euclidInv(yval, xval % yval, xval / yval)[swapped ? 0 : 1];
1117 // Result can't be negative, so make it positive by adding the
1118 // original modulus, y.ival (not the possibly "swapped" yval).
1119 if (result.ival < 0)
1120 result.ival += y.ival;
1124 BigInteger x = this;
1126 // As above, force this to be a positive value via modulo math.
1130 // Swap values so x > y.
1131 if (x.compareTo(y) < 0)
1133 BigInteger tmp = x; x = y; y = tmp;
1136 // As above (for ints), result will be in the 2nd element unless
1137 // the original x and y were swapped.
1138 BigInteger rem = new BigInteger();
1139 BigInteger quot = new BigInteger();
1140 divide(x, y, quot, rem, FLOOR);
1141 result = euclidInv(y, rem, quot)[swapped ? 0 : 1];
1143 // Result can't be negative, so make it positive by adding the
1144 // original modulus, y (which is now x if they were swapped).
1145 if (result.isNegative())
1146 result = add(result, swapped ? x : y, 1);
1152 public BigInteger modPow(BigInteger exponent, BigInteger m)
1154 if (m.isNegative() || m.isZero())
1155 throw new ArithmeticException("non-positive modulo");
1157 if (exponent.isNegative())
1158 return modInverse(m);
1159 if (exponent.isOne())
1162 // To do this naively by first raising this to the power of exponent
1163 // and then performing modulo m would be extremely expensive, especially
1164 // for very large numbers. The solution is found in Number Theory
1165 // where a combination of partial powers and modulos can be done easily.
1167 // We'll use the algorithm for Additive Chaining which can be found on
1168 // p. 244 of "Applied Cryptography, Second Edition" by Bruce Schneier.
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);
1187 /** Calculate Greatest Common Divisor for non-negative ints. */
1188 private static final int gcd(int a, int b)
1190 // Euclid's algorithm, copied from libg++.
1193 int tmp = a; a = b; b = tmp;
1210 public BigInteger gcd(BigInteger y)
1217 return BigInteger.abs(y);
1219 && xval != Integer.MIN_VALUE && yval != Integer.MIN_VALUE)
1225 return BigInteger.make(BigInteger.gcd(xval, yval));
1229 if (y.words == null)
1232 return BigInteger.abs(this);
1235 int len = (xval > yval ? xval : yval) + 1;
1236 int[] xwords = new int[len];
1237 int[] ywords = new int[len];
1238 getAbsolute(xwords);
1239 y.getAbsolute(ywords);
1240 len = MPN.gcd(xwords, ywords, len);
1241 BigInteger result = new BigInteger(0);
1243 result.words = xwords;
1244 return result.canonicalize();
1247 public boolean isProbablePrime(int certainty)
1249 /** We'll use the Rabin-Miller algorithm for doing a probabilistic
1250 * primality test. It is fast, easy and has faster decreasing odds of a
1251 * composite passing than with other tests. This means that this
1252 * method will actually have a probability much greater than the
1253 * 1 - .5^certainty specified in the JCL (p. 117), but I don't think
1254 * anyone will complain about better performance with greater certainty.
1256 * The Rabin-Miller algorithm can be found on pp. 259-261 of "Applied
1257 * Cryptography, Second Edition" by Bruce Schneier.
1260 // First rule out small prime factors and assure the number is odd.
1261 for (int i = 0; i < primes.length; i++)
1263 if (words == null && ival == primes[i])
1265 if (remainder(make(primes[i])).isZero())
1269 // Now perform the Rabin-Miller test.
1270 // NB: I know that this can be simplified programatically, but
1271 // I have tried to keep it as close as possible to the algorithm
1272 // as written in the Schneier book for reference purposes.
1274 // Set b to the number of times 2 evenly divides (this - 1).
1275 // I.e. 2^b is the largest power of 2 that divides (this - 1).
1276 BigInteger pMinus1 = add(this, -1);
1277 int b = pMinus1.getLowestSetBit();
1279 // Set m such that this = 1 + 2^b * m.
1280 BigInteger m = pMinus1.divide(make(2L << b - 1));
1282 Random rand = new Random();
1283 while (certainty-- > 0)
1285 // Pick a random number greater than 1 and less than this.
1286 // The algorithm says to pick a small number to make the calculations
1287 // go faster, but it doesn't say how small; we'll use 2 to 1024.
1288 int a = rand.nextInt();
1289 a = (a < 0 ? -a : a) % 1023 + 2;
1291 BigInteger z = make(a).modPow(m, this);
1292 if (z.isOne() || z.equals(pMinus1))
1293 continue; // Passes the test; may be prime.
1296 for (i = 0; i < b; )
1301 if (z.equals(pMinus1))
1302 break; // Passes the test; may be prime.
1304 z = z.modPow(make(2), this);
1307 if (i == b && !z.equals(pMinus1))
1313 private void setInvert()
1319 for (int i = ival; --i >= 0; )
1320 words[i] = ~words[i];
1324 private void setShiftLeft(BigInteger x, int count)
1328 if (x.words == null)
1332 set((long) x.ival << count);
1335 xwords = new int[1];
1344 int word_count = count >> 5;
1346 int new_len = xlen + word_count;
1350 for (int i = xlen; --i >= 0; )
1351 words[i+word_count] = xwords[i];
1357 int shift_out = MPN.lshift(words, word_count, xwords, xlen, count);
1359 words[new_len-1] = (shift_out << count) >> count; // sign-extend.
1362 for (int i = word_count; --i >= 0; )
1366 private void setShiftRight(BigInteger x, int count)
1368 if (x.words == null)
1369 set(count < 32 ? x.ival >> count : x.ival < 0 ? -1 : 0);
1370 else if (count == 0)
1374 boolean neg = x.isNegative();
1375 int word_count = count >> 5;
1377 int d_len = x.ival - word_count;
1382 if (words == null || words.length < d_len)
1384 MPN.rshift(words, x.words, word_count, d_len, count);
1387 words[ival-1] |= -1 << (32 - count);
1392 private void setShift(BigInteger x, int count)
1395 setShiftLeft(x, count);
1397 setShiftRight(x, -count);
1400 private static BigInteger shift(BigInteger x, int count)
1402 if (x.words == null)
1405 return make(count > -32 ? x.ival >> (-count) : x.ival < 0 ? -1 : 0);
1407 return make((long) x.ival << count);
1411 BigInteger result = new BigInteger(0);
1412 result.setShift(x, count);
1413 return result.canonicalize();
1416 public BigInteger shiftLeft(int n)
1418 return shift(this, n);
1421 public BigInteger shiftRight(int n)
1423 return shift(this, -n);
1426 private void format(int radix, StringBuffer buffer)
1429 buffer.append(Integer.toString(ival, radix));
1431 buffer.append(Long.toString(longValue(), radix));
1434 boolean neg = isNegative();
1436 if (neg || radix != 16)
1438 work = new int[ival];
1445 int buf_size = len * (MPN.chars_per_word(radix) + 1);
1450 int buf_start = buffer.length();
1451 for (int i = len; --i >= 0; )
1454 for (int j = 8; --j >= 0; )
1456 int hex_digit = (word >> (4 * j)) & 0xF;
1457 // Suppress leading zeros:
1458 if (hex_digit > 0 || buffer.length() > buf_start)
1459 buffer.append(Character.forDigit(hex_digit, 16));
1465 int i = buffer.length();
1468 int digit = MPN.divmod_1(work, work, len, radix);
1469 buffer.append(Character.forDigit(digit, radix));
1470 while (len > 0 && work[len-1] == 0) len--;
1476 /* Reverse buffer. */
1477 int j = buffer.length() - 1;
1480 char tmp = buffer.charAt(i);
1481 buffer.setCharAt(i, buffer.charAt(j));
1482 buffer.setCharAt(j, tmp);
1489 public String toString()
1491 return toString(10);
1494 public String toString(int radix)
1497 return Integer.toString(ival, radix);
1499 return Long.toString(longValue(), radix);
1500 int buf_size = ival * (MPN.chars_per_word(radix) + 1);
1501 StringBuffer buffer = new StringBuffer(buf_size);
1502 format(radix, buffer);
1503 return buffer.toString();
1506 public int intValue()
1513 public long longValue()
1519 return ((long)words[1] << 32) + ((long)words[0] & 0xffffffffL);
1522 public int hashCode()
1524 // FIXME: May not match hashcode of JDK.
1525 return words == null ? ival : (words[0] + words[ival - 1]);
1528 /* Assumes x and y are both canonicalized. */
1529 private static boolean equals(BigInteger x, BigInteger y)
1531 if (x.words == null && y.words == null)
1532 return x.ival == y.ival;
1533 if (x.words == null || y.words == null || x.ival != y.ival)
1535 for (int i = x.ival; --i >= 0; )
1537 if (x.words[i] != y.words[i])
1543 /* Assumes this and obj are both canonicalized. */
1544 public boolean equals(Object obj)
1546 if (obj == null || ! (obj instanceof BigInteger))
1548 return BigInteger.equals(this, (BigInteger) obj);
1551 private static BigInteger valueOf(String s, int radix)
1552 throws NumberFormatException
1554 int len = s.length();
1555 // Testing (len < MPN.chars_per_word(radix)) would be more accurate,
1556 // but slightly more expensive, for little practical gain.
1557 if (len <= 15 && radix <= 16)
1558 return BigInteger.make(Long.parseLong(s, radix));
1561 byte[] bytes = new byte[len];
1562 boolean negative = false;
1563 for (int i = 0; i < len; i++)
1565 char ch = s.charAt(i);
1568 else if (ch == '_' || (byte_len == 0 && (ch == ' ' || ch == '\t')))
1572 int digit = Character.digit(ch, radix);
1575 bytes[byte_len++] = (byte) digit;
1578 return valueOf(bytes, byte_len, negative, radix);
1581 private static BigInteger valueOf(byte[] digits, int byte_len,
1582 boolean negative, int radix)
1584 int chars_per_word = MPN.chars_per_word(radix);
1585 int[] words = new int[byte_len / chars_per_word + 1];
1586 int size = MPN.set_str(words, digits, byte_len, radix);
1589 if (words[size-1] < 0)
1592 negate(words, words, size);
1593 return make(words, size);
1596 public double doubleValue()
1599 return (double) ival;
1601 return (double) longValue();
1603 return BigInteger.neg(this).roundToDouble(0, true, false);
1605 return roundToDouble(0, false, false);
1608 public float floatValue()
1610 return (float) doubleValue();
1613 /** Return true if any of the lowest n bits are one.
1614 * (false if n is negative). */
1615 private boolean checkBits(int n)
1620 return n > 31 || ((ival & ((1 << n) - 1)) != 0);
1622 for (i = 0; i < (n >> 5) ; i++)
1625 return (n & 31) != 0 && (words[i] & ((1 << (n & 31)) - 1)) != 0;
1628 /** Convert a semi-processed BigInteger to double.
1629 * Number must be non-negative. Multiplies by a power of two, applies sign,
1630 * and converts to double, with the usual java rounding.
1631 * @param exp power of two, positive or negative, by which to multiply
1632 * @param neg true if negative
1633 * @param remainder true if the BigInteger is the result of a truncating
1634 * division that had non-zero remainder. To ensure proper rounding in
1635 * this case, the BigInteger must have at least 54 bits. */
1636 private double roundToDouble(int exp, boolean neg, boolean remainder)
1639 int il = bitLength();
1641 // Exponent when normalized to have decimal point directly after
1642 // leading one. This is stored excess 1023 in the exponent bit field.
1645 // Gross underflow. If exp == -1075, we let the rounding
1646 // computation determine whether it is minval or 0 (which are just
1647 // 0x0000 0000 0000 0001 and 0x0000 0000 0000 0000 as bit
1650 return neg ? -0.0 : 0.0;
1654 return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
1656 // number of bits in mantissa, including the leading one.
1657 // 53 unless it's denormalized
1658 int ml = (exp >= -1022 ? 53 : 53 + exp + 1022);
1660 // Get top ml + 1 bits. The extra one is for rounding.
1662 int excess_bits = il - (ml + 1);
1663 if (excess_bits > 0)
1664 m = ((words == null) ? ival >> excess_bits
1665 : MPN.rshift_long(words, ival, excess_bits));
1667 m = longValue() << (- excess_bits);
1669 // Special rounding for maxval. If the number exceeds maxval by
1670 // any amount, even if it's less than half a step, it overflows.
1671 if (exp == 1023 && ((m >> 1) == (1L << 53) - 1))
1673 if (remainder || checkBits(il - ml))
1674 return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
1676 return neg ? - Double.MAX_VALUE : Double.MAX_VALUE;
1679 // Normal round-to-even rule: round up if the bit dropped is a one, and
1680 // the bit above it or any of the bits below it is a one.
1682 && ((m & 2) == 2 || remainder || checkBits(excess_bits)))
1685 // Check if we overflowed the mantissa
1686 if ((m & (1L << 54)) != 0)
1692 // Check if a denormalized mantissa was just rounded up to a
1694 else if (ml == 52 && (m & (1L << 53)) != 0)
1698 // Discard the rounding bit
1701 long bits_sign = neg ? (1L << 63) : 0;
1703 long bits_exp = (exp <= 0) ? 0 : ((long)exp) << 52;
1704 long bits_mant = m & ~(1L << 52);
1705 return Double.longBitsToDouble(bits_sign | bits_exp | bits_mant);
1708 /** Copy the abolute value of this into an array of words.
1709 * Assumes words.length >= (this.words == null ? 1 : this.ival).
1710 * Result is zero-extended, but need not be a valid 2's complement number.
1713 private void getAbsolute(int[] words)
1716 if (this.words == null)
1719 words[0] = this.ival;
1724 for (int i = len; --i >= 0; )
1725 words[i] = this.words[i];
1727 if (words[len - 1] < 0)
1728 negate(words, words, len);
1729 for (int i = words.length; --i > len; )
1733 /** Set dest[0:len-1] to the negation of src[0:len-1].
1734 * Return true if overflow (i.e. if src is -2**(32*len-1)).
1735 * Ok for src==dest. */
1736 private static boolean negate(int[] dest, int[] src, int len)
1739 boolean negative = src[len-1] < 0;
1740 for (int i = 0; i < len; i++)
1742 carry += ((long) (~src[i]) & 0xffffffffL);
1743 dest[i] = (int) carry;
1746 return (negative && dest[len-1] < 0);
1749 /** Destructively set this to the negative of x.
1750 * It is OK if x==this.*/
1751 private void setNegative(BigInteger x)
1754 if (x.words == null)
1756 if (len == Integer.MIN_VALUE)
1763 if (BigInteger.negate(words, x.words, len))
1768 /** Destructively negate this. */
1769 private final void setNegative()
1774 private static BigInteger abs(BigInteger x)
1776 return x.isNegative() ? neg(x) : x;
1779 public BigInteger abs()
1784 private static BigInteger neg(BigInteger x)
1786 if (x.words == null && x.ival != Integer.MIN_VALUE)
1787 return make(- x.ival);
1788 BigInteger result = new BigInteger(0);
1789 result.setNegative(x);
1790 return result.canonicalize();
1793 public BigInteger negate()
1795 return BigInteger.neg(this);
1798 /** Calculates ceiling(log2(this < 0 ? -this : this+1))
1799 * See Common Lisp: the Language, 2nd ed, p. 361.
1801 public int bitLength()
1804 return MPN.intLength(ival);
1806 return MPN.intLength(words, ival);
1809 public byte[] toByteArray()
1811 // Determine number of bytes needed. The method bitlength returns
1812 // the size without the sign bit, so add one bit for that and then
1813 // add 7 more to emulate the ceil function using integer math.
1814 byte[] bytes = new byte[(bitLength() + 1 + 7) / 8];
1815 int nbytes = bytes.length;
1820 // Deal with words array until one word or less is left to process.
1821 // If BigInteger is an int, then it is in ival and nbytes will be <= 4.
1824 word = words[wptr++];
1825 for (int i = 4; i > 0; --i, word >>= 8)
1826 bytes[--nbytes] = (byte) word;
1829 // Deal with the last few bytes. If BigInteger is an int, use ival.
1830 word = (words == null) ? ival : words[wptr];
1831 for ( ; nbytes > 0; word >>= 8)
1832 bytes[--nbytes] = (byte) word;
1837 /** Return the boolean opcode (for bitOp) for swapped operands.
1838 * I.e. bitOp(swappedOp(op), x, y) == bitOp(op, y, x).
1840 private static int swappedOp(int op)
1843 "\000\001\004\005\002\003\006\007\010\011\014\015\012\013\016\017"
1847 /** Do one the the 16 possible bit-wise operations of two BigIntegers. */
1848 private static BigInteger bitOp(int op, BigInteger x, BigInteger y)
1852 case 0: return ZERO;
1853 case 1: return x.and(y);
1856 case 15: return make(-1);
1858 BigInteger result = new BigInteger();
1859 setBitOp(result, op, x, y);
1860 return result.canonicalize();
1863 /** Do one the the 16 possible bit-wise operations of two BigIntegers. */
1864 private static void setBitOp(BigInteger result, int op,
1865 BigInteger x, BigInteger y)
1867 if (y.words == null) ;
1868 else if (x.words == null || x.ival < y.ival)
1870 BigInteger temp = x; x = y; y = temp;
1876 if (y.words == null)
1886 if (x.words == null)
1897 result.realloc(xlen);
1898 int[] w = result.words;
1900 // Code for how to handle the remainder of x.
1901 // 0: Truncate to length of y.
1902 // 1: Copy rest of x.
1903 // 2: Invert rest of x.
1915 if (i+1 >= ylen) break;
1916 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1918 if (yi < 0) finish = 1;
1924 if (i+1 >= ylen) break;
1925 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1927 if (yi >= 0) finish = 1;
1931 finish = 1; // Copy rest
1937 if (i+1 >= ylen) break;
1938 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1940 if (yi < 0) finish = 2;
1946 if (i+1 >= ylen) break;
1947 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1954 if (i+1 >= ylen) break;
1955 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1957 finish = yi < 0 ? 2 : 1;
1963 if (i+1 >= ylen) break;
1964 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1966 if (yi >= 0) finish = 1;
1972 if (i+1 >= ylen) break;
1973 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1975 if (yi >= 0) finish = 2;
1977 case 9: // eqv [exclusive nor]
1981 if (i+1 >= ylen) break;
1982 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1984 finish = yi >= 0 ? 2 : 1;
1990 if (i+1 >= ylen) break;
1991 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
1998 if (i+1 >= ylen) break;
1999 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
2001 if (yi < 0) finish = 1;
2011 if (i+1 >= ylen) break;
2012 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
2014 if (yi >= 0) finish = 2;
2020 if (i+1 >= ylen) break;
2021 w[i++] = ni; xi = x.words[i]; yi = y.words[i];
2023 if (yi < 0) finish = 2;
2030 // Here i==ylen-1; w[0]..w[i-1] have the correct result;
2031 // and ni contains the correct result for w[i+1].
2037 if (i == 0 && w == null)
2044 case 1: w[i] = ni; while (++i < xlen) w[i] = x.words[i]; break;
2045 case 2: w[i] = ni; while (++i < xlen) w[i] = ~x.words[i]; break;
2050 /** Return the logical (bit-wise) "and" of a BigInteger and an int. */
2051 private static BigInteger and(BigInteger x, int y)
2053 if (x.words == null)
2054 return BigInteger.make(x.ival & y);
2056 return BigInteger.make(x.words[0] & y);
2058 int[] words = new int[len];
2059 words[0] = x.words[0] & y;
2061 words[len] = x.words[len];
2062 return BigInteger.make(words, x.ival);
2065 /** Return the logical (bit-wise) "and" of two BigIntegers. */
2066 public BigInteger and(BigInteger y)
2068 if (y.words == null)
2069 return and(this, y.ival);
2070 else if (words == null)
2071 return and(y, ival);
2073 BigInteger x = this;
2076 BigInteger temp = this; x = y; y = temp;
2079 int len = y.isNegative() ? x.ival : y.ival;
2080 int[] words = new int[len];
2081 for (i = 0; i < y.ival; i++)
2082 words[i] = x.words[i] & y.words[i];
2083 for ( ; i < len; i++)
2084 words[i] = x.words[i];
2085 return BigInteger.make(words, len);
2088 /** Return the logical (bit-wise) "(inclusive) or" of two BigIntegers. */
2089 public BigInteger or(BigInteger y)
2091 return bitOp(7, this, y);
2094 /** Return the logical (bit-wise) "exclusive or" of two BigIntegers. */
2095 public BigInteger xor(BigInteger y)
2097 return bitOp(6, this, y);
2100 /** Return the logical (bit-wise) negation of a BigInteger. */
2101 public BigInteger not()
2103 return bitOp(12, this, ZERO);
2106 public BigInteger andNot(BigInteger val)
2108 return and(val.not());
2111 public BigInteger clearBit(int n)
2114 throw new ArithmeticException();
2116 return and(ONE.shiftLeft(n).not());
2119 public BigInteger setBit(int n)
2122 throw new ArithmeticException();
2124 return or(ONE.shiftLeft(n));
2127 public boolean testBit(int n)
2130 throw new ArithmeticException();
2132 return !and(ONE.shiftLeft(n)).isZero();
2135 public BigInteger flipBit(int n)
2138 throw new ArithmeticException();
2140 return xor(ONE.shiftLeft(n));
2143 public int getLowestSetBit()
2149 return MPN.findLowestBit(ival);
2151 return MPN.findLowestBit(words);
2154 // bit4count[I] is number of '1' bits in I.
2155 private static final byte[] bit4_count = { 0, 1, 1, 2, 1, 2, 2, 3,
2156 1, 2, 2, 3, 2, 3, 3, 4};
2158 private static int bitCount(int i)
2163 count += bit4_count[i & 15];
2169 private static int bitCount(int[] x, int len)
2173 count += bitCount(x[len]);
2177 /** Count one bits in a BigInteger.
2178 * If argument is negative, count zero bits instead. */
2179 public int bitCount()
2182 int[] x_words = words;
2183 if (x_words == null)
2191 i = bitCount(x_words, x_len);
2193 return isNegative() ? x_len * 32 - i : i;