1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package java.math; 19 20 import java.io.IOException; 21 import java.io.ObjectInputStream; 22 import java.io.ObjectOutputStream; 23 import java.io.Serializable; 24 import java.util.Random; 25 import libcore.util.NonNull; 26 import libcore.util.Nullable; 27 28 /** 29 * An immutable arbitrary-precision signed integer. 30 * 31 * <h3>Fast Cryptography</h3> 32 * This implementation is efficient for operations traditionally used in 33 * cryptography, such as the generation of large prime numbers and computation 34 * of the modular inverse. 35 * 36 * <h3>Slow Two's Complement Bitwise Operations</h3> 37 * This API includes operations for bitwise operations in two's complement 38 * representation. Two's complement is not the internal representation used by 39 * this implementation, so such methods may be inefficient. Use {@link 40 * java.util.BitSet} for high-performance bitwise operations on 41 * arbitrarily-large sequences of bits. 42 */ 43 public class BigInteger extends Number 44 implements Comparable<BigInteger>, Serializable { 45 46 /** This is the serialVersionUID used by the sun implementation. */ 47 private static final long serialVersionUID = -8287574255936472291L; 48 49 private transient BigInt bigInt; 50 51 private transient boolean nativeIsValid = false; 52 53 private transient boolean javaIsValid = false; 54 55 /** The magnitude of this in the little-endian representation. */ 56 transient int[] digits; 57 58 /** 59 * The length of this in measured in ints. Can be less than 60 * digits.length(). 61 */ 62 transient int numberLength; 63 64 /** The sign of this. */ 65 transient int sign; 66 67 /** The {@code BigInteger} constant 0. */ 68 @NonNull public static final BigInteger ZERO = new BigInteger(0, 0); 69 70 /** The {@code BigInteger} constant 1. */ 71 @NonNull public static final BigInteger ONE = new BigInteger(1, 1); 72 73 /** The {@code BigInteger} constant 10. */ 74 @NonNull public static final BigInteger TEN = new BigInteger(1, 10); 75 76 /** The {@code BigInteger} constant -1. */ 77 static final BigInteger MINUS_ONE = new BigInteger(-1, 1); 78 79 /** All the {@code BigInteger} numbers in the range [0,10] are cached. */ 80 static final BigInteger[] SMALL_VALUES = { ZERO, ONE, new BigInteger(1, 2), 81 new BigInteger(1, 3), new BigInteger(1, 4), new BigInteger(1, 5), 82 new BigInteger(1, 6), new BigInteger(1, 7), new BigInteger(1, 8), 83 new BigInteger(1, 9), TEN }; 84 85 private transient int firstNonzeroDigit = -2; 86 87 /** sign field, used for serialization. */ 88 private int signum; 89 90 /** absolute value field, used for serialization */ 91 private byte[] magnitude; 92 93 /** Cache for the hash code. */ 94 private transient int hashCode = 0; 95 BigInteger(BigInt bigInt)96 BigInteger(BigInt bigInt) { 97 if (bigInt == null || !bigInt.hasNativeBignum()) { 98 throw new AssertionError(); 99 } 100 setBigInt(bigInt); 101 } 102 BigInteger(int sign, long value)103 BigInteger(int sign, long value) { 104 BigInt bigInt = new BigInt(); 105 bigInt.putULongInt(value, (sign < 0)); 106 setBigInt(bigInt); 107 } 108 109 /** 110 * Constructs a number without creating new space. This construct should be 111 * used only if the three fields of representation are known. 112 * 113 * @param sign the sign of the number. 114 * @param numberLength the length of the internal array. 115 * @param digits a reference of some array created before. 116 */ BigInteger(int sign, int numberLength, int[] digits)117 BigInteger(int sign, int numberLength, int[] digits) { 118 setJavaRepresentation(sign, numberLength, digits); 119 } 120 121 /** 122 * Constructs a random non-negative {@code BigInteger} instance in the range 123 * {@code [0, pow(2, numBits)-1]}. 124 * 125 * @param numBits maximum length of the new {@code BigInteger} in bits. 126 * @param random is the random number generator to be used. 127 * @throws IllegalArgumentException if {@code numBits} < 0. 128 */ BigInteger(int numBits, @NonNull Random random)129 public BigInteger(int numBits, @NonNull Random random) { 130 if (numBits < 0) { 131 throw new IllegalArgumentException("numBits < 0: " + numBits); 132 } 133 if (numBits == 0) { 134 setJavaRepresentation(0, 1, new int[] { 0 }); 135 } else { 136 int sign = 1; 137 int numberLength = (numBits + 31) >> 5; 138 int[] digits = new int[numberLength]; 139 for (int i = 0; i < numberLength; i++) { 140 digits[i] = random.nextInt(); 141 } 142 // Clear any extra bits. 143 digits[numberLength - 1] >>>= (-numBits) & 31; 144 setJavaRepresentation(sign, numberLength, digits); 145 } 146 javaIsValid = true; 147 } 148 149 /** 150 * Constructs a random {@code BigInteger} instance in the range {@code [0, 151 * pow(2, bitLength)-1]} which is probably prime. The probability that the 152 * returned {@code BigInteger} is prime is greater than 153 * {@code 1 - 1/2<sup>certainty</sup>)}. 154 * 155 * <p><b>Note:</b> the {@code Random} argument is ignored if 156 * {@code bitLength >= 16}, where this implementation will use OpenSSL's 157 * {@code BN_generate_prime_ex} as a source of cryptographically strong pseudo-random numbers. 158 * 159 * @param bitLength length of the new {@code BigInteger} in bits. 160 * @param certainty tolerated primality uncertainty. 161 * @throws ArithmeticException if {@code bitLength < 2}. 162 * @see <a href="http://www.openssl.org/docs/crypto/BN_rand.html"> 163 * Specification of random generator used from OpenSSL library</a> 164 */ BigInteger(int bitLength, int certainty, @NonNull Random random)165 public BigInteger(int bitLength, int certainty, @NonNull Random random) { 166 if (bitLength < 2) { 167 throw new ArithmeticException("bitLength < 2: " + bitLength); 168 } 169 if (bitLength < 16) { 170 // We have to generate short primes ourselves, because OpenSSL bottoms out at 16 bits. 171 int candidate; 172 do { 173 candidate = random.nextInt() & ((1 << bitLength) - 1); 174 candidate |= (1 << (bitLength - 1)); // Set top bit. 175 if (bitLength > 2) { 176 candidate |= 1; // Any prime longer than 2 bits must have the bottom bit set. 177 } 178 } while (!isSmallPrime(candidate)); 179 BigInt prime = new BigInt(); 180 prime.putULongInt(candidate, false); 181 setBigInt(prime); 182 } else { 183 // We need a loop here to work around an OpenSSL bug; http://b/8588028. 184 do { 185 setBigInt(BigInt.generatePrimeDefault(bitLength)); 186 } while (bitLength() != bitLength); 187 } 188 } 189 isSmallPrime(int x)190 private static boolean isSmallPrime(int x) { 191 if (x == 2) { 192 return true; 193 } 194 if ((x % 2) == 0) { 195 return false; 196 } 197 final int max = (int) Math.sqrt(x); 198 for (int i = 3; i <= max; i += 2) { 199 if ((x % i) == 0) { 200 return false; 201 } 202 } 203 return true; 204 } 205 206 /** 207 * Constructs a new {@code BigInteger} by parsing {@code value}. The string 208 * representation consists of an optional plus or minus sign followed by a 209 * non-empty sequence of decimal digits. Digits are interpreted as if by 210 * {@code Character.digit(char,10)}. 211 * 212 * @param value string representation of the new {@code BigInteger}. 213 * @throws NullPointerException if {@code value == null}. 214 * @throws NumberFormatException if {@code value} is not a valid 215 * representation of a {@code BigInteger}. 216 */ BigInteger(@onNull String value)217 public BigInteger(@NonNull String value) { 218 BigInt bigInt = new BigInt(); 219 bigInt.putDecString(value); 220 setBigInt(bigInt); 221 } 222 223 /** 224 * Constructs a new {@code BigInteger} instance by parsing {@code value}. 225 * The string representation consists of an optional plus or minus sign 226 * followed by a non-empty sequence of digits in the specified radix. Digits 227 * are interpreted as if by {@code Character.digit(char, radix)}. 228 * 229 * @param value string representation of the new {@code BigInteger}. 230 * @param radix the base to be used for the conversion. 231 * @throws NullPointerException if {@code value == null}. 232 * @throws NumberFormatException if {@code value} is not a valid 233 * representation of a {@code BigInteger} or if {@code radix < 234 * Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}. 235 */ BigInteger(@onNull String value, int radix)236 public BigInteger(@NonNull String value, int radix) { 237 if (value == null) { 238 throw new NullPointerException("value == null"); 239 } 240 if (radix == 10) { 241 BigInt bigInt = new BigInt(); 242 bigInt.putDecString(value); 243 setBigInt(bigInt); 244 } else if (radix == 16) { 245 BigInt bigInt = new BigInt(); 246 bigInt.putHexString(value); 247 setBigInt(bigInt); 248 } else { 249 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { 250 throw new NumberFormatException("Invalid radix: " + radix); 251 } 252 if (value.isEmpty()) { 253 throw new NumberFormatException("value.isEmpty()"); 254 } 255 BigInteger.parseFromString(this, value, radix); 256 } 257 } 258 259 /** 260 * Constructs a new {@code BigInteger} instance with the given sign and 261 * magnitude. 262 * 263 * @param signum sign of the new {@code BigInteger} (-1 for negative, 0 for 264 * zero, 1 for positive). 265 * @param magnitude magnitude of the new {@code BigInteger} with the most 266 * significant byte first. 267 * @throws NullPointerException if {@code magnitude == null}. 268 * @throws NumberFormatException if the sign is not one of -1, 0, 1 or if 269 * the sign is zero and the magnitude contains non-zero entries. 270 */ BigInteger(int signum, byte @NonNull [] magnitude)271 public BigInteger(int signum, byte @NonNull [] magnitude) { 272 if (magnitude == null) { 273 throw new NullPointerException("magnitude == null"); 274 } 275 if (signum < -1 || signum > 1) { 276 throw new NumberFormatException("Invalid signum: " + signum); 277 } 278 if (signum == 0) { 279 for (byte element : magnitude) { 280 if (element != 0) { 281 throw new NumberFormatException("signum-magnitude mismatch"); 282 } 283 } 284 } 285 BigInt bigInt = new BigInt(); 286 bigInt.putBigEndian(magnitude, signum < 0); 287 setBigInt(bigInt); 288 } 289 290 /** 291 * Constructs a new {@code BigInteger} from the given two's complement 292 * representation. The most significant byte is the entry at index 0. The 293 * most significant bit of this entry determines the sign of the new {@code 294 * BigInteger} instance. The array must be nonempty. 295 * 296 * @param value two's complement representation of the new {@code 297 * BigInteger}. 298 * @throws NullPointerException if {@code value == null}. 299 * @throws NumberFormatException if the length of {@code value} is zero. 300 */ BigInteger(byte @NonNull [] value)301 public BigInteger(byte @NonNull [] value) { 302 if (value.length == 0) { 303 throw new NumberFormatException("value.length == 0"); 304 } 305 BigInt bigInt = new BigInt(); 306 bigInt.putBigEndianTwosComplement(value); 307 setBigInt(bigInt); 308 } 309 310 /** 311 * Returns the internal native representation of this big integer, computing 312 * it if necessary. 313 */ getBigInt()314 BigInt getBigInt() { 315 if (nativeIsValid) { 316 return bigInt; 317 } 318 319 synchronized (this) { 320 if (nativeIsValid) { 321 return bigInt; 322 } 323 BigInt bigInt = new BigInt(); 324 bigInt.putLittleEndianInts(digits, (sign < 0)); 325 setBigInt(bigInt); 326 return bigInt; 327 } 328 } 329 setBigInt(BigInt bigInt)330 private void setBigInt(BigInt bigInt) { 331 this.bigInt = bigInt; 332 this.nativeIsValid = true; 333 } 334 setJavaRepresentation(int sign, int numberLength, int[] digits)335 private void setJavaRepresentation(int sign, int numberLength, int[] digits) { 336 // decrement numberLength to drop leading zeroes... 337 while (numberLength > 0 && digits[--numberLength] == 0) { 338 ; 339 } 340 // ... and then increment it back because we always drop one too many 341 if (digits[numberLength++] == 0) { 342 sign = 0; 343 } 344 this.sign = sign; 345 this.digits = digits; 346 this.numberLength = numberLength; 347 this.javaIsValid = true; 348 } 349 prepareJavaRepresentation()350 void prepareJavaRepresentation() { 351 if (javaIsValid) { 352 return; 353 } 354 355 synchronized (this) { 356 if (javaIsValid) { 357 return; 358 } 359 int sign = bigInt.sign(); 360 int[] digits = (sign != 0) ? bigInt.littleEndianIntsMagnitude() : new int[] { 0 }; 361 setJavaRepresentation(sign, digits.length, digits); 362 } 363 } 364 365 /** Returns a {@code BigInteger} whose value is equal to {@code value}. */ valueOf(long value)366 @NonNull public static BigInteger valueOf(long value) { 367 if (value < 0) { 368 if (value != -1) { 369 return new BigInteger(-1, -value); 370 } 371 return MINUS_ONE; 372 } else if (value < SMALL_VALUES.length) { 373 return SMALL_VALUES[(int) value]; 374 } else {// (value > 10) 375 return new BigInteger(1, value); 376 } 377 } 378 379 /** 380 * Returns the two's complement representation of this {@code BigInteger} in 381 * a byte array. 382 */ toByteArray()383 public byte @NonNull [] toByteArray() { 384 return twosComplement(); 385 } 386 387 /** 388 * Returns a {@code BigInteger} whose value is the absolute value of {@code 389 * this}. 390 */ abs()391 @NonNull public BigInteger abs() { 392 BigInt bigInt = getBigInt(); 393 if (bigInt.sign() >= 0) { 394 return this; 395 } 396 BigInt a = bigInt.copy(); 397 a.setSign(1); 398 return new BigInteger(a); 399 } 400 401 /** 402 * Returns a {@code BigInteger} whose value is the {@code -this}. 403 */ negate()404 @NonNull public BigInteger negate() { 405 BigInt bigInt = getBigInt(); 406 int sign = bigInt.sign(); 407 if (sign == 0) { 408 return this; 409 } 410 BigInt a = bigInt.copy(); 411 a.setSign(-sign); 412 return new BigInteger(a); 413 } 414 415 /** 416 * Returns a {@code BigInteger} whose value is {@code this + value}. 417 */ add(@onNull BigInteger value)418 @NonNull public BigInteger add(@NonNull BigInteger value) { 419 BigInt lhs = getBigInt(); 420 BigInt rhs = value.getBigInt(); 421 if (rhs.sign() == 0) { 422 return this; 423 } 424 if (lhs.sign() == 0) { 425 return value; 426 } 427 return new BigInteger(BigInt.addition(lhs, rhs)); 428 } 429 430 /** 431 * Returns a {@code BigInteger} whose value is {@code this - value}. 432 */ subtract(@onNull BigInteger value)433 @NonNull public BigInteger subtract(@NonNull BigInteger value) { 434 BigInt lhs = getBigInt(); 435 BigInt rhs = value.getBigInt(); 436 if (rhs.sign() == 0) { 437 return this; 438 } 439 return new BigInteger(BigInt.subtraction(lhs, rhs)); 440 } 441 442 /** 443 * Returns the sign of this {@code BigInteger}. 444 * 445 * @return {@code -1} if {@code this < 0}, {@code 0} if {@code this == 0}, 446 * {@code 1} if {@code this > 0}. 447 */ signum()448 public int signum() { 449 if (javaIsValid) { 450 return sign; 451 } 452 return getBigInt().sign(); 453 } 454 455 /** 456 * Returns a {@code BigInteger} whose value is {@code this >> n}. For 457 * negative arguments, the result is also negative. The shift distance may 458 * be negative which means that {@code this} is shifted left. 459 * 460 * <p><b>Implementation Note:</b> Usage of this method on negative values is 461 * not recommended as the current implementation is not efficient. 462 * 463 * @param n shift distance 464 * @return {@code this >> n} if {@code n >= 0}; {@code this << (-n)} 465 * otherwise 466 */ shiftRight(int n)467 @NonNull public BigInteger shiftRight(int n) { 468 return shiftLeft(-n); 469 } 470 471 /** 472 * Returns a {@code BigInteger} whose value is {@code this << n}. The 473 * result is equivalent to {@code this * pow(2, n)} if n >= 0. The shift 474 * distance may be negative which means that {@code this} is shifted right. 475 * The result then corresponds to {@code floor(this / pow(2, -n))}. 476 * 477 * <p><b>Implementation Note:</b> Usage of this method on negative values is 478 * not recommended as the current implementation is not efficient. 479 * 480 * @param n shift distance. 481 * @return {@code this << n} if {@code n >= 0}; {@code this >> (-n)}. 482 * otherwise 483 */ shiftLeft(int n)484 @NonNull public BigInteger shiftLeft(int n) { 485 if (n == 0) { 486 return this; 487 } 488 int sign = signum(); 489 if (sign == 0) { 490 return this; 491 } 492 if ((sign > 0) || (n >= 0)) { 493 return new BigInteger(BigInt.shift(getBigInt(), n)); 494 } else { 495 // Negative numbers faking 2's complement: 496 // Not worth optimizing this: 497 // Sticking to Harmony Java implementation. 498 return BitLevel.shiftRight(this, -n); 499 } 500 } 501 shiftLeftOneBit()502 BigInteger shiftLeftOneBit() { 503 return (signum() == 0) ? this : BitLevel.shiftLeftOneBit(this); 504 } 505 506 /** 507 * Returns the length of the value's two's complement representation without 508 * leading zeros for positive numbers / without leading ones for negative 509 * values. 510 * 511 * <p>The two's complement representation of {@code this} will be at least 512 * {@code bitLength() + 1} bits long. 513 * 514 * <p>The value will fit into an {@code int} if {@code bitLength() < 32} or 515 * into a {@code long} if {@code bitLength() < 64}. 516 * 517 * @return the length of the minimal two's complement representation for 518 * {@code this} without the sign bit. 519 */ bitLength()520 public int bitLength() { 521 // Optimization to avoid unnecessary duplicate representation: 522 if (!nativeIsValid && javaIsValid) { 523 return BitLevel.bitLength(this); 524 } 525 return getBigInt().bitLength(); 526 } 527 528 /** 529 * Tests whether the bit at position n in {@code this} is set. The result is 530 * equivalent to {@code this & pow(2, n) != 0}. 531 * 532 * <p><b>Implementation Note:</b> Usage of this method is not recommended as 533 * the current implementation is not efficient. 534 * 535 * @param n position where the bit in {@code this} has to be inspected. 536 * @throws ArithmeticException if {@code n < 0}. 537 */ testBit(int n)538 public boolean testBit(int n) { 539 if (n < 0) { 540 throw new ArithmeticException("n < 0: " + n); 541 } 542 int sign = signum(); 543 if (sign > 0 && nativeIsValid && !javaIsValid) { 544 return getBigInt().isBitSet(n); 545 } else { 546 // Negative numbers faking 2's complement: 547 // Not worth optimizing this: 548 // Sticking to Harmony Java implementation. 549 prepareJavaRepresentation(); 550 if (n == 0) { 551 return ((digits[0] & 1) != 0); 552 } 553 int intCount = n >> 5; 554 if (intCount >= numberLength) { 555 return (sign < 0); 556 } 557 int digit = digits[intCount]; 558 n = (1 << (n & 31)); // int with 1 set to the needed position 559 if (sign < 0) { 560 int firstNonZeroDigit = getFirstNonzeroDigit(); 561 if (intCount < firstNonZeroDigit) { 562 return false; 563 } else if (firstNonZeroDigit == intCount) { 564 digit = -digit; 565 } else { 566 digit = ~digit; 567 } 568 } 569 return ((digit & n) != 0); 570 } 571 } 572 573 /** 574 * Returns a {@code BigInteger} which has the same binary representation 575 * as {@code this} but with the bit at position n set. The result is 576 * equivalent to {@code this | pow(2, n)}. 577 * 578 * <p><b>Implementation Note:</b> Usage of this method is not recommended as 579 * the current implementation is not efficient. 580 * 581 * @param n position where the bit in {@code this} has to be set. 582 * @throws ArithmeticException if {@code n < 0}. 583 */ setBit(int n)584 @NonNull public BigInteger setBit(int n) { 585 prepareJavaRepresentation(); 586 if (!testBit(n)) { 587 return BitLevel.flipBit(this, n); 588 } else { 589 return this; 590 } 591 } 592 593 /** 594 * Returns a {@code BigInteger} which has the same binary representation 595 * as {@code this} but with the bit at position n cleared. The result is 596 * equivalent to {@code this & ~pow(2, n)}. 597 * 598 * <p><b>Implementation Note:</b> Usage of this method is not recommended as 599 * the current implementation is not efficient. 600 * 601 * @param n position where the bit in {@code this} has to be cleared. 602 * @throws ArithmeticException if {@code n < 0}. 603 */ clearBit(int n)604 @NonNull public BigInteger clearBit(int n) { 605 prepareJavaRepresentation(); 606 if (testBit(n)) { 607 return BitLevel.flipBit(this, n); 608 } else { 609 return this; 610 } 611 } 612 613 /** 614 * Returns a {@code BigInteger} which has the same binary representation 615 * as {@code this} but with the bit at position n flipped. The result is 616 * equivalent to {@code this ^ pow(2, n)}. 617 * 618 * <p><b>Implementation Note:</b> Usage of this method is not recommended as 619 * the current implementation is not efficient. 620 * 621 * @param n position where the bit in {@code this} has to be flipped. 622 * @throws ArithmeticException if {@code n < 0}. 623 */ flipBit(int n)624 @NonNull public BigInteger flipBit(int n) { 625 prepareJavaRepresentation(); 626 if (n < 0) { 627 throw new ArithmeticException("n < 0: " + n); 628 } 629 return BitLevel.flipBit(this, n); 630 } 631 632 /** 633 * Returns the position of the lowest set bit in the two's complement 634 * representation of this {@code BigInteger}. If all bits are zero (this==0) 635 * then -1 is returned as result. 636 * 637 * <p><b>Implementation Note:</b> Usage of this method is not recommended as 638 * the current implementation is not efficient. 639 */ getLowestSetBit()640 public int getLowestSetBit() { 641 prepareJavaRepresentation(); 642 if (sign == 0) { 643 return -1; 644 } 645 // (sign != 0) implies that exists some non zero digit 646 int i = getFirstNonzeroDigit(); 647 return ((i << 5) + Integer.numberOfTrailingZeros(digits[i])); 648 } 649 650 /** 651 * Returns the number of bits in the two's complement representation of 652 * {@code this} which differ from the sign bit. If {@code this} is negative, 653 * the result is equivalent to the number of bits set in the two's 654 * complement representation of {@code -this - 1}. 655 * 656 * <p>Use {@code bitLength(0)} to find the length of the binary value in 657 * bits. 658 * 659 * <p><b>Implementation Note:</b> Usage of this method is not recommended as 660 * the current implementation is not efficient. 661 */ bitCount()662 public int bitCount() { 663 prepareJavaRepresentation(); 664 return BitLevel.bitCount(this); 665 } 666 667 /** 668 * Returns a {@code BigInteger} whose value is {@code ~this}. The result 669 * of this operation is {@code -this-1}. 670 * 671 * <p><b>Implementation Note:</b> Usage of this method is not recommended as 672 * the current implementation is not efficient. 673 */ not()674 @NonNull public BigInteger not() { 675 this.prepareJavaRepresentation(); 676 return Logical.not(this); 677 } 678 679 /** 680 * Returns a {@code BigInteger} whose value is {@code this & value}. 681 * 682 * <p><b>Implementation Note:</b> Usage of this method is not recommended 683 * as the current implementation is not efficient. 684 * 685 * @param value value to be and'ed with {@code this}. 686 * @throws NullPointerException if {@code value == null}. 687 */ and(@onNull BigInteger value)688 @NonNull public BigInteger and(@NonNull BigInteger value) { 689 this.prepareJavaRepresentation(); 690 value.prepareJavaRepresentation(); 691 return Logical.and(this, value); 692 } 693 694 /** 695 * Returns a {@code BigInteger} whose value is {@code this | value}. 696 * 697 * <p><b>Implementation Note:</b> Usage of this method is not recommended as 698 * the current implementation is not efficient. 699 * 700 * @param value value to be or'ed with {@code this}. 701 * @throws NullPointerException if {@code value == null}. 702 */ or(@onNull BigInteger value)703 @NonNull public BigInteger or(@NonNull BigInteger value) { 704 this.prepareJavaRepresentation(); 705 value.prepareJavaRepresentation(); 706 return Logical.or(this, value); 707 } 708 709 /** 710 * Returns a {@code BigInteger} whose value is {@code this ^ value}. 711 * 712 * <p><b>Implementation Note:</b> Usage of this method is not recommended as 713 * the current implementation is not efficient. 714 * 715 * @param value value to be xor'ed with {@code this} 716 * @throws NullPointerException if {@code value == null} 717 */ xor(@onNull BigInteger value)718 @NonNull public BigInteger xor(@NonNull BigInteger value) { 719 this.prepareJavaRepresentation(); 720 value.prepareJavaRepresentation(); 721 return Logical.xor(this, value); 722 } 723 724 /** 725 * Returns a {@code BigInteger} whose value is {@code this & ~value}. 726 * Evaluating {@code x.andNot(value)} returns the same result as {@code 727 * x.and(value.not())}. 728 * 729 * <p><b>Implementation Note:</b> Usage of this method is not recommended 730 * as the current implementation is not efficient. 731 * 732 * @param value value to be not'ed and then and'ed with {@code this}. 733 * @throws NullPointerException if {@code value == null}. 734 */ andNot(@onNull BigInteger value)735 @NonNull public BigInteger andNot(@NonNull BigInteger value) { 736 this.prepareJavaRepresentation(); 737 value.prepareJavaRepresentation(); 738 return Logical.andNot(this, value); 739 } 740 741 /** 742 * Returns this {@code BigInteger} as an int value. If {@code this} is too 743 * big to be represented as an int, then {@code this % (1 << 32)} is 744 * returned. 745 */ 746 @Override intValue()747 public int intValue() { 748 if (nativeIsValid && bigInt.twosCompFitsIntoBytes(4)) { 749 return (int) bigInt.longInt(); 750 } 751 this.prepareJavaRepresentation(); 752 return (sign * digits[0]); 753 } 754 755 /** 756 * Returns this {@code BigInteger} as a long value. If {@code this} is too 757 * big to be represented as a long, then {@code this % pow(2, 64)} is 758 * returned. 759 */ 760 @Override longValue()761 public long longValue() { 762 if (nativeIsValid && bigInt.twosCompFitsIntoBytes(8)) { 763 return bigInt.longInt(); 764 } 765 prepareJavaRepresentation(); 766 long value = numberLength > 1 767 ? ((long) digits[1]) << 32 | digits[0] & 0xFFFFFFFFL 768 : digits[0] & 0xFFFFFFFFL; 769 return sign * value; 770 } 771 772 /** 773 * Returns this {@code BigInteger} as a float. If {@code this} is too big to 774 * be represented as a float, then {@code Float.POSITIVE_INFINITY} or 775 * {@code Float.NEGATIVE_INFINITY} is returned. Note that not all integers 776 * in the range {@code [-Float.MAX_VALUE, Float.MAX_VALUE]} can be exactly 777 * represented as a float. 778 */ 779 @Override floatValue()780 public float floatValue() { 781 return (float) doubleValue(); 782 } 783 784 /** 785 * Returns this {@code BigInteger} as a double. If {@code this} is too big 786 * to be represented as a double, then {@code Double.POSITIVE_INFINITY} or 787 * {@code Double.NEGATIVE_INFINITY} is returned. Note that not all integers 788 * in the range {@code [-Double.MAX_VALUE, Double.MAX_VALUE]} can be exactly 789 * represented as a double. 790 */ 791 @Override doubleValue()792 public double doubleValue() { 793 return Conversion.bigInteger2Double(this); 794 } 795 796 /** 797 * Compares this {@code BigInteger} with {@code value}. Returns {@code -1} 798 * if {@code this < value}, {@code 0} if {@code this == value} and {@code 1} 799 * if {@code this > value}, . 800 * 801 * @param value value to be compared with {@code this}. 802 * @throws NullPointerException if {@code value == null}. 803 */ compareTo(@onNull BigInteger value)804 public int compareTo(@NonNull BigInteger value) { 805 return BigInt.cmp(getBigInt(), value.getBigInt()); 806 } 807 808 /** 809 * Returns the minimum of this {@code BigInteger} and {@code value}. 810 * 811 * @param value value to be used to compute the minimum with {@code this}. 812 * @throws NullPointerException if {@code value == null}. 813 */ min(@onNull BigInteger value)814 @NonNull public BigInteger min(@NonNull BigInteger value) { 815 return this.compareTo(value) == -1 ? this : value; 816 } 817 818 /** 819 * Returns the maximum of this {@code BigInteger} and {@code value}. 820 * 821 * @param value value to be used to compute the maximum with {@code this} 822 * @throws NullPointerException if {@code value == null} 823 */ max(@onNull BigInteger value)824 @NonNull public BigInteger max(@NonNull BigInteger value) { 825 return this.compareTo(value) == 1 ? this : value; 826 } 827 828 @Override hashCode()829 public int hashCode() { 830 if (hashCode == 0) { 831 prepareJavaRepresentation(); 832 int hash = 0; 833 for (int i = 0; i < numberLength; ++i) { 834 hash = hash * 33 + digits[i]; 835 } 836 hashCode = hash * sign; 837 } 838 return hashCode; 839 } 840 841 @Override equals(@ullable Object x)842 public boolean equals(@Nullable Object x) { 843 if (this == x) { 844 return true; 845 } 846 if (x instanceof BigInteger) { 847 return this.compareTo((BigInteger) x) == 0; 848 } 849 return false; 850 } 851 852 /** 853 * Returns a string representation of this {@code BigInteger} in decimal 854 * form. 855 */ 856 @Override toString()857 @NonNull public String toString() { 858 return getBigInt().decString(); 859 } 860 861 /** 862 * Returns a string containing a string representation of this {@code 863 * BigInteger} with base radix. If {@code radix < Character.MIN_RADIX} or 864 * {@code radix > Character.MAX_RADIX} then a decimal representation is 865 * returned. The characters of the string representation are generated with 866 * method {@code Character.forDigit}. 867 * 868 * @param radix base to be used for the string representation. 869 */ toString(int radix)870 @NonNull public String toString(int radix) { 871 if (radix == 10) { 872 return getBigInt().decString(); 873 } else { 874 prepareJavaRepresentation(); 875 return Conversion.bigInteger2String(this, radix); 876 } 877 } 878 879 /** 880 * Returns a {@code BigInteger} whose value is greatest common divisor 881 * of {@code this} and {@code value}. If {@code this == 0} and {@code 882 * value == 0} then zero is returned, otherwise the result is positive. 883 * 884 * @param value value with which the greatest common divisor is computed. 885 * @throws NullPointerException if {@code value == null}. 886 */ gcd(@onNull BigInteger value)887 @NonNull public BigInteger gcd(@NonNull BigInteger value) { 888 // First optimize the case in which the two arguments have very different 889 // length. 890 int thisLen = bitLength(); 891 int valueLen = value.bitLength(); 892 final int gcdDirectRatio = 16; 893 if (thisLen > gcdDirectRatio * valueLen) { 894 // A division-based step reduces the length of this by a factor of at 895 // least gcdDirectRatio, thus ensuring that a division-based step will 896 // easily pay for itself. 897 if (value.signum() == 0) { 898 return this.abs(); 899 } 900 return value.gcd(this.mod(value.abs())); 901 } else if (valueLen > gcdDirectRatio * thisLen) { 902 if (signum() == 0) { 903 return value.abs(); 904 } 905 return this.gcd(value.mod(this.abs())); 906 } 907 908 return new BigInteger(BigInt.gcd(getBigInt(), value.getBigInt())); 909 } 910 911 /** 912 * Returns a {@code BigInteger} whose value is {@code this * value}. 913 * 914 * @throws NullPointerException if {@code value == null}. 915 */ multiply(@onNull BigInteger value)916 @NonNull public BigInteger multiply(@NonNull BigInteger value) { 917 return new BigInteger(BigInt.product(getBigInt(), value.getBigInt())); 918 } 919 920 /** 921 * Returns a {@code BigInteger} whose value is {@code pow(this, exp)}. 922 * 923 * @throws ArithmeticException if {@code exp < 0}. 924 */ pow(int exp)925 @NonNull public BigInteger pow(int exp) { 926 if (exp < 0) { 927 throw new ArithmeticException("exp < 0: " + exp); 928 } 929 return new BigInteger(BigInt.exp(getBigInt(), exp)); 930 } 931 932 /** 933 * Returns a two element {@code BigInteger} array containing 934 * {@code this / divisor} at index 0 and {@code this % divisor} at index 1. 935 * 936 * @param divisor value by which {@code this} is divided. 937 * @throws NullPointerException if {@code divisor == null}. 938 * @throws ArithmeticException if {@code divisor == 0}. 939 * @see #divide 940 * @see #remainder 941 */ divideAndRemainder(@onNull BigInteger divisor)942 public @NonNull BigInteger @NonNull [] divideAndRemainder(@NonNull BigInteger divisor) { 943 BigInt divisorBigInt = divisor.getBigInt(); 944 BigInt quotient = new BigInt(); 945 BigInt remainder = new BigInt(); 946 BigInt.division(getBigInt(), divisorBigInt, quotient, remainder); 947 return new BigInteger[] {new BigInteger(quotient), new BigInteger(remainder) }; 948 } 949 950 /** 951 * Returns a {@code BigInteger} whose value is {@code this / divisor}. 952 * 953 * @param divisor value by which {@code this} is divided. 954 * @return {@code this / divisor}. 955 * @throws NullPointerException if {@code divisor == null}. 956 * @throws ArithmeticException if {@code divisor == 0}. 957 */ divide(@onNull BigInteger divisor)958 @NonNull public BigInteger divide(@NonNull BigInteger divisor) { 959 BigInt quotient = new BigInt(); 960 BigInt.division(getBigInt(), divisor.getBigInt(), quotient, null); 961 return new BigInteger(quotient); 962 } 963 964 /** 965 * Returns a {@code BigInteger} whose value is {@code this % divisor}. 966 * Regarding signs this methods has the same behavior as the % operator on 967 * ints: the sign of the remainder is the same as the sign of this. 968 * 969 * @param divisor value by which {@code this} is divided. 970 * @throws NullPointerException if {@code divisor == null}. 971 * @throws ArithmeticException if {@code divisor == 0}. 972 */ remainder(@onNull BigInteger divisor)973 @NonNull public BigInteger remainder(@NonNull BigInteger divisor) { 974 BigInt remainder = new BigInt(); 975 BigInt.division(getBigInt(), divisor.getBigInt(), null, remainder); 976 return new BigInteger(remainder); 977 } 978 979 /** 980 * Returns a {@code BigInteger} whose value is {@code 1/this mod m}. The 981 * modulus {@code m} must be positive. The result is guaranteed to be in the 982 * interval {@code [0, m)} (0 inclusive, m exclusive). If {@code this} is 983 * not relatively prime to m, then an exception is thrown. 984 * 985 * @param m the modulus. 986 * @throws NullPointerException if {@code m == null} 987 * @throws ArithmeticException if {@code m < 0 or} if {@code this} is not 988 * relatively prime to {@code m} 989 */ modInverse(@onNull BigInteger m)990 @NonNull public BigInteger modInverse(@NonNull BigInteger m) { 991 if (m.signum() <= 0) { 992 throw new ArithmeticException("modulus not positive"); 993 } 994 return new BigInteger(BigInt.modInverse(getBigInt(), m.getBigInt())); 995 } 996 997 /** 998 * Returns a {@code BigInteger} whose value is {@code 999 * pow(this, exponent) mod modulus}. The modulus must be positive. The 1000 * result is guaranteed to be in the interval {@code [0, modulus)}. 1001 * If the exponent is negative, then 1002 * {@code pow(this.modInverse(modulus), -exponent) mod modulus} is computed. 1003 * The inverse of this only exists if {@code this} is relatively prime to the modulus, 1004 * otherwise an exception is thrown. 1005 * 1006 * @throws NullPointerException if {@code modulus == null} or {@code exponent == null}. 1007 * @throws ArithmeticException if {@code modulus < 0} or if {@code exponent < 0} and 1008 * not relatively prime to {@code modulus}. 1009 */ modPow(@onNull BigInteger exponent, @NonNull BigInteger modulus)1010 @NonNull public BigInteger modPow(@NonNull BigInteger exponent, @NonNull BigInteger modulus) { 1011 if (modulus.signum() <= 0) { 1012 throw new ArithmeticException("modulus.signum() <= 0"); 1013 } 1014 int exponentSignum = exponent.signum(); 1015 if (exponentSignum == 0) { // OpenSSL gets this case wrong; http://b/8574367. 1016 return ONE.mod(modulus); 1017 } 1018 BigInteger base = exponentSignum < 0 ? modInverse(modulus) : this; 1019 return new BigInteger(BigInt.modExp(base.getBigInt(), exponent.getBigInt(), modulus.getBigInt())); 1020 } 1021 1022 /** 1023 * Returns a {@code BigInteger} whose value is {@code this mod m}. The 1024 * modulus {@code m} must be positive. The result is guaranteed to be in the 1025 * interval {@code [0, m)} (0 inclusive, m exclusive). The behavior of this 1026 * function is not equivalent to the behavior of the % operator defined for 1027 * the built-in {@code int}'s. 1028 * 1029 * @param m the modulus. 1030 * @return {@code this mod m}. 1031 * @throws NullPointerException if {@code m == null}. 1032 * @throws ArithmeticException if {@code m < 0}. 1033 */ 1034 @NonNull public BigInteger mod(@NonNull BigInteger m) { 1035 if (m.signum() <= 0) { 1036 throw new ArithmeticException("m.signum() <= 0"); 1037 } 1038 return new BigInteger(BigInt.modulus(getBigInt(), m.getBigInt())); 1039 } 1040 1041 /** 1042 * Tests whether this {@code BigInteger} is probably prime. If {@code true} 1043 * is returned, then this is prime with a probability greater than 1044 * {@code 1 - 1/2<sup>certainty</sup>)}. If {@code false} is returned, then this 1045 * is definitely composite. If the argument {@code certainty} <= 0, then 1046 * this method returns true. 1047 * 1048 * @param certainty tolerated primality uncertainty. 1049 * @return {@code true}, if {@code this} is probably prime, {@code false} 1050 * otherwise. 1051 */ 1052 public boolean isProbablePrime(int certainty) { 1053 if (certainty <= 0) { 1054 return true; 1055 } 1056 return getBigInt().isPrime(certainty); 1057 } 1058 1059 /** 1060 * Returns the smallest integer x > {@code this} which is probably prime as 1061 * a {@code BigInteger} instance. The probability that the returned {@code 1062 * BigInteger} is prime is greater than {@code 1 - 1/2<sup>100</sup>}. 1063 * 1064 * @return smallest integer > {@code this} which is probably prime. 1065 * @throws ArithmeticException if {@code this < 0}. 1066 */ 1067 @NonNull public BigInteger nextProbablePrime() { 1068 if (sign < 0) { 1069 throw new ArithmeticException("sign < 0"); 1070 } 1071 return Primality.nextProbablePrime(this); 1072 } 1073 1074 /** 1075 * Returns a random positive {@code BigInteger} instance in the range {@code 1076 * [0, pow(2, bitLength)-1]} which is probably prime. The probability that 1077 * the returned {@code BigInteger} is prime is greater than {@code 1 - 1/2<sup>100</sup>)}. 1078 * 1079 * @param bitLength length of the new {@code BigInteger} in bits. 1080 * @return probably prime random {@code BigInteger} instance. 1081 * @throws IllegalArgumentException if {@code bitLength < 2}. 1082 */ 1083 @NonNull public static BigInteger probablePrime(int bitLength, @NonNull Random random) { 1084 return new BigInteger(bitLength, 100, random); 1085 } 1086 1087 /* Private Methods */ 1088 1089 /** 1090 * Returns the two's complement representation of this BigInteger in a byte 1091 * array. 1092 */ 1093 private byte[] twosComplement() { 1094 prepareJavaRepresentation(); 1095 if (this.sign == 0) { 1096 return new byte[] { 0 }; 1097 } 1098 BigInteger temp = this; 1099 int bitLen = bitLength(); 1100 int iThis = getFirstNonzeroDigit(); 1101 int bytesLen = (bitLen >> 3) + 1; 1102 /* Puts the little-endian int array representing the magnitude 1103 * of this BigInteger into the big-endian byte array. */ 1104 byte[] bytes = new byte[bytesLen]; 1105 int firstByteNumber = 0; 1106 int highBytes; 1107 int bytesInInteger = 4; 1108 int hB; 1109 1110 if (bytesLen - (numberLength << 2) == 1) { 1111 bytes[0] = (byte) ((sign < 0) ? -1 : 0); 1112 highBytes = 4; 1113 firstByteNumber++; 1114 } else { 1115 hB = bytesLen & 3; 1116 highBytes = (hB == 0) ? 4 : hB; 1117 } 1118 1119 int digitIndex = iThis; 1120 bytesLen -= iThis << 2; 1121 1122 if (sign < 0) { 1123 int digit = -temp.digits[digitIndex]; 1124 digitIndex++; 1125 if (digitIndex == numberLength) { 1126 bytesInInteger = highBytes; 1127 } 1128 for (int i = 0; i < bytesInInteger; i++, digit >>= 8) { 1129 bytes[--bytesLen] = (byte) digit; 1130 } 1131 while (bytesLen > firstByteNumber) { 1132 digit = ~temp.digits[digitIndex]; 1133 digitIndex++; 1134 if (digitIndex == numberLength) { 1135 bytesInInteger = highBytes; 1136 } 1137 for (int i = 0; i < bytesInInteger; i++, digit >>= 8) { 1138 bytes[--bytesLen] = (byte) digit; 1139 } 1140 } 1141 } else { 1142 while (bytesLen > firstByteNumber) { 1143 int digit = temp.digits[digitIndex]; 1144 digitIndex++; 1145 if (digitIndex == numberLength) { 1146 bytesInInteger = highBytes; 1147 } 1148 for (int i = 0; i < bytesInInteger; i++, digit >>= 8) { 1149 bytes[--bytesLen] = (byte) digit; 1150 } 1151 } 1152 } 1153 return bytes; 1154 } 1155 1156 1157 static int multiplyByInt(int[] res, int[] a, int aSize, int factor) { 1158 long carry = 0; 1159 1160 for (int i = 0; i < aSize; i++) { 1161 carry += (a[i] & 0xFFFFFFFFL) * (factor & 0xFFFFFFFFL); 1162 res[i] = (int) carry; 1163 carry >>>= 32; 1164 } 1165 return (int) carry; 1166 } 1167 1168 static int inplaceAdd(int[] a, int aSize, int addend) { 1169 long carry = addend & 0xFFFFFFFFL; 1170 1171 for (int i = 0; (carry != 0) && (i < aSize); i++) { 1172 carry += a[i] & 0xFFFFFFFFL; 1173 a[i] = (int) carry; 1174 carry >>= 32; 1175 } 1176 return (int) carry; 1177 } 1178 1179 /** @see BigInteger#BigInteger(String, int) */ parseFromString(BigInteger bi, String value, int radix)1180 private static void parseFromString(BigInteger bi, String value, int radix) { 1181 int stringLength = value.length(); 1182 int endChar = stringLength; 1183 1184 int sign; 1185 int startChar; 1186 if (value.charAt(0) == '-') { 1187 sign = -1; 1188 startChar = 1; 1189 stringLength--; 1190 } else { 1191 sign = 1; 1192 startChar = 0; 1193 } 1194 1195 /* 1196 * We use the following algorithm: split a string into portions of n 1197 * characters and convert each portion to an integer according to the 1198 * radix. Then convert an pow(radix, n) based number to binary using the 1199 * multiplication method. See D. Knuth, The Art of Computer Programming, 1200 * vol. 2. 1201 */ 1202 1203 int charsPerInt = Conversion.digitFitInInt[radix]; 1204 int bigRadixDigitsLength = stringLength / charsPerInt; 1205 int topChars = stringLength % charsPerInt; 1206 1207 if (topChars != 0) { 1208 bigRadixDigitsLength++; 1209 } 1210 int[] digits = new int[bigRadixDigitsLength]; 1211 // Get the maximal power of radix that fits in int 1212 int bigRadix = Conversion.bigRadices[radix - 2]; 1213 // Parse an input string and accumulate the BigInteger's magnitude 1214 int digitIndex = 0; // index of digits array 1215 int substrEnd = startChar + ((topChars == 0) ? charsPerInt : topChars); 1216 1217 for (int substrStart = startChar; substrStart < endChar; 1218 substrStart = substrEnd, substrEnd = substrStart + charsPerInt) { 1219 int bigRadixDigit = Integer.parseInt(value.substring(substrStart, substrEnd), radix); 1220 int newDigit = multiplyByInt(digits, digits, digitIndex, bigRadix); 1221 newDigit += inplaceAdd(digits, digitIndex, bigRadixDigit); 1222 digits[digitIndex++] = newDigit; 1223 } 1224 int numberLength = digitIndex; 1225 bi.setJavaRepresentation(sign, numberLength, digits); 1226 } 1227 getFirstNonzeroDigit()1228 int getFirstNonzeroDigit() { 1229 if (firstNonzeroDigit == -2) { 1230 int i; 1231 if (this.sign == 0) { 1232 i = -1; 1233 } else { 1234 for (i = 0; digits[i] == 0; i++) { 1235 ; 1236 } 1237 } 1238 firstNonzeroDigit = i; 1239 } 1240 return firstNonzeroDigit; 1241 } 1242 1243 /** 1244 * Returns a copy of the current instance to achieve immutability 1245 */ copy()1246 BigInteger copy() { 1247 prepareJavaRepresentation(); 1248 int[] copyDigits = new int[numberLength]; 1249 System.arraycopy(digits, 0, copyDigits, 0, numberLength); 1250 return new BigInteger(sign, numberLength, copyDigits); 1251 } 1252 1253 /** 1254 * Assigns all transient fields upon deserialization of a {@code BigInteger} 1255 * instance. 1256 */ readObject(ObjectInputStream in)1257 private void readObject(ObjectInputStream in) 1258 throws IOException, ClassNotFoundException { 1259 in.defaultReadObject(); 1260 BigInt bigInt = new BigInt(); 1261 bigInt.putBigEndian(magnitude, signum < 0); 1262 setBigInt(bigInt); 1263 } 1264 1265 /** 1266 * Prepares this {@code BigInteger} for serialization, i.e. the 1267 * non-transient fields {@code signum} and {@code magnitude} are assigned. 1268 */ writeObject(ObjectOutputStream out)1269 private void writeObject(ObjectOutputStream out) throws IOException { 1270 BigInt bigInt = getBigInt(); 1271 signum = bigInt.sign(); 1272 magnitude = bigInt.bigEndianMagnitude(); 1273 out.defaultWriteObject(); 1274 } 1275 } 1276