/[classpath]/classpath/java/math/BigInteger.java
ViewVC logotype

Diff of /classpath/java/math/BigInteger.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

Legend:
Removed from v.1.10  
changed lines
  Added in v.1.11

savannah-hackers-public@gnu.org
ViewVC Help
Powered by ViewVC 1.1.26