BigInteger.java 71.5 KB
Newer Older
Tom Tromey committed
1
/* java.math.BigInteger -- Arbitary precision integers
2
   Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2005, 2006, 2007  Free Software Foundation, Inc.
Tom Tromey committed
3 4 5 6 7 8 9

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
10

Tom Tromey committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package java.math;

41 42 43 44
import gnu.classpath.Configuration;

import gnu.java.lang.CPStringBuilder;
import gnu.java.math.GMP;
Tom Tromey committed
45 46 47 48 49 50
import gnu.java.math.MPN;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Random;
51
import java.util.logging.Logger;
Tom Tromey committed
52 53 54 55 56

/**
 * Written using on-line Java Platform 1.2 API Specification, as well
 * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998) and
 * "Applied Cryptography, Second Edition" by Bruce Schneier (Wiley, 1996).
57
 *
Tom Tromey committed
58 59 60 61 62 63 64
 * Based primarily on IntNum.java BitOps.java by Per Bothner (per@bothner.com)
 * (found in Kawa 1.6.62).
 *
 * @author Warren Levy (warrenl@cygnus.com)
 * @date December 20, 1999.
 * @status believed complete and correct.
 */
65
public class BigInteger extends Number implements Comparable<BigInteger>
Tom Tromey committed
66
{
67 68
  private static final Logger log = Logger.getLogger(BigInteger.class.getName());

Tom Tromey committed
69 70 71 72 73 74 75 76
  /** All integers are stored in 2's-complement form.
   * If words == null, the ival is the value of this BigInteger.
   * Otherwise, the first ival elements of words make the value
   * of this BigInteger, stored in little-endian order, 2's-complement form. */
  private transient int ival;
  private transient int[] words;

  // Serialization fields.
77 78
  // the first three, although not used in the code, are present for
  // compatibility with older RI versions of this class. DO NOT REMOVE.
Tom Tromey committed
79 80 81 82 83 84 85 86
  private int bitCount = -1;
  private int bitLength = -1;
  private int lowestSetBit = -2;
  private byte[] magnitude;
  private int signum;
  private static final long serialVersionUID = -8287574255936472291L;


87
  /** We pre-allocate integers in the range minFixNum..maxFixNum.
88
   * Note that we must at least preallocate 0, 1, and 10.  */
Tom Tromey committed
89 90 91
  private static final int minFixNum = -100;
  private static final int maxFixNum = 1024;
  private static final int numFixNum = maxFixNum-minFixNum+1;
92
  private static final BigInteger[] smallFixNums;
93

94 95 96 97 98
  /** The alter-ego GMP instance for this. */
  private transient GMP mpz;

  private static final boolean USING_NATIVE = Configuration.WANT_NATIVE_BIG_INTEGER
                                              && initializeLibrary();
Tom Tromey committed
99

100 101
  static
  {
102 103 104 105 106 107 108 109 110 111
    if (USING_NATIVE)
      {
        smallFixNums = null;
        ZERO = valueOf(0L);
        ONE = valueOf(1L);
        TEN = valueOf(10L);
      }
    else
      {
        smallFixNums = new BigInteger[numFixNum];
112 113
        for (int i = numFixNum;  --i >= 0; )
          smallFixNums[i] = new BigInteger(i + minFixNum);
114 115 116 117 118

        ZERO = smallFixNums[-minFixNum];
        ONE = smallFixNums[1 - minFixNum];
        TEN = smallFixNums[10 - minFixNum];
      }
Tom Tromey committed
119 120
  }

121 122 123 124
  /**
   * The constant zero as a BigInteger.
   * @since 1.2
   */
125
  public static final BigInteger ZERO;
Tom Tromey committed
126

127 128 129 130
  /**
   * The constant one as a BigInteger.
   * @since 1.2
   */
131
  public static final BigInteger ONE;
132

133 134 135 136
  /**
   * The constant ten as a BigInteger.
   * @since 1.5
   */
137
  public static final BigInteger TEN;
Tom Tromey committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

  /* Rounding modes: */
  private static final int FLOOR = 1;
  private static final int CEILING = 2;
  private static final int TRUNCATE = 3;
  private static final int ROUND = 4;

  /** When checking the probability of primes, it is most efficient to
   * first check the factoring of small primes, so we'll use this array.
   */
  private static final int[] primes =
    {   2,   3,   5,   7,  11,  13,  17,  19,  23,  29,  31,  37,  41,  43,
       47,  53,  59,  61,  67,  71,  73,  79,  83,  89,  97, 101, 103, 107,
      109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
      191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 };

  /** HAC (Handbook of Applied Cryptography), Alfred Menezes & al. Table 4.4. */
  private static final int[] k =
      {100,150,200,250,300,350,400,500,600,800,1250, Integer.MAX_VALUE};
  private static final int[] t =
      { 27, 18, 15, 12,  9,  8,  7,  6,  5,  4,   3, 2};

  private BigInteger()
  {
162 163 164 165
    super();

    if (USING_NATIVE)
      mpz = new GMP();
Tom Tromey committed
166 167 168 169 170
  }

  /* Create a new (non-shared) BigInteger, and initialize to an int. */
  private BigInteger(int value)
  {
171 172
    super();

Tom Tromey committed
173 174 175
    ival = value;
  }

176
  public BigInteger(String s, int radix)
Tom Tromey committed
177
  {
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    this();

    int len = s.length();
    int i, digit;
    boolean negative;
    byte[] bytes;
    char ch = s.charAt(0);
    if (ch == '-')
      {
        negative = true;
        i = 1;
        bytes = new byte[len - 1];
      }
    else
      {
        negative = false;
        i = 0;
        bytes = new byte[len];
      }
    int byte_len = 0;
    for ( ; i < len;  i++)
      {
        ch = s.charAt(i);
        digit = Character.digit(ch, radix);
        if (digit < 0)
          throw new NumberFormatException("Invalid character at position #" + i);
        bytes[byte_len++] = (byte) digit;
      }

    if (USING_NATIVE)
      {
        bytes = null;
        if (mpz.fromString(s, radix) != 0)
          throw new NumberFormatException("String \"" + s
                                          + "\" is NOT a valid number in base "
                                          + radix);
      }
    else
      {
        BigInteger result;
        // Testing (len < MPN.chars_per_word(radix)) would be more accurate,
        // but slightly more expensive, for little practical gain.
        if (len <= 15 && radix <= 16)
          result = valueOf(Long.parseLong(s, radix));
        else
          result = valueOf(bytes, byte_len, negative, radix);

        this.ival = result.ival;
        this.words = result.words;
      }
Tom Tromey committed
228 229 230 231 232 233 234 235 236 237
  }

  public BigInteger(String val)
  {
    this(val, 10);
  }

  /* Create a new (non-shared) BigInteger, and initialize from a byte array. */
  public BigInteger(byte[] val)
  {
238 239
    this();

Tom Tromey committed
240 241 242
    if (val == null || val.length < 1)
      throw new NumberFormatException();

243 244 245 246 247 248 249 250 251
    if (USING_NATIVE)
      mpz.fromByteArray(val);
    else
      {
        words = byteArrayToIntArray(val, val[0] < 0 ? -1 : 0);
        BigInteger result = make(words, words.length);
        this.ival = result.ival;
        this.words = result.words;
      }
Tom Tromey committed
252 253 254 255
  }

  public BigInteger(int signum, byte[] magnitude)
  {
256 257
    this();

Tom Tromey committed
258 259 260 261 262
    if (magnitude == null || signum > 1 || signum < -1)
      throw new NumberFormatException();

    if (signum == 0)
      {
263 264 265 266 267
        int i;
        for (i = magnitude.length - 1; i >= 0 && magnitude[i] == 0; --i)
          ;
        if (i >= 0)
          throw new NumberFormatException();
Tom Tromey committed
268 269 270
        return;
      }

271 272 273 274 275 276 277 278 279
    if (USING_NATIVE)
      mpz.fromSignedMagnitude(magnitude, signum == -1);
    else
      {
        // Magnitude is always positive, so don't ever pass a sign of -1.
        words = byteArrayToIntArray(magnitude, 0);
        BigInteger result = make(words, words.length);
        this.ival = result.ival;
        this.words = result.words;
Tom Tromey committed
280

281 282 283
        if (signum < 0)
          setNegative();
      }
Tom Tromey committed
284 285 286 287
  }

  public BigInteger(int numBits, Random rnd)
  {
288 289
    this();

Tom Tromey committed
290 291 292 293 294 295 296 297
    if (numBits < 0)
      throw new IllegalArgumentException();

    init(numBits, rnd);
  }

  private void init(int numBits, Random rnd)
  {
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    if (USING_NATIVE)
      {
        int length = (numBits + 7) / 8;
        byte[] magnitude = new byte[length];
        rnd.nextBytes(magnitude);
        int discardedBitCount = numBits % 8;
        if (discardedBitCount != 0)
          {
            discardedBitCount = 8 - discardedBitCount;
            magnitude[0] = (byte)((magnitude[0] & 0xFF) >>> discardedBitCount);
          }
        mpz.fromSignedMagnitude(magnitude, false);
        magnitude = null;
        return;
      }

Tom Tromey committed
314
    int highbits = numBits & 31;
315 316 317 318 319 320 321
    // minimum number of bytes to store the above number of bits
    int highBitByteCount = (highbits + 7) / 8;
    // number of bits to discard from the last byte
    int discardedBitCount = highbits % 8;
    if (discardedBitCount != 0)
      discardedBitCount = 8 - discardedBitCount;
    byte[] highBitBytes = new byte[highBitByteCount];
Tom Tromey committed
322
    if (highbits > 0)
323 324 325 326 327 328
      {
        rnd.nextBytes(highBitBytes);
        highbits = (highBitBytes[highBitByteCount - 1] & 0xFF) >>> discardedBitCount;
        for (int i = highBitByteCount - 2; i >= 0; i--)
          highbits = (highbits << 8) | (highBitBytes[i] & 0xFF);
      }
Tom Tromey committed
329 330 331 332
    int nwords = numBits / 32;

    while (highbits == 0 && nwords > 0)
      {
333 334
        highbits = rnd.nextInt();
        --nwords;
Tom Tromey committed
335 336 337
      }
    if (nwords == 0 && highbits >= 0)
      {
338
        ival = highbits;
Tom Tromey committed
339 340 341
      }
    else
      {
342 343 344 345 346
        ival = highbits < 0 ? nwords + 2 : nwords + 1;
        words = new int[ival];
        words[nwords] = highbits;
        while (--nwords >= 0)
          words[nwords] = rnd.nextInt();
Tom Tromey committed
347 348 349 350 351
      }
  }

  public BigInteger(int bitLength, int certainty, Random rnd)
  {
352
    this();
Tom Tromey committed
353

354
    BigInteger result = new BigInteger();
Tom Tromey committed
355 356
    while (true)
      {
357 358 359 360 361 362 363 364 365 366
        result.init(bitLength, rnd);
        result = result.setBit(bitLength - 1);
        if (result.isProbablePrime(certainty))
          break;
      }

    if (USING_NATIVE)
      mpz.fromBI(result.mpz);
    else
      {
367 368
        this.ival = result.ival;
        this.words = result.words;
Tom Tromey committed
369 370 371
      }
  }

372
  /**
Tom Tromey committed
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
   *  Return a BigInteger that is bitLength bits long with a
   *  probability < 2^-100 of being composite.
   *
   *  @param bitLength length in bits of resulting number
   *  @param rnd random number generator to use
   *  @throws ArithmeticException if bitLength < 2
   *  @since 1.4
   */
  public static BigInteger probablePrime(int bitLength, Random rnd)
  {
    if (bitLength < 2)
      throw new ArithmeticException();

    return new BigInteger(bitLength, 100, rnd);
  }

  /** Return a (possibly-shared) BigInteger with a given long value. */
  public static BigInteger valueOf(long val)
  {
392 393 394 395 396 397 398
    if (USING_NATIVE)
      {
        BigInteger result = new BigInteger();
        result.mpz.fromLong(val);
        return result;
      }

Tom Tromey committed
399 400 401 402 403 404 405 406 407 408 409 410
    if (val >= minFixNum && val <= maxFixNum)
      return smallFixNums[(int) val - minFixNum];
    int i = (int) val;
    if ((long) i == val)
      return new BigInteger(i);
    BigInteger result = alloc(2);
    result.ival = 2;
    result.words[0] = i;
    result.words[1] = (int)(val >> 32);
    return result;
  }

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
  /**
   * @return <code>true</code> if the GMP-based native implementation library
   *         was successfully loaded. Returns <code>false</code> otherwise.
   */
  private static boolean initializeLibrary()
  {
    boolean result;
    try
    {
      System.loadLibrary("javamath");
      GMP.natInitializeLibrary();
      result = true;
    }
    catch (Throwable x)
    {
      result = false;
      if (Configuration.DEBUG)
        {
          log.info("Unable to use native BigInteger: " + x);
          log.info("Will use a pure Java implementation instead");
        }
    }
    return result;
  }

Tom Tromey committed
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
  /** Make a canonicalized BigInteger from an array of words.
   * The array may be reused (without copying). */
  private static BigInteger make(int[] words, int len)
  {
    if (words == null)
      return valueOf(len);
    len = BigInteger.wordsNeeded(words, len);
    if (len <= 1)
      return len == 0 ? ZERO : valueOf(words[0]);
    BigInteger num = new BigInteger();
    num.words = words;
    num.ival = len;
    return num;
  }

  /** Convert a big-endian byte array to a little-endian array of words. */
  private static int[] byteArrayToIntArray(byte[] bytes, int sign)
  {
    // Determine number of words needed.
    int[] words = new int[bytes.length/4 + 1];
    int nwords = words.length;

    // Create a int out of modulo 4 high order bytes.
    int bptr = 0;
    int word = sign;
    for (int i = bytes.length % 4; i > 0; --i, bptr++)
      word = (word << 8) | (bytes[bptr] & 0xff);
    words[--nwords] = word;

    // Elements remaining in byte[] are a multiple of 4.
    while (nwords > 0)
      words[--nwords] = bytes[bptr++] << 24 |
468 469 470
                        (bytes[bptr++] & 0xff) << 16 |
                        (bytes[bptr++] & 0xff) << 8 |
                        (bytes[bptr++] & 0xff);
Tom Tromey committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
    return words;
  }

  /** Allocate a new non-shared BigInteger.
   * @param nwords number of words to allocate
   */
  private static BigInteger alloc(int nwords)
  {
    BigInteger result = new BigInteger();
    if (nwords > 1)
    result.words = new int[nwords];
    return result;
  }

  /** Change words.length to nwords.
   * We allow words.length to be upto nwords+2 without reallocating.
   */
  private void realloc(int nwords)
  {
    if (nwords == 0)
      {
492 493 494 495 496 497
        if (words != null)
          {
            if (ival > 0)
              ival = words[0];
            words = null;
          }
Tom Tromey committed
498 499
      }
    else if (words == null
500 501
             || words.length < nwords
             || words.length > nwords + 2)
Tom Tromey committed
502
      {
503 504 505 506 507 508 509 510 511 512 513 514 515
        int[] new_words = new int [nwords];
        if (words == null)
          {
            new_words[0] = ival;
            ival = 1;
          }
        else
          {
            if (nwords < ival)
              ival = nwords;
            System.arraycopy(words, 0, new_words, 0, ival);
          }
        words = new_words;
Tom Tromey committed
516 517 518 519 520 521 522 523 524 525
      }
  }

  private boolean isNegative()
  {
    return (words == null ? ival : words[ival - 1]) < 0;
  }

  public int signum()
  {
526 527 528
    if (USING_NATIVE)
      return mpz.compare(ZERO.mpz);

529
    if (ival == 0 && words == null)
Tom Tromey committed
530
      return 0;
531
    int top = words == null ? ival : words[ival-1];
Tom Tromey committed
532 533 534 535 536
    return top < 0 ? -1 : 1;
  }

  private static int compareTo(BigInteger x, BigInteger y)
  {
537 538 539 540 541 542
    if (USING_NATIVE)
      {
        int dummy = y.signum; // force NPE check
        return x.mpz.compare(y.mpz);
      }

Tom Tromey committed
543 544 545 546 547 548 549 550 551 552 553 554 555
    if (x.words == null && y.words == null)
      return x.ival < y.ival ? -1 : x.ival > y.ival ? 1 : 0;
    boolean x_negative = x.isNegative();
    boolean y_negative = y.isNegative();
    if (x_negative != y_negative)
      return x_negative ? -1 : 1;
    int x_len = x.words == null ? 1 : x.ival;
    int y_len = y.words == null ? 1 : y.ival;
    if (x_len != y_len)
      return (x_len > y_len) != x_negative ? 1 : -1;
    return MPN.cmp(x.words, y.words, x_len);
  }

556
  /** @since 1.2 */
Tom Tromey committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
  public int compareTo(BigInteger val)
  {
    return compareTo(this, val);
  }

  public BigInteger min(BigInteger val)
  {
    return compareTo(this, val) < 0 ? this : val;
  }

  public BigInteger max(BigInteger val)
  {
    return compareTo(this, val) > 0 ? this : val;
  }

  private boolean isZero()
  {
    return words == null && ival == 0;
  }

  private boolean isOne()
  {
    return words == null && ival == 1;
  }

  /** Calculate how many words are significant in words[0:len-1].
   * Returns the least value x such that x>0 && words[0:x-1]==words[0:len-1],
   * when words is viewed as a 2's complement integer.
   */
  private static int wordsNeeded(int[] words, int len)
  {
    int i = len;
    if (i > 0)
      {
591 592 593 594 595 596 597 598 599 600 601 602 603
        int word = words[--i];
        if (word == -1)
          {
            while (i > 0 && (word = words[i - 1]) < 0)
              {
                i--;
                if (word != -1) break;
              }
          }
        else
          {
            while (word == 0 && i > 0 && (word = words[i - 1]) >= 0)  i--;
          }
Tom Tromey committed
604 605 606 607 608 609 610
      }
    return i + 1;
  }

  private BigInteger canonicalize()
  {
    if (words != null
611
        && (ival = BigInteger.wordsNeeded(words, ival)) <= 1)
Tom Tromey committed
612
      {
613 614 615
        if (ival == 1)
          ival = words[0];
        words = null;
Tom Tromey committed
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
      }
    if (words == null && ival >= minFixNum && ival <= maxFixNum)
      return smallFixNums[ival - minFixNum];
    return this;
  }

  /** Add two ints, yielding a BigInteger. */
  private static BigInteger add(int x, int y)
  {
    return valueOf((long) x + (long) y);
  }

  /** Add a BigInteger and an int, yielding a new BigInteger. */
  private static BigInteger add(BigInteger x, int y)
  {
    if (x.words == null)
      return BigInteger.add(x.ival, y);
    BigInteger result = new BigInteger(0);
    result.setAdd(x, y);
    return result.canonicalize();
  }

  /** Set this to the sum of x and y.
   * OK if x==this. */
  private void setAdd(BigInteger x, int y)
  {
    if (x.words == null)
      {
644 645
        set((long) x.ival + (long) y);
        return;
Tom Tromey committed
646 647 648 649 650 651
      }
    int len = x.ival;
    realloc(len + 1);
    long carry = y;
    for (int i = 0;  i < len;  i++)
      {
652 653 654
        carry += ((long) x.words[i] & 0xffffffffL);
        words[i] = (int) carry;
        carry >>= 32;
Tom Tromey committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
      }
    if (x.words[len - 1] < 0)
      carry--;
    words[len] = (int) carry;
    ival = wordsNeeded(words, len + 1);
  }

  /** Destructively add an int to this. */
  private void setAdd(int y)
  {
    setAdd(this, y);
  }

  /** Destructively set the value of this to a long. */
  private void set(long y)
  {
    int i = (int) y;
    if ((long) i == y)
      {
674 675
        ival = i;
        words = null;
Tom Tromey committed
676 677 678
      }
    else
      {
679 680 681 682
        realloc(2);
        words[0] = i;
        words[1] = (int) (y >> 32);
        ival = 2;
Tom Tromey committed
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
      }
  }

  /** Destructively set the value of this to the given words.
  * The words array is reused, not copied. */
  private void set(int[] words, int length)
  {
    this.ival = length;
    this.words = words;
  }

  /** Destructively set the value of this to that of y. */
  private void set(BigInteger y)
  {
    if (y.words == null)
      set(y.ival);
    else if (this != y)
      {
701 702 703
        realloc(y.ival);
        System.arraycopy(y.words, 0, words, 0, y.ival);
        ival = y.ival;
Tom Tromey committed
704 705 706 707 708 709 710 711 712 713
      }
  }

  /** Add two BigIntegers, yielding their sum as another BigInteger. */
  private static BigInteger add(BigInteger x, BigInteger y, int k)
  {
    if (x.words == null && y.words == null)
      return valueOf((long) k * (long) y.ival + (long) x.ival);
    if (k != 1)
      {
714 715 716 717
        if (k == -1)
          y = BigInteger.neg(y);
        else
          y = BigInteger.times(y, valueOf(k));
Tom Tromey committed
718 719 720 721 722 723 724 725
      }
    if (x.words == null)
      return BigInteger.add(y, x.ival);
    if (y.words == null)
      return BigInteger.add(x, y.ival);
    // Both are big
    if (y.ival > x.ival)
      { // Swap so x is longer then y.
726
        BigInteger tmp = x;  x = y;  y = tmp;
Tom Tromey committed
727 728 729 730 731 732 733
      }
    BigInteger result = alloc(x.ival + 1);
    int i = y.ival;
    long carry = MPN.add_n(result.words, x.words, y.words, i);
    long y_ext = y.words[i - 1] < 0 ? 0xffffffffL : 0;
    for (; i < x.ival;  i++)
      {
734 735 736
        carry += ((long) x.words[i] & 0xffffffffL) + y_ext;
        result.words[i] = (int) carry;
        carry >>>= 32;
Tom Tromey committed
737 738 739 740 741 742 743 744 745 746
      }
    if (x.words[i - 1] < 0)
      y_ext--;
    result.words[i] = (int) (carry + y_ext);
    result.ival = i+1;
    return result.canonicalize();
  }

  public BigInteger add(BigInteger val)
  {
747 748 749 750 751 752 753 754
    if (USING_NATIVE)
      {
        int dummy = val.signum; // force NPE check
        BigInteger result = new BigInteger();
        mpz.add(val.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
755 756 757 758 759
    return add(this, val, 1);
  }

  public BigInteger subtract(BigInteger val)
  {
760 761 762 763 764 765 766 767
    if (USING_NATIVE)
      {
        int dummy = val.signum; // force NPE check
        BigInteger result = new BigInteger();
        mpz.subtract(val.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
    return add(this, val, -1);
  }

  private static BigInteger times(BigInteger x, int y)
  {
    if (y == 0)
      return ZERO;
    if (y == 1)
      return x;
    int[] xwords = x.words;
    int xlen = x.ival;
    if (xwords == null)
      return valueOf((long) xlen * (long) y);
    boolean negative;
    BigInteger result = BigInteger.alloc(xlen + 1);
    if (xwords[xlen - 1] < 0)
      {
785 786 787
        negative = true;
        negate(result.words, xwords, xlen);
        xwords = result.words;
Tom Tromey committed
788 789 790 791 792
      }
    else
      negative = false;
    if (y < 0)
      {
793 794
        negative = !negative;
        y = -y;
Tom Tromey committed
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
      }
    result.words[xlen] = MPN.mul_1(result.words, xwords, xlen, y);
    result.ival = xlen + 1;
    if (negative)
      result.setNegative();
    return result.canonicalize();
  }

  private static BigInteger times(BigInteger x, BigInteger y)
  {
    if (y.words == null)
      return times(x, y.ival);
    if (x.words == null)
      return times(y, x.ival);
    boolean negative = false;
    int[] xwords;
    int[] ywords;
    int xlen = x.ival;
    int ylen = y.ival;
    if (x.isNegative())
      {
816 817 818
        negative = true;
        xwords = new int[xlen];
        negate(xwords, x.words, xlen);
Tom Tromey committed
819 820 821
      }
    else
      {
822 823
        negative = false;
        xwords = x.words;
Tom Tromey committed
824 825 826
      }
    if (y.isNegative())
      {
827 828 829
        negative = !negative;
        ywords = new int[ylen];
        negate(ywords, y.words, ylen);
Tom Tromey committed
830 831 832 833 834 835
      }
    else
      ywords = y.words;
    // Swap if x is shorter then y.
    if (xlen < ylen)
      {
836 837
        int[] twords = xwords;  xwords = ywords;  ywords = twords;
        int tlen = xlen;  xlen = ylen;  ylen = tlen;
Tom Tromey committed
838 839 840 841 842 843 844 845 846 847 848
      }
    BigInteger result = BigInteger.alloc(xlen+ylen);
    MPN.mul(result.words, xwords, xlen, ywords, ylen);
    result.ival = xlen+ylen;
    if (negative)
      result.setNegative();
    return result.canonicalize();
  }

  public BigInteger multiply(BigInteger y)
  {
849 850 851 852 853 854 855 856
    if (USING_NATIVE)
      {
        int dummy = y.signum; // force NPE check
        BigInteger result = new BigInteger();
        mpz.multiply(y.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
857 858 859 860
    return times(this, y);
  }

  private static void divide(long x, long y,
861 862
                             BigInteger quotient, BigInteger remainder,
                             int rounding_mode)
Tom Tromey committed
863 864 865 866
  {
    boolean xNegative, yNegative;
    if (x < 0)
      {
867 868 869 870 871 872 873 874
        xNegative = true;
        if (x == Long.MIN_VALUE)
          {
            divide(valueOf(x), valueOf(y),
                   quotient, remainder, rounding_mode);
            return;
          }
        x = -x;
Tom Tromey committed
875 876 877 878 879 880
      }
    else
      xNegative = false;

    if (y < 0)
      {
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
        yNegative = true;
        if (y == Long.MIN_VALUE)
          {
            if (rounding_mode == TRUNCATE)
              { // x != Long.Min_VALUE implies abs(x) < abs(y)
                if (quotient != null)
                  quotient.set(0);
                if (remainder != null)
                  remainder.set(x);
              }
            else
              divide(valueOf(x), valueOf(y),
                      quotient, remainder, rounding_mode);
            return;
          }
        y = -y;
Tom Tromey committed
897 898 899 900 901 902 903 904 905 906 907
      }
    else
      yNegative = false;

    long q = x / y;
    long r = x % y;
    boolean qNegative = xNegative ^ yNegative;

    boolean add_one = false;
    if (r != 0)
      {
908 909 910 911 912 913 914 915 916 917 918 919 920
        switch (rounding_mode)
          {
          case TRUNCATE:
            break;
          case CEILING:
          case FLOOR:
            if (qNegative == (rounding_mode == FLOOR))
              add_one = true;
            break;
          case ROUND:
            add_one = r > ((y - (q & 1)) >> 1);
            break;
          }
Tom Tromey committed
921 922 923
      }
    if (quotient != null)
      {
924 925 926 927 928
        if (add_one)
          q++;
        if (qNegative)
          q = -q;
        quotient.set(q);
Tom Tromey committed
929 930 931
      }
    if (remainder != null)
      {
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
        // The remainder is by definition: X-Q*Y
        if (add_one)
          {
            // Subtract the remainder from Y.
            r = y - r;
            // In this case, abs(Q*Y) > abs(X).
            // So sign(remainder) = -sign(X).
            xNegative = ! xNegative;
          }
        else
          {
            // If !add_one, then: abs(Q*Y) <= abs(X).
            // So sign(remainder) = sign(X).
          }
        if (xNegative)
          r = -r;
        remainder.set(r);
Tom Tromey committed
949 950 951 952 953 954 955 956 957 958 959 960
      }
  }

  /** Divide two integers, yielding quotient and remainder.
   * @param x the numerator in the division
   * @param y the denominator in the division
   * @param quotient is set to the quotient of the result (iff quotient!=null)
   * @param remainder is set to the remainder of the result
   *  (iff remainder!=null)
   * @param rounding_mode one of FLOOR, CEILING, TRUNCATE, or ROUND.
   */
  private static void divide(BigInteger x, BigInteger y,
961 962
                             BigInteger quotient, BigInteger remainder,
                             int rounding_mode)
Tom Tromey committed
963 964
  {
    if ((x.words == null || x.ival <= 2)
965
        && (y.words == null || y.ival <= 2))
Tom Tromey committed
966
      {
967 968 969 970 971 972 973
        long x_l = x.longValue();
        long y_l = y.longValue();
        if (x_l != Long.MIN_VALUE && y_l != Long.MIN_VALUE)
          {
            divide(x_l, y_l, quotient, remainder, rounding_mode);
            return;
          }
Tom Tromey committed
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
      }

    boolean xNegative = x.isNegative();
    boolean yNegative = y.isNegative();
    boolean qNegative = xNegative ^ yNegative;

    int ylen = y.words == null ? 1 : y.ival;
    int[] ywords = new int[ylen];
    y.getAbsolute(ywords);
    while (ylen > 1 && ywords[ylen - 1] == 0)  ylen--;

    int xlen = x.words == null ? 1 : x.ival;
    int[] xwords = new int[xlen+2];
    x.getAbsolute(xwords);
    while (xlen > 1 && xwords[xlen-1] == 0)  xlen--;

    int qlen, rlen;

    int cmpval = MPN.cmp(xwords, xlen, ywords, ylen);
    if (cmpval < 0)  // abs(x) < abs(y)
      { // quotient = 0;  remainder = num.
995 996
        int[] rwords = xwords;  xwords = ywords;  ywords = rwords;
        rlen = xlen;  qlen = 1;  xwords[0] = 0;
Tom Tromey committed
997 998 999
      }
    else if (cmpval == 0)  // abs(x) == abs(y)
      {
1000 1001
        xwords[0] = 1;  qlen = 1;  // quotient = 1
        ywords[0] = 0;  rlen = 1;  // remainder = 0;
Tom Tromey committed
1002 1003 1004
      }
    else if (ylen == 1)
      {
1005 1006 1007 1008 1009 1010 1011 1012 1013
        qlen = xlen;
        // Need to leave room for a word of leading zeros if dividing by 1
        // and the dividend has the high bit set.  It might be safe to
        // increment qlen in all cases, but it certainly is only necessary
        // in the following case.
        if (ywords[0] == 1 && xwords[xlen-1] < 0)
          qlen++;
        rlen = 1;
        ywords[0] = MPN.divmod_1(xwords, xwords, xlen, ywords[0]);
Tom Tromey committed
1014 1015 1016
      }
    else  // abs(x) > abs(y)
      {
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
        // Normalize the denominator, i.e. make its most significant bit set by
        // shifting it normalization_steps bits to the left.  Also shift the
        // numerator the same number of steps (to keep the quotient the same!).

        int nshift = MPN.count_leading_zeros(ywords[ylen - 1]);
        if (nshift != 0)
          {
            // Shift up the denominator setting the most significant bit of
            // the most significant word.
            MPN.lshift(ywords, 0, ywords, ylen, nshift);

            // Shift up the numerator, possibly introducing a new most
            // significant word.
            int x_high = MPN.lshift(xwords, 0, xwords, xlen, nshift);
            xwords[xlen++] = x_high;
          }

        if (xlen == ylen)
          xwords[xlen++] = 0;
        MPN.divide(xwords, xlen, ywords, ylen);
        rlen = ylen;
        MPN.rshift0 (ywords, xwords, 0, rlen, nshift);

        qlen = xlen + 1 - ylen;
        if (quotient != null)
          {
            for (int i = 0;  i < qlen;  i++)
              xwords[i] = xwords[i+ylen];
          }
Tom Tromey committed
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
      }

    if (ywords[rlen-1] < 0)
      {
        ywords[rlen] = 0;
        rlen++;
      }

    // Now the quotient is in xwords, and the remainder is in ywords.

    boolean add_one = false;
    if (rlen > 1 || ywords[0] != 0)
      { // Non-zero remainder i.e. in-exact quotient.
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
        switch (rounding_mode)
          {
          case TRUNCATE:
            break;
          case CEILING:
          case FLOOR:
            if (qNegative == (rounding_mode == FLOOR))
              add_one = true;
            break;
          case ROUND:
            // int cmp = compareTo(remainder<<1, abs(y));
            BigInteger tmp = remainder == null ? new BigInteger() : remainder;
            tmp.set(ywords, rlen);
            tmp = shift(tmp, 1);
            if (yNegative)
              tmp.setNegative();
            int cmp = compareTo(tmp, y);
            // Now cmp == compareTo(sign(y)*(remainder<<1), y)
            if (yNegative)
              cmp = -cmp;
            add_one = (cmp == 1) || (cmp == 0 && (xwords[0]&1) != 0);
          }
Tom Tromey committed
1081 1082 1083
      }
    if (quotient != null)
      {
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        quotient.set(xwords, qlen);
        if (qNegative)
          {
            if (add_one)  // -(quotient + 1) == ~(quotient)
              quotient.setInvert();
            else
              quotient.setNegative();
          }
        else if (add_one)
          quotient.setAdd(1);
Tom Tromey committed
1094 1095 1096
      }
    if (remainder != null)
      {
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
        // The remainder is by definition: X-Q*Y
        remainder.set(ywords, rlen);
        if (add_one)
          {
            // Subtract the remainder from Y:
            // abs(R) = abs(Y) - abs(orig_rem) = -(abs(orig_rem) - abs(Y)).
            BigInteger tmp;
            if (y.words == null)
              {
                tmp = remainder;
                tmp.set(yNegative ? ywords[0] + y.ival : ywords[0] - y.ival);
              }
            else
              tmp = BigInteger.add(remainder, y, yNegative ? 1 : -1);
            // Now tmp <= 0.
            // In this case, abs(Q) = 1 + floor(abs(X)/abs(Y)).
            // Hence, abs(Q*Y) > abs(X).
            // So sign(remainder) = -sign(X).
            if (xNegative)
              remainder.setNegative(tmp);
            else
              remainder.set(tmp);
          }
        else
          {
            // If !add_one, then: abs(Q*Y) <= abs(X).
            // So sign(remainder) = sign(X).
            if (xNegative)
              remainder.setNegative();
          }
Tom Tromey committed
1127 1128 1129 1130 1131
      }
  }

  public BigInteger divide(BigInteger val)
  {
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
    if (USING_NATIVE)
      {
        if (val.compareTo(ZERO) == 0)
          throw new ArithmeticException("divisor is zero");

        BigInteger result = new BigInteger();
        mpz.quotient(val.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
    if (val.isZero())
      throw new ArithmeticException("divisor is zero");

    BigInteger quot = new BigInteger();
    divide(this, val, quot, null, TRUNCATE);
    return quot.canonicalize();
  }

  public BigInteger remainder(BigInteger val)
  {
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    if (USING_NATIVE)
      {
        if (val.compareTo(ZERO) == 0)
          throw new ArithmeticException("divisor is zero");

        BigInteger result = new BigInteger();
        mpz.remainder(val.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
    if (val.isZero())
      throw new ArithmeticException("divisor is zero");

    BigInteger rem = new BigInteger();
    divide(this, val, null, rem, TRUNCATE);
    return rem.canonicalize();
  }

  public BigInteger[] divideAndRemainder(BigInteger val)
  {
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    if (USING_NATIVE)
      {
        if (val.compareTo(ZERO) == 0)
          throw new ArithmeticException("divisor is zero");

        BigInteger q = new BigInteger();
        BigInteger r = new BigInteger();
        mpz.quotientAndRemainder(val.mpz, q.mpz, r.mpz);
        return new BigInteger[] { q, r };
      }

Tom Tromey committed
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    if (val.isZero())
      throw new ArithmeticException("divisor is zero");

    BigInteger[] result = new BigInteger[2];
    result[0] = new BigInteger();
    result[1] = new BigInteger();
    divide(this, val, result[0], result[1], TRUNCATE);
    result[0].canonicalize();
    result[1].canonicalize();
    return result;
  }

  public BigInteger mod(BigInteger m)
  {
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    if (USING_NATIVE)
      {
        int dummy = m.signum; // force NPE check
        if (m.compareTo(ZERO) < 1)
          throw new ArithmeticException("non-positive modulus");

        BigInteger result = new BigInteger();
        mpz.modulo(m.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    if (m.isNegative() || m.isZero())
      throw new ArithmeticException("non-positive modulus");

    BigInteger rem = new BigInteger();
    divide(this, m, null, rem, FLOOR);
    return rem.canonicalize();
  }

  /** Calculate the integral power of a BigInteger.
   * @param exponent the exponent (must be non-negative)
   */
  public BigInteger pow(int exponent)
  {
    if (exponent <= 0)
      {
1223 1224 1225
        if (exponent == 0)
          return ONE;
          throw new ArithmeticException("negative exponent");
Tom Tromey committed
1226
      }
1227 1228 1229 1230 1231 1232 1233 1234

    if (USING_NATIVE)
      {
        BigInteger result = new BigInteger();
        mpz.pow(exponent, result.mpz);
        return result;
      }

Tom Tromey committed
1235 1236 1237 1238 1239 1240 1241 1242
    if (isZero())
      return this;
    int plen = words == null ? 1 : ival;  // Length of pow2.
    int blen = ((bitLength() * exponent) >> 5) + 2 * plen;
    boolean negative = isNegative() && (exponent & 1) != 0;
    int[] pow2 = new int [blen];
    int[] rwords = new int [blen];
    int[] work = new int [blen];
1243
    getAbsolute(pow2);  // pow2 = abs(this);
Tom Tromey committed
1244 1245 1246 1247
    int rlen = 1;
    rwords[0] = 1; // rwords = 1;
    for (;;)  // for (i = 0;  ; i++)
      {
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
        // pow2 == this**(2**i)
        // prod = this**(sum(j=0..i-1, (exponent>>j)&1))
        if ((exponent & 1) != 0)
          { // r *= pow2
            MPN.mul(work, pow2, plen, rwords, rlen);
            int[] temp = work;  work = rwords;  rwords = temp;
            rlen += plen;
            while (rwords[rlen - 1] == 0)  rlen--;
          }
        exponent >>= 1;
        if (exponent == 0)
          break;
        // pow2 *= pow2;
        MPN.mul(work, pow2, plen, pow2, plen);
        int[] temp = work;  work = pow2;  pow2 = temp;  // swap to avoid a copy
        plen *= 2;
        while (pow2[plen - 1] == 0)  plen--;
Tom Tromey committed
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
      }
    if (rwords[rlen - 1] < 0)
      rlen++;
    if (negative)
      negate(rwords, rwords, rlen);
    return BigInteger.make(rwords, rlen);
  }

  private static int[] euclidInv(int a, int b, int prevDiv)
  {
    if (b == 0)
      throw new ArithmeticException("not invertible");

    if (b == 1)
1279 1280 1281
        // Success:  values are indeed invertible!
        // Bottom of the recursion reached; start unwinding.
        return new int[] { -prevDiv, 1 };
Tom Tromey committed
1282

1283
    int[] xy = euclidInv(b, a % b, a / b);      // Recursion happens here.
Tom Tromey committed
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    a = xy[0]; // use our local copy of 'a' as a work var
    xy[0] = a * -prevDiv + xy[1];
    xy[1] = a;
    return xy;
  }

  private static void euclidInv(BigInteger a, BigInteger b,
                                BigInteger prevDiv, BigInteger[] xy)
  {
    if (b.isZero())
      throw new ArithmeticException("not invertible");

    if (b.isOne())
      {
1298 1299 1300
        // Success:  values are indeed invertible!
        // Bottom of the recursion reached; start unwinding.
        xy[0] = neg(prevDiv);
Tom Tromey committed
1301
        xy[1] = ONE;
1302
        return;
Tom Tromey committed
1303 1304 1305 1306 1307 1308 1309 1310
      }

    // Recursion happens in the following conditional!

    // If a just contains an int, then use integer math for the rest.
    if (a.words == null)
      {
        int[] xyInt = euclidInv(b.ival, a.ival % b.ival, a.ival / b.ival);
1311
        xy[0] = new BigInteger(xyInt[0]);
Tom Tromey committed
1312 1313 1314 1315
        xy[1] = new BigInteger(xyInt[1]);
      }
    else
      {
1316 1317 1318
        BigInteger rem = new BigInteger();
        BigInteger quot = new BigInteger();
        divide(a, b, quot, rem, FLOOR);
Tom Tromey committed
1319 1320 1321
        // quot and rem may not be in canonical form. ensure
        rem.canonicalize();
        quot.canonicalize();
1322
        euclidInv(b, rem, quot, xy);
Tom Tromey committed
1323 1324 1325 1326 1327 1328 1329 1330 1331
      }

    BigInteger t = xy[0];
    xy[0] = add(xy[1], times(t, prevDiv), -1);
    xy[1] = t;
  }

  public BigInteger modInverse(BigInteger y)
  {
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    if (USING_NATIVE)
      {
        int dummy = y.signum; // force NPE check
        if (mpz.compare(ZERO.mpz) < 1)
          throw new ArithmeticException("non-positive modulo");

        BigInteger result = new BigInteger();
        mpz.modInverse(y.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    if (y.isNegative() || y.isZero())
      throw new ArithmeticException("non-positive modulo");

    // Degenerate cases.
    if (y.isOne())
      return ZERO;
    if (isOne())
      return ONE;

    // Use Euclid's algorithm as in gcd() but do this recursively
    // rather than in a loop so we can use the intermediate results as we
    // unwind from the recursion.
    // Used http://www.math.nmsu.edu/~crypto/EuclideanAlgo.html as reference.
    BigInteger result = new BigInteger();
    boolean swapped = false;

    if (y.words == null)
      {
1361 1362 1363 1364 1365 1366
        // The result is guaranteed to be less than the modulus, y (which is
        // an int), so simplify this by working with the int result of this
        // modulo y.  Also, if this is negative, make it positive via modulo
        // math.  Note that BigInteger.mod() must be used even if this is
        // already an int as the % operator would provide a negative result if
        // this is negative, BigInteger.mod() never returns negative values.
Tom Tromey committed
1367 1368 1369
        int xval = (words != null || isNegative()) ? mod(y).ival : ival;
        int yval = y.ival;

1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
        // Swap values so x > y.
        if (yval > xval)
          {
            int tmp = xval; xval = yval; yval = tmp;
            swapped = true;
          }
        // Normally, the result is in the 2nd element of the array, but
        // if originally x < y, then x and y were swapped and the result
        // is in the 1st element of the array.
        result.ival =
          euclidInv(yval, xval % yval, xval / yval)[swapped ? 0 : 1];

        // Result can't be negative, so make it positive by adding the
        // original modulus, y.ival (not the possibly "swapped" yval).
        if (result.ival < 0)
          result.ival += y.ival;
Tom Tromey committed
1386 1387 1388
      }
    else
      {
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
        // As above, force this to be a positive value via modulo math.
        BigInteger x = isNegative() ? this.mod(y) : this;

        // Swap values so x > y.
        if (x.compareTo(y) < 0)
          {
            result = x; x = y; y = result; // use 'result' as a work var
            swapped = true;
          }
        // As above (for ints), result will be in the 2nd element unless
        // the original x and y were swapped.
        BigInteger rem = new BigInteger();
        BigInteger quot = new BigInteger();
        divide(x, y, quot, rem, FLOOR);
Tom Tromey committed
1403 1404 1405
        // quot and rem may not be in canonical form. ensure
        rem.canonicalize();
        quot.canonicalize();
1406 1407 1408
        BigInteger[] xy = new BigInteger[2];
        euclidInv(y, rem, quot, xy);
        result = swapped ? xy[0] : xy[1];
Tom Tromey committed
1409

1410 1411 1412 1413
        // Result can't be negative, so make it positive by adding the
        // original modulus, y (which is now x if they were swapped).
        if (result.isNegative())
          result = add(result, swapped ? x : y, 1);
Tom Tromey committed
1414
      }
1415

Tom Tromey committed
1416 1417 1418 1419 1420
    return result;
  }

  public BigInteger modPow(BigInteger exponent, BigInteger m)
  {
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
    if (USING_NATIVE)
      {
        int dummy = exponent.signum; // force NPE check
        if (m.mpz.compare(ZERO.mpz) < 1)
          throw new ArithmeticException("non-positive modulo");

        BigInteger result = new BigInteger();
        mpz.modPow(exponent.mpz, m.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
1432 1433 1434 1435
    if (m.isNegative() || m.isZero())
      throw new ArithmeticException("non-positive modulo");

    if (exponent.isNegative())
1436
      return modInverse(m).modPow(exponent.negate(), m);
Tom Tromey committed
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
    if (exponent.isOne())
      return mod(m);

    // To do this naively by first raising this to the power of exponent
    // and then performing modulo m would be extremely expensive, especially
    // for very large numbers.  The solution is found in Number Theory
    // where a combination of partial powers and moduli can be done easily.
    //
    // We'll use the algorithm for Additive Chaining which can be found on
    // p. 244 of "Applied Cryptography, Second Edition" by Bruce Schneier.
    BigInteger s = ONE;
    BigInteger t = this;
    BigInteger u = exponent;

    while (!u.isZero())
      {
1453 1454 1455 1456
        if (u.and(ONE).isOne())
          s = times(s, t).mod(m);
        u = u.shiftRight(1);
        t = times(t, t).mod(m);
Tom Tromey committed
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
      }

    return s;
  }

  /** Calculate Greatest Common Divisor for non-negative ints. */
  private static int gcd(int a, int b)
  {
    // Euclid's algorithm, copied from libg++.
    int tmp;
    if (b > a)
      {
1469
        tmp = a; a = b; b = tmp;
Tom Tromey committed
1470 1471 1472
      }
    for(;;)
      {
1473 1474
        if (b == 0)
          return a;
Tom Tromey committed
1475
        if (b == 1)
1476
          return b;
Tom Tromey committed
1477
        tmp = b;
1478 1479 1480
            b = a % b;
            a = tmp;
          }
Tom Tromey committed
1481 1482 1483 1484
      }

  public BigInteger gcd(BigInteger y)
  {
1485 1486 1487 1488 1489 1490 1491 1492
    if (USING_NATIVE)
      {
        int dummy = y.signum; // force NPE check
        BigInteger result = new BigInteger();
        mpz.gcd(y.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
1493 1494 1495 1496
    int xval = ival;
    int yval = y.ival;
    if (words == null)
      {
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
        if (xval == 0)
          return abs(y);
        if (y.words == null
            && xval != Integer.MIN_VALUE && yval != Integer.MIN_VALUE)
          {
            if (xval < 0)
              xval = -xval;
            if (yval < 0)
              yval = -yval;
            return valueOf(gcd(xval, yval));
          }
        xval = 1;
Tom Tromey committed
1509 1510 1511
      }
    if (y.words == null)
      {
1512 1513 1514
        if (yval == 0)
          return abs(this);
        yval = 1;
Tom Tromey committed
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
      }
    int len = (xval > yval ? xval : yval) + 1;
    int[] xwords = new int[len];
    int[] ywords = new int[len];
    getAbsolute(xwords);
    y.getAbsolute(ywords);
    len = MPN.gcd(xwords, ywords, len);
    BigInteger result = new BigInteger(0);
    result.ival = len;
    result.words = xwords;
    return result.canonicalize();
  }

  /**
   * <p>Returns <code>true</code> if this BigInteger is probably prime,
   * <code>false</code> if it's definitely composite. If <code>certainty</code>
   * is <code><= 0</code>, <code>true</code> is returned.</p>
   *
   * @param certainty a measure of the uncertainty that the caller is willing
   * to tolerate: if the call returns <code>true</code> the probability that
   * this BigInteger is prime exceeds <code>(1 - 1/2<sup>certainty</sup>)</code>.
   * The execution time of this method is proportional to the value of this
   * parameter.
   * @return <code>true</code> if this BigInteger is probably prime,
   * <code>false</code> if it's definitely composite.
   */
  public boolean isProbablePrime(int certainty)
  {
    if (certainty < 1)
      return true;

1546 1547 1548
    if (USING_NATIVE)
      return mpz.testPrimality(certainty) != 0;

Tom Tromey committed
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
    /** We'll use the Rabin-Miller algorithm for doing a probabilistic
     * primality test.  It is fast, easy and has faster decreasing odds of a
     * composite passing than with other tests.  This means that this
     * method will actually have a probability much greater than the
     * 1 - .5^certainty specified in the JCL (p. 117), but I don't think
     * anyone will complain about better performance with greater certainty.
     *
     * The Rabin-Miller algorithm can be found on pp. 259-261 of "Applied
     * Cryptography, Second Edition" by Bruce Schneier.
     */

    // First rule out small prime factors
    BigInteger rem = new BigInteger();
    int i;
    for (i = 0; i < primes.length; i++)
      {
1565 1566
        if (words == null && ival == primes[i])
          return true;
Tom Tromey committed
1567 1568 1569

        divide(this, smallFixNums[primes[i] - minFixNum], null, rem, TRUNCATE);
        if (rem.canonicalize().isZero())
1570
          return false;
Tom Tromey committed
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
      }

    // Now perform the Rabin-Miller test.

    // Set b to the number of times 2 evenly divides (this - 1).
    // I.e. 2^b is the largest power of 2 that divides (this - 1).
    BigInteger pMinus1 = add(this, -1);
    int b = pMinus1.getLowestSetBit();

    // Set m such that this = 1 + 2^b * m.
1581
    BigInteger m = pMinus1.divide(valueOf(2L).pow(b));
Tom Tromey committed
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601

    // The HAC (Handbook of Applied Cryptography), Alfred Menezes & al. Note
    // 4.49 (controlling the error probability) gives the number of trials
    // for an error probability of 1/2**80, given the number of bits in the
    // number to test.  we shall use these numbers as is if/when 'certainty'
    // is less or equal to 80, and twice as much if it's greater.
    int bits = this.bitLength();
    for (i = 0; i < k.length; i++)
      if (bits <= k[i])
        break;
    int trials = t[i];
    if (certainty > 80)
      trials *= 2;
    BigInteger z;
    for (int t = 0; t < trials; t++)
      {
        // The HAC (Handbook of Applied Cryptography), Alfred Menezes & al.
        // Remark 4.28 states: "...A strategy that is sometimes employed
        // is to fix the bases a to be the first few primes instead of
        // choosing them at random.
1602 1603 1604
        z = smallFixNums[primes[t] - minFixNum].modPow(m, this);
        if (z.isOne() || z.equals(pMinus1))
          continue;                     // Passes the test; may be prime.
Tom Tromey committed
1605

1606 1607 1608 1609 1610 1611 1612
        for (i = 0; i < b; )
          {
            if (z.isOne())
              return false;
            i++;
            if (z.equals(pMinus1))
              break;                    // Passes the test; may be prime.
Tom Tromey committed
1613

1614 1615
            z = z.modPow(valueOf(2), this);
          }
Tom Tromey committed
1616

1617 1618
        if (i == b && !z.equals(pMinus1))
          return false;
Tom Tromey committed
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
      }
    return true;
  }

  private void setInvert()
  {
    if (words == null)
      ival = ~ival;
    else
      {
1629 1630
        for (int i = ival;  --i >= 0; )
          words[i] = ~words[i];
Tom Tromey committed
1631 1632 1633 1634 1635 1636 1637 1638 1639
      }
  }

  private void setShiftLeft(BigInteger x, int count)
  {
    int[] xwords;
    int xlen;
    if (x.words == null)
      {
1640 1641 1642 1643 1644 1645 1646 1647
        if (count < 32)
          {
            set((long) x.ival << count);
            return;
          }
        xwords = new int[1];
        xwords[0] = x.ival;
        xlen = 1;
Tom Tromey committed
1648 1649 1650
      }
    else
      {
1651 1652
        xwords = x.words;
        xlen = x.ival;
Tom Tromey committed
1653 1654 1655 1656 1657 1658
      }
    int word_count = count >> 5;
    count &= 31;
    int new_len = xlen + word_count;
    if (count == 0)
      {
1659 1660 1661
        realloc(new_len);
        for (int i = xlen;  --i >= 0; )
          words[i+word_count] = xwords[i];
Tom Tromey committed
1662 1663 1664
      }
    else
      {
1665 1666 1667 1668 1669
        new_len++;
        realloc(new_len);
        int shift_out = MPN.lshift(words, word_count, xwords, xlen, count);
        count = 32 - count;
        words[new_len-1] = (shift_out << count) >> count;  // sign-extend.
Tom Tromey committed
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
      }
    ival = new_len;
    for (int i = word_count;  --i >= 0; )
      words[i] = 0;
  }

  private void setShiftRight(BigInteger x, int count)
  {
    if (x.words == null)
      set(count < 32 ? x.ival >> count : x.ival < 0 ? -1 : 0);
    else if (count == 0)
      set(x);
    else
      {
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
        boolean neg = x.isNegative();
        int word_count = count >> 5;
        count &= 31;
        int d_len = x.ival - word_count;
        if (d_len <= 0)
          set(neg ? -1 : 0);
        else
          {
            if (words == null || words.length < d_len)
              realloc(d_len);
            MPN.rshift0 (words, x.words, word_count, d_len, count);
            ival = d_len;
            if (neg)
              words[d_len-1] |= -2 << (31 - count);
          }
Tom Tromey committed
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
      }
  }

  private void setShift(BigInteger x, int count)
  {
    if (count > 0)
      setShiftLeft(x, count);
    else
      setShiftRight(x, -count);
  }

  private static BigInteger shift(BigInteger x, int count)
  {
    if (x.words == null)
      {
1714 1715 1716 1717
        if (count <= 0)
          return valueOf(count > -32 ? x.ival >> (-count) : x.ival < 0 ? -1 : 0);
        if (count < 32)
          return valueOf((long) x.ival << count);
Tom Tromey committed
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
      }
    if (count == 0)
      return x;
    BigInteger result = new BigInteger(0);
    result.setShift(x, count);
    return result.canonicalize();
  }

  public BigInteger shiftLeft(int n)
  {
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
    if (n == 0)
      return this;

    if (USING_NATIVE)
      {
        BigInteger result = new BigInteger();
        if (n < 0)
          mpz.shiftRight(-n, result.mpz);
        else
          mpz.shiftLeft(n, result.mpz);
        return result;
      }

Tom Tromey committed
1741 1742 1743 1744 1745
    return shift(this, n);
  }

  public BigInteger shiftRight(int n)
  {
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
    if (n == 0)
      return this;

    if (USING_NATIVE)
      {
        BigInteger result = new BigInteger();
        if (n < 0)
          mpz.shiftLeft(-n, result.mpz);
        else
          mpz.shiftRight(n, result.mpz);
        return result;
      }

Tom Tromey committed
1759 1760 1761
    return shift(this, -n);
  }

1762
  private void format(int radix, CPStringBuilder buffer)
Tom Tromey committed
1763 1764 1765 1766 1767 1768 1769
  {
    if (words == null)
      buffer.append(Integer.toString(ival, radix));
    else if (ival <= 2)
      buffer.append(Long.toString(longValue(), radix));
    else
      {
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
        boolean neg = isNegative();
        int[] work;
        if (neg || radix != 16)
          {
            work = new int[ival];
            getAbsolute(work);
          }
        else
          work = words;
        int len = ival;

        if (radix == 16)
          {
            if (neg)
              buffer.append('-');
            int buf_start = buffer.length();
            for (int i = len;  --i >= 0; )
              {
                int word = work[i];
                for (int j = 8;  --j >= 0; )
                  {
                    int hex_digit = (word >> (4 * j)) & 0xF;
                    // Suppress leading zeros:
                    if (hex_digit > 0 || buffer.length() > buf_start)
                      buffer.append(Character.forDigit(hex_digit, 16));
                  }
              }
          }
        else
          {
            int i = buffer.length();
            for (;;)
              {
                int digit = MPN.divmod_1(work, work, len, radix);
                buffer.append(Character.forDigit(digit, radix));
                while (len > 0 && work[len-1] == 0) len--;
                if (len == 0)
                  break;
              }
            if (neg)
              buffer.append('-');
            /* Reverse buffer. */
            int j = buffer.length() - 1;
            while (i < j)
              {
                char tmp = buffer.charAt(i);
                buffer.setCharAt(i, buffer.charAt(j));
                buffer.setCharAt(j, tmp);
                i++;  j--;
              }
          }
Tom Tromey committed
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
      }
  }

  public String toString()
  {
    return toString(10);
  }

  public String toString(int radix)
  {
1831 1832 1833
    if (USING_NATIVE)
      return mpz.toString(radix);

Tom Tromey committed
1834 1835 1836 1837 1838
    if (words == null)
      return Integer.toString(ival, radix);
    if (ival <= 2)
      return Long.toString(longValue(), radix);
    int buf_size = ival * (MPN.chars_per_word(radix) + 1);
1839
    CPStringBuilder buffer = new CPStringBuilder(buf_size);
Tom Tromey committed
1840 1841 1842 1843 1844 1845
    format(radix, buffer);
    return buffer.toString();
  }

  public int intValue()
  {
1846 1847 1848 1849 1850 1851
    if (USING_NATIVE)
      {
        int result = mpz.absIntValue();
        return mpz.compare(ZERO.mpz) < 0 ? - result : result;
      }

Tom Tromey committed
1852 1853 1854 1855 1856 1857 1858
    if (words == null)
      return ival;
    return words[0];
  }

  public long longValue()
  {
1859 1860 1861 1862 1863 1864 1865 1866 1867
    if (USING_NATIVE)
      {
        long result;
        result = (abs().shiftRight(32)).mpz.absIntValue();
        result <<= 32;
        result |= mpz.absIntValue() & 0xFFFFFFFFL;
        return this.compareTo(ZERO) < 0 ? - result : result;
      }

Tom Tromey committed
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
    if (words == null)
      return ival;
    if (ival == 1)
      return words[0];
    return ((long)words[1] << 32) + ((long)words[0] & 0xffffffffL);
  }

  public int hashCode()
  {
    // FIXME: May not match hashcode of JDK.
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
    if (USING_NATIVE)
      {
        // TODO: profile to decide whether to make it native
        byte[] bytes = this.toByteArray();
        int result = 0;
        for (int i = 0; i < bytes.length; i++)
          result ^= (bytes[i] & 0xFF) << (8 * (i % 4));
        return result;
      }

Tom Tromey committed
1888 1889 1890 1891 1892 1893
    return words == null ? ival : (words[0] + words[ival - 1]);
  }

  /* Assumes x and y are both canonicalized. */
  private static boolean equals(BigInteger x, BigInteger y)
  {
1894 1895 1896
    if (USING_NATIVE)
      return x.mpz.compare(y.mpz) == 0;

Tom Tromey committed
1897 1898 1899 1900 1901 1902
    if (x.words == null && y.words == null)
      return x.ival == y.ival;
    if (x.words == null || y.words == null || x.ival != y.ival)
      return false;
    for (int i = x.ival; --i >= 0; )
      {
1903 1904
        if (x.words[i] != y.words[i])
          return false;
Tom Tromey committed
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
      }
    return true;
  }

  /* Assumes this and obj are both canonicalized. */
  public boolean equals(Object obj)
  {
    if (! (obj instanceof BigInteger))
      return false;
    return equals(this, (BigInteger) obj);
  }

  private static BigInteger valueOf(byte[] digits, int byte_len,
1918
                                    boolean negative, int radix)
Tom Tromey committed
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
  {
    int chars_per_word = MPN.chars_per_word(radix);
    int[] words = new int[byte_len / chars_per_word + 1];
    int size = MPN.set_str(words, digits, byte_len, radix);
    if (size == 0)
      return ZERO;
    if (words[size-1] < 0)
      words[size++] = 0;
    if (negative)
      negate(words, words, size);
    return make(words, size);
  }

  public double doubleValue()
  {
1934 1935 1936
    if (USING_NATIVE)
      return mpz.doubleValue();

Tom Tromey committed
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
    if (words == null)
      return (double) ival;
    if (ival <= 2)
      return (double) longValue();
    if (isNegative())
      return neg(this).roundToDouble(0, true, false);
      return roundToDouble(0, false, false);
  }

  public float floatValue()
  {
    return (float) doubleValue();
  }

  /** Return true if any of the lowest n bits are one.
   * (false if n is negative).  */
  private boolean checkBits(int n)
  {
    if (n <= 0)
      return false;
    if (words == null)
      return n > 31 || ((ival & ((1 << n) - 1)) != 0);
    int i;
    for (i = 0; i < (n >> 5) ; i++)
      if (words[i] != 0)
1962
        return true;
Tom Tromey committed
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
    return (n & 31) != 0 && (words[i] & ((1 << (n & 31)) - 1)) != 0;
  }

  /** Convert a semi-processed BigInteger to double.
   * Number must be non-negative.  Multiplies by a power of two, applies sign,
   * and converts to double, with the usual java rounding.
   * @param exp power of two, positive or negative, by which to multiply
   * @param neg true if negative
   * @param remainder true if the BigInteger is the result of a truncating
   * division that had non-zero remainder.  To ensure proper rounding in
   * this case, the BigInteger must have at least 54 bits.  */
  private double roundToDouble(int exp, boolean neg, boolean remainder)
  {
    // Compute length.
    int il = bitLength();

    // Exponent when normalized to have decimal point directly after
    // leading one.  This is stored excess 1023 in the exponent bit field.
    exp += il - 1;

    // Gross underflow.  If exp == -1075, we let the rounding
    // computation determine whether it is minval or 0 (which are just
    // 0x0000 0000 0000 0001 and 0x0000 0000 0000 0000 as bit
    // patterns).
    if (exp < -1075)
      return neg ? -0.0 : 0.0;

    // gross overflow
    if (exp > 1023)
      return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;

    // number of bits in mantissa, including the leading one.
    // 53 unless it's denormalized
    int ml = (exp >= -1022 ? 53 : 53 + exp + 1022);

    // Get top ml + 1 bits.  The extra one is for rounding.
    long m;
    int excess_bits = il - (ml + 1);
    if (excess_bits > 0)
      m = ((words == null) ? ival >> excess_bits
2003
           : MPN.rshift_long(words, ival, excess_bits));
Tom Tromey committed
2004 2005 2006 2007 2008 2009 2010
    else
      m = longValue() << (- excess_bits);

    // Special rounding for maxval.  If the number exceeds maxval by
    // any amount, even if it's less than half a step, it overflows.
    if (exp == 1023 && ((m >> 1) == (1L << 53) - 1))
      {
2011 2012 2013 2014
        if (remainder || checkBits(il - ml))
          return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
        else
          return neg ? - Double.MAX_VALUE : Double.MAX_VALUE;
Tom Tromey committed
2015 2016 2017 2018 2019
      }

    // Normal round-to-even rule: round up if the bit dropped is a one, and
    // the bit above it or any of the bits below it is a one.
    if ((m & 1) == 1
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
        && ((m & 2) == 2 || remainder || checkBits(excess_bits)))
      {
        m += 2;
        // Check if we overflowed the mantissa
        if ((m & (1L << 54)) != 0)
          {
            exp++;
            // renormalize
            m >>= 1;
          }
        // Check if a denormalized mantissa was just rounded up to a
        // normalized one.
        else if (ml == 52 && (m & (1L << 53)) != 0)
          exp++;
      }

Tom Tromey committed
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
    // Discard the rounding bit
    m >>= 1;

    long bits_sign = neg ? (1L << 63) : 0;
    exp += 1023;
    long bits_exp = (exp <= 0) ? 0 : ((long)exp) << 52;
    long bits_mant = m & ~(1L << 52);
    return Double.longBitsToDouble(bits_sign | bits_exp | bits_mant);
  }

  /** Copy the abolute value of this into an array of words.
   * Assumes words.length >= (this.words == null ? 1 : this.ival).
   * Result is zero-extended, but need not be a valid 2's complement number.
   */
  private void getAbsolute(int[] words)
  {
    int len;
    if (this.words == null)
      {
2055 2056
        len = 1;
        words[0] = this.ival;
Tom Tromey committed
2057 2058 2059
      }
    else
      {
2060 2061 2062
        len = this.ival;
        for (int i = len;  --i >= 0; )
          words[i] = this.words[i];
Tom Tromey committed
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
      }
    if (words[len - 1] < 0)
      negate(words, words, len);
    for (int i = words.length;  --i > len; )
      words[i] = 0;
  }

  /** Set dest[0:len-1] to the negation of src[0:len-1].
   * Return true if overflow (i.e. if src is -2**(32*len-1)).
   * Ok for src==dest. */
  private static boolean negate(int[] dest, int[] src, int len)
  {
    long carry = 1;
    boolean negative = src[len-1] < 0;
    for (int i = 0;  i < len;  i++)
      {
        carry += ((long) (~src[i]) & 0xffffffffL);
        dest[i] = (int) carry;
        carry >>= 32;
      }
    return (negative && dest[len-1] < 0);
  }

  /** Destructively set this to the negative of x.
   * It is OK if x==this.*/
  private void setNegative(BigInteger x)
  {
    int len = x.ival;
    if (x.words == null)
      {
2093 2094 2095 2096 2097
        if (len == Integer.MIN_VALUE)
          set(- (long) len);
        else
          set(-len);
        return;
Tom Tromey committed
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
      }
    realloc(len + 1);
    if (negate(words, x.words, len))
      words[len++] = 0;
    ival = len;
  }

  /** Destructively negate this. */
  private void setNegative()
  {
    setNegative(this);
  }

  private static BigInteger abs(BigInteger x)
  {
    return x.isNegative() ? neg(x) : x;
  }

  public BigInteger abs()
  {
2118 2119 2120 2121 2122 2123 2124
    if (USING_NATIVE)
      {
        BigInteger result = new BigInteger();
        mpz.abs(result.mpz);
        return result;
      }

Tom Tromey committed
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138
    return abs(this);
  }

  private static BigInteger neg(BigInteger x)
  {
    if (x.words == null && x.ival != Integer.MIN_VALUE)
      return valueOf(- x.ival);
    BigInteger result = new BigInteger(0);
    result.setNegative(x);
    return result.canonicalize();
  }

  public BigInteger negate()
  {
2139 2140 2141
    if (USING_NATIVE)
      {
        BigInteger result = new BigInteger();
2142
        mpz.negate(result.mpz);
2143 2144 2145
        return result;
      }

Tom Tromey committed
2146 2147 2148 2149 2150 2151 2152 2153
    return neg(this);
  }

  /** Calculates ceiling(log2(this < 0 ? -this : this+1))
   * See Common Lisp: the Language, 2nd ed, p. 361.
   */
  public int bitLength()
  {
2154 2155 2156
    if (USING_NATIVE)
      return mpz.bitLength();

Tom Tromey committed
2157 2158 2159 2160 2161 2162 2163
    if (words == null)
      return MPN.intLength(ival);
      return MPN.intLength(words, ival);
  }

  public byte[] toByteArray()
  {
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
    if (signum() == 0)
      return new byte[1];

    if (USING_NATIVE)
      {
        // the minimal number of bytes required to represent the MPI is function
        // of (a) its bit-length, and (b) its sign.  only when this MPI is both
        // positive, and its bit-length is a multiple of 8 do we add one zero
        // bit for its sign.  we do this so if we construct a new MPI from the
        // resulting byte array, we wouldn't mistake a positive number, whose
        // bit-length is a multiple of 8, for a similar-length negative one.
        int bits = bitLength();
        if (bits % 8 == 0 || this.signum() == 1)
          bits++;
        byte[] bytes = new byte[(bits + 7) / 8];
        mpz.toByteArray(bytes);
        return bytes;
      }

Tom Tromey committed
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
    // Determine number of bytes needed.  The method bitlength returns
    // the size without the sign bit, so add one bit for that and then
    // add 7 more to emulate the ceil function using integer math.
    byte[] bytes = new byte[(bitLength() + 1 + 7) / 8];
    int nbytes = bytes.length;

    int wptr = 0;
    int word;

    // Deal with words array until one word or less is left to process.
    // If BigInteger is an int, then it is in ival and nbytes will be <= 4.
    while (nbytes > 4)
      {
2196 2197
        word = words[wptr++];
        for (int i = 4; i > 0; --i, word >>= 8)
Tom Tromey committed
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
          bytes[--nbytes] = (byte) word;
      }

    // Deal with the last few bytes.  If BigInteger is an int, use ival.
    word = (words == null) ? ival : words[wptr];
    for ( ; nbytes > 0; word >>= 8)
      bytes[--nbytes] = (byte) word;

    return bytes;
  }

  /** Return the boolean opcode (for bitOp) for swapped operands.
   * I.e. bitOp(swappedOp(op), x, y) == bitOp(op, y, x).
   */
  private static int swappedOp(int op)
  {
    return
    "\000\001\004\005\002\003\006\007\010\011\014\015\012\013\016\017"
    .charAt(op);
  }

  /** Do one the the 16 possible bit-wise operations of two BigIntegers. */
  private static BigInteger bitOp(int op, BigInteger x, BigInteger y)
  {
    switch (op)
      {
        case 0:  return ZERO;
        case 1:  return x.and(y);
        case 3:  return x;
        case 5:  return y;
        case 15: return valueOf(-1);
      }
    BigInteger result = new BigInteger();
    setBitOp(result, op, x, y);
    return result.canonicalize();
  }

  /** Do one the the 16 possible bit-wise operations of two BigIntegers. */
  private static void setBitOp(BigInteger result, int op,
2237
                               BigInteger x, BigInteger y)
Tom Tromey committed
2238
  {
2239
    if ((y.words != null) && (x.words == null || x.ival < y.ival))
Tom Tromey committed
2240
      {
2241 2242
        BigInteger temp = x;  x = y;  y = temp;
        op = swappedOp(op);
Tom Tromey committed
2243 2244 2245 2246 2247 2248
      }
    int xi;
    int yi;
    int xlen, ylen;
    if (y.words == null)
      {
2249 2250
        yi = y.ival;
        ylen = 1;
Tom Tromey committed
2251 2252 2253
      }
    else
      {
2254 2255
        yi = y.words[0];
        ylen = y.ival;
Tom Tromey committed
2256 2257 2258
      }
    if (x.words == null)
      {
2259 2260
        xi = x.ival;
        xlen = 1;
Tom Tromey committed
2261 2262 2263
      }
    else
      {
2264 2265
        xi = x.words[0];
        xlen = x.ival;
Tom Tromey committed
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
      }
    if (xlen > 1)
      result.realloc(xlen);
    int[] w = result.words;
    int i = 0;
    // Code for how to handle the remainder of x.
    // 0:  Truncate to length of y.
    // 1:  Copy rest of x.
    // 2:  Invert rest of x.
    int finish = 0;
    int ni;
    switch (op)
      {
      case 0:  // clr
2280 2281
        ni = 0;
        break;
Tom Tromey committed
2282
      case 1: // and
2283 2284 2285 2286 2287 2288 2289 2290
        for (;;)
          {
            ni = xi & yi;
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        if (yi < 0) finish = 1;
        break;
Tom Tromey committed
2291
      case 2: // andc2
2292 2293 2294 2295 2296 2297 2298 2299
        for (;;)
          {
            ni = xi & ~yi;
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        if (yi >= 0) finish = 1;
        break;
Tom Tromey committed
2300
      case 3:  // copy x
2301 2302 2303
        ni = xi;
        finish = 1;  // Copy rest
        break;
Tom Tromey committed
2304
      case 4: // andc1
2305 2306 2307 2308 2309 2310 2311 2312
        for (;;)
          {
            ni = ~xi & yi;
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        if (yi < 0) finish = 2;
        break;
Tom Tromey committed
2313
      case 5: // copy y
2314 2315 2316 2317 2318 2319 2320
        for (;;)
          {
            ni = yi;
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        break;
Tom Tromey committed
2321
      case 6:  // xor
2322 2323 2324 2325 2326 2327 2328 2329
        for (;;)
          {
            ni = xi ^ yi;
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        finish = yi < 0 ? 2 : 1;
        break;
Tom Tromey committed
2330
      case 7:  // ior
2331 2332 2333 2334 2335 2336 2337 2338
        for (;;)
          {
            ni = xi | yi;
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        if (yi >= 0) finish = 1;
        break;
Tom Tromey committed
2339
      case 8:  // nor
2340 2341 2342 2343 2344 2345 2346 2347
        for (;;)
          {
            ni = ~(xi | yi);
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        if (yi >= 0)  finish = 2;
        break;
Tom Tromey committed
2348
      case 9:  // eqv [exclusive nor]
2349 2350 2351 2352 2353 2354 2355 2356
        for (;;)
          {
            ni = ~(xi ^ yi);
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        finish = yi >= 0 ? 2 : 1;
        break;
Tom Tromey committed
2357
      case 10:  // c2
2358 2359 2360 2361 2362 2363 2364
        for (;;)
          {
            ni = ~yi;
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        break;
Tom Tromey committed
2365
      case 11:  // orc2
2366 2367 2368 2369 2370 2371 2372 2373
        for (;;)
          {
            ni = xi | ~yi;
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        if (yi < 0)  finish = 1;
        break;
Tom Tromey committed
2374
      case 12:  // c1
2375 2376 2377
        ni = ~xi;
        finish = 2;
        break;
Tom Tromey committed
2378
      case 13:  // orc1
2379 2380 2381 2382 2383 2384 2385 2386
        for (;;)
          {
            ni = ~xi | yi;
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        if (yi >= 0) finish = 2;
        break;
Tom Tromey committed
2387
      case 14:  // nand
2388 2389 2390 2391 2392 2393 2394 2395
        for (;;)
          {
            ni = ~(xi & yi);
            if (i+1 >= ylen) break;
            w[i++] = ni;  xi = x.words[i];  yi = y.words[i];
          }
        if (yi < 0) finish = 2;
        break;
Tom Tromey committed
2396 2397
      default:
      case 15:  // set
2398 2399
        ni = -1;
        break;
Tom Tromey committed
2400 2401 2402 2403 2404 2405 2406 2407
      }
    // Here i==ylen-1; w[0]..w[i-1] have the correct result;
    // and ni contains the correct result for w[i+1].
    if (i+1 == xlen)
      finish = 0;
    switch (finish)
      {
      case 0:
2408 2409 2410 2411 2412 2413 2414
        if (i == 0 && w == null)
          {
            result.ival = ni;
            return;
          }
        w[i++] = ni;
        break;
Tom Tromey committed
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
      case 1:  w[i] = ni;  while (++i < xlen)  w[i] = x.words[i];  break;
      case 2:  w[i] = ni;  while (++i < xlen)  w[i] = ~x.words[i];  break;
      }
    result.ival = i;
  }

  /** Return the logical (bit-wise) "and" of a BigInteger and an int. */
  private static BigInteger and(BigInteger x, int y)
  {
    if (x.words == null)
      return valueOf(x.ival & y);
    if (y >= 0)
      return valueOf(x.words[0] & y);
    int len = x.ival;
    int[] words = new int[len];
    words[0] = x.words[0] & y;
    while (--len > 0)
      words[len] = x.words[len];
    return make(words, x.ival);
  }

  /** Return the logical (bit-wise) "and" of two BigIntegers. */
  public BigInteger and(BigInteger y)
  {
2439 2440 2441 2442 2443 2444 2445 2446
    if (USING_NATIVE)
      {
        int dummy = y.signum; // force NPE check
        BigInteger result = new BigInteger();
        mpz.and(y.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
    if (y.words == null)
      return and(this, y.ival);
    else if (words == null)
      return and(y, ival);

    BigInteger x = this;
    if (ival < y.ival)
      {
        BigInteger temp = this;  x = y;  y = temp;
      }
    int i;
    int len = y.isNegative() ? x.ival : y.ival;
    int[] words = new int[len];
    for (i = 0;  i < y.ival;  i++)
      words[i] = x.words[i] & y.words[i];
    for ( ; i < len;  i++)
      words[i] = x.words[i];
    return make(words, len);
  }

  /** Return the logical (bit-wise) "(inclusive) or" of two BigIntegers. */
  public BigInteger or(BigInteger y)
  {
2470 2471 2472 2473 2474 2475 2476 2477
    if (USING_NATIVE)
      {
        int dummy = y.signum; // force NPE check
        BigInteger result = new BigInteger();
        mpz.or(y.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
2478 2479 2480 2481 2482 2483
    return bitOp(7, this, y);
  }

  /** Return the logical (bit-wise) "exclusive or" of two BigIntegers. */
  public BigInteger xor(BigInteger y)
  {
2484 2485 2486 2487 2488 2489 2490 2491
    if (USING_NATIVE)
      {
        int dummy = y.signum; // force NPE check
        BigInteger result = new BigInteger();
        mpz.xor(y.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
2492 2493 2494 2495 2496 2497
    return bitOp(6, this, y);
  }

  /** Return the logical (bit-wise) negation of a BigInteger. */
  public BigInteger not()
  {
2498 2499 2500 2501 2502 2503 2504
    if (USING_NATIVE)
      {
        BigInteger result = new BigInteger();
        mpz.not(result.mpz);
        return result;
      }

Tom Tromey committed
2505 2506 2507 2508 2509
    return bitOp(12, this, ZERO);
  }

  public BigInteger andNot(BigInteger val)
  {
2510 2511 2512 2513 2514 2515 2516 2517
    if (USING_NATIVE)
      {
        int dummy = val.signum; // force NPE check
        BigInteger result = new BigInteger();
        mpz.andNot(val.mpz, result.mpz);
        return result;
      }

Tom Tromey committed
2518 2519 2520 2521 2522 2523 2524 2525
    return and(val.not());
  }

  public BigInteger clearBit(int n)
  {
    if (n < 0)
      throw new ArithmeticException();

2526 2527 2528 2529 2530 2531 2532
    if (USING_NATIVE)
      {
        BigInteger result = new BigInteger();
        mpz.setBit(n, false, result.mpz);
        return result;
      }

Tom Tromey committed
2533 2534 2535 2536 2537 2538 2539 2540
    return and(ONE.shiftLeft(n).not());
  }

  public BigInteger setBit(int n)
  {
    if (n < 0)
      throw new ArithmeticException();

2541 2542 2543 2544 2545 2546 2547
    if (USING_NATIVE)
      {
        BigInteger result = new BigInteger();
        mpz.setBit(n, true, result.mpz);
        return result;
      }

Tom Tromey committed
2548 2549 2550 2551 2552 2553 2554 2555
    return or(ONE.shiftLeft(n));
  }

  public boolean testBit(int n)
  {
    if (n < 0)
      throw new ArithmeticException();

2556 2557 2558
    if (USING_NATIVE)
      return mpz.testBit(n) != 0;

Tom Tromey committed
2559 2560 2561 2562 2563 2564 2565 2566
    return !and(ONE.shiftLeft(n)).isZero();
  }

  public BigInteger flipBit(int n)
  {
    if (n < 0)
      throw new ArithmeticException();

2567 2568 2569 2570 2571 2572 2573
    if (USING_NATIVE)
      {
        BigInteger result = new BigInteger();
        mpz.flipBit(n, result.mpz);
        return result;
      }

Tom Tromey committed
2574 2575 2576 2577 2578
    return xor(ONE.shiftLeft(n));
  }

  public int getLowestSetBit()
  {
2579 2580 2581
    if (USING_NATIVE)
      return mpz.compare(ZERO.mpz) == 0 ? -1 : mpz.lowestSetBit();

Tom Tromey committed
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
    if (isZero())
      return -1;

    if (words == null)
      return MPN.findLowestBit(ival);
    else
      return MPN.findLowestBit(words);
  }

  // bit4count[I] is number of '1' bits in I.
  private static final byte[] bit4_count = { 0, 1, 1, 2,  1, 2, 2, 3,
2593
                                             1, 2, 2, 3,  2, 3, 3, 4};
Tom Tromey committed
2594 2595 2596 2597 2598 2599

  private static int bitCount(int i)
  {
    int count = 0;
    while (i != 0)
      {
2600 2601
        count += bit4_count[i & 15];
        i >>>= 4;
Tom Tromey committed
2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
      }
    return count;
  }

  private static int bitCount(int[] x, int len)
  {
    int count = 0;
    while (--len >= 0)
      count += bitCount(x[len]);
    return count;
  }

  /** Count one bits in a BigInteger.
   * If argument is negative, count zero bits instead. */
  public int bitCount()
  {
2618 2619 2620
    if (USING_NATIVE)
      return mpz.bitCount();

Tom Tromey committed
2621 2622 2623 2624
    int i, x_len;
    int[] x_words = words;
    if (x_words == null)
      {
2625 2626
        x_len = 1;
        i = bitCount(ival);
Tom Tromey committed
2627 2628 2629
      }
    else
      {
2630 2631
        x_len = ival;
        i = bitCount(x_words, x_len);
Tom Tromey committed
2632 2633 2634 2635 2636 2637 2638
      }
    return isNegative() ? x_len * 32 - i : i;
  }

  private void readObject(ObjectInputStream s)
    throws IOException, ClassNotFoundException
  {
2639
    if (USING_NATIVE)
2640
      {
2641 2642 2643 2644 2645
        mpz = new GMP();
        s.defaultReadObject();
        if (signum != 0)
          mpz.fromByteArray(magnitude);
        // else it's zero and we need to do nothing
2646 2647 2648
      }
    else
      {
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661
        s.defaultReadObject();
        if (magnitude.length == 0 || signum == 0)
          {
            this.ival = 0;
            this.words = null;
          }
        else
          {
            words = byteArrayToIntArray(magnitude, signum < 0 ? -1 : 0);
            BigInteger result = make(words, words.length);
            this.ival = result.ival;
            this.words = result.words;
          }
2662
      }
Tom Tromey committed
2663 2664 2665 2666 2667 2668
  }

  private void writeObject(ObjectOutputStream s)
    throws IOException, ClassNotFoundException
  {
    signum = signum();
2669
    magnitude = signum == 0 ? new byte[0] : toByteArray();
Tom Tromey committed
2670
    s.defaultWriteObject();
2671
    magnitude = null; // not needed anymore
Tom Tromey committed
2672
  }
2673 2674 2675

  // inner class(es) ..........................................................

Tom Tromey committed
2676
}