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 return new BigInteger(BigInt.gcd(getBigInt(), value.getBigInt())); 889 } 890 891 /** 892 * Returns a {@code BigInteger} whose value is {@code this * value}. 893 * 894 * @throws NullPointerException if {@code value == null}. 895 */ multiply(@onNull BigInteger value)896 @NonNull public BigInteger multiply(@NonNull BigInteger value) { 897 return new BigInteger(BigInt.product(getBigInt(), value.getBigInt())); 898 } 899 900 /** 901 * Returns a {@code BigInteger} whose value is {@code pow(this, exp)}. 902 * 903 * @throws ArithmeticException if {@code exp < 0}. 904 */ pow(int exp)905 @NonNull public BigInteger pow(int exp) { 906 if (exp < 0) { 907 throw new ArithmeticException("exp < 0: " + exp); 908 } 909 return new BigInteger(BigInt.exp(getBigInt(), exp)); 910 } 911 912 /** 913 * Returns a two element {@code BigInteger} array containing 914 * {@code this / divisor} at index 0 and {@code this % divisor} at index 1. 915 * 916 * @param divisor value by which {@code this} is divided. 917 * @throws NullPointerException if {@code divisor == null}. 918 * @throws ArithmeticException if {@code divisor == 0}. 919 * @see #divide 920 * @see #remainder 921 */ divideAndRemainder(@onNull BigInteger divisor)922 public @NonNull BigInteger @NonNull [] divideAndRemainder(@NonNull BigInteger divisor) { 923 BigInt divisorBigInt = divisor.getBigInt(); 924 BigInt quotient = new BigInt(); 925 BigInt remainder = new BigInt(); 926 BigInt.division(getBigInt(), divisorBigInt, quotient, remainder); 927 return new BigInteger[] {new BigInteger(quotient), new BigInteger(remainder) }; 928 } 929 930 /** 931 * Returns a {@code BigInteger} whose value is {@code this / divisor}. 932 * 933 * @param divisor value by which {@code this} is divided. 934 * @return {@code this / divisor}. 935 * @throws NullPointerException if {@code divisor == null}. 936 * @throws ArithmeticException if {@code divisor == 0}. 937 */ divide(@onNull BigInteger divisor)938 @NonNull public BigInteger divide(@NonNull BigInteger divisor) { 939 BigInt quotient = new BigInt(); 940 BigInt.division(getBigInt(), divisor.getBigInt(), quotient, null); 941 return new BigInteger(quotient); 942 } 943 944 /** 945 * Returns a {@code BigInteger} whose value is {@code this % divisor}. 946 * Regarding signs this methods has the same behavior as the % operator on 947 * ints: the sign of the remainder is the same as the sign of this. 948 * 949 * @param divisor value by which {@code this} is divided. 950 * @throws NullPointerException if {@code divisor == null}. 951 * @throws ArithmeticException if {@code divisor == 0}. 952 */ remainder(@onNull BigInteger divisor)953 @NonNull public BigInteger remainder(@NonNull BigInteger divisor) { 954 BigInt remainder = new BigInt(); 955 BigInt.division(getBigInt(), divisor.getBigInt(), null, remainder); 956 return new BigInteger(remainder); 957 } 958 959 /** 960 * Returns a {@code BigInteger} whose value is {@code 1/this mod m}. The 961 * modulus {@code m} must be positive. The result is guaranteed to be in the 962 * interval {@code [0, m)} (0 inclusive, m exclusive). If {@code this} is 963 * not relatively prime to m, then an exception is thrown. 964 * 965 * @param m the modulus. 966 * @throws NullPointerException if {@code m == null} 967 * @throws ArithmeticException if {@code m < 0 or} if {@code this} is not 968 * relatively prime to {@code m} 969 */ modInverse(@onNull BigInteger m)970 @NonNull public BigInteger modInverse(@NonNull BigInteger m) { 971 if (m.signum() <= 0) { 972 throw new ArithmeticException("modulus not positive"); 973 } 974 return new BigInteger(BigInt.modInverse(getBigInt(), m.getBigInt())); 975 } 976 977 /** 978 * Returns a {@code BigInteger} whose value is {@code 979 * pow(this, exponent) mod modulus}. The modulus must be positive. The 980 * result is guaranteed to be in the interval {@code [0, modulus)}. 981 * If the exponent is negative, then 982 * {@code pow(this.modInverse(modulus), -exponent) mod modulus} is computed. 983 * The inverse of this only exists if {@code this} is relatively prime to the modulus, 984 * otherwise an exception is thrown. 985 * 986 * @throws NullPointerException if {@code modulus == null} or {@code exponent == null}. 987 * @throws ArithmeticException if {@code modulus < 0} or if {@code exponent < 0} and 988 * not relatively prime to {@code modulus}. 989 */ modPow(@onNull BigInteger exponent, @NonNull BigInteger modulus)990 @NonNull public BigInteger modPow(@NonNull BigInteger exponent, @NonNull BigInteger modulus) { 991 if (modulus.signum() <= 0) { 992 throw new ArithmeticException("modulus.signum() <= 0"); 993 } 994 int exponentSignum = exponent.signum(); 995 if (exponentSignum == 0) { // OpenSSL gets this case wrong; http://b/8574367. 996 return ONE.mod(modulus); 997 } 998 BigInteger base = exponentSignum < 0 ? modInverse(modulus) : this; 999 return new BigInteger(BigInt.modExp(base.getBigInt(), exponent.getBigInt(), modulus.getBigInt())); 1000 } 1001 1002 /** 1003 * Returns a {@code BigInteger} whose value is {@code this mod m}. The 1004 * modulus {@code m} must be positive. The result is guaranteed to be in the 1005 * interval {@code [0, m)} (0 inclusive, m exclusive). The behavior of this 1006 * function is not equivalent to the behavior of the % operator defined for 1007 * the built-in {@code int}'s. 1008 * 1009 * @param m the modulus. 1010 * @return {@code this mod m}. 1011 * @throws NullPointerException if {@code m == null}. 1012 * @throws ArithmeticException if {@code m < 0}. 1013 */ 1014 @NonNull public BigInteger mod(@NonNull BigInteger m) { 1015 if (m.signum() <= 0) { 1016 throw new ArithmeticException("m.signum() <= 0"); 1017 } 1018 return new BigInteger(BigInt.modulus(getBigInt(), m.getBigInt())); 1019 } 1020 1021 /** 1022 * Tests whether this {@code BigInteger} is probably prime. If {@code true} 1023 * is returned, then this is prime with a probability greater than 1024 * {@code 1 - 1/2<sup>certainty</sup>)}. If {@code false} is returned, then this 1025 * is definitely composite. If the argument {@code certainty} <= 0, then 1026 * this method returns true. 1027 * 1028 * @param certainty tolerated primality uncertainty. 1029 * @return {@code true}, if {@code this} is probably prime, {@code false} 1030 * otherwise. 1031 */ 1032 public boolean isProbablePrime(int certainty) { 1033 if (certainty <= 0) { 1034 return true; 1035 } 1036 return getBigInt().isPrime(certainty); 1037 } 1038 1039 /** 1040 * Returns the smallest integer x > {@code this} which is probably prime as 1041 * a {@code BigInteger} instance. The probability that the returned {@code 1042 * BigInteger} is prime is greater than {@code 1 - 1/2<sup>100</sup>}. 1043 * 1044 * @return smallest integer > {@code this} which is probably prime. 1045 * @throws ArithmeticException if {@code this < 0}. 1046 */ 1047 @NonNull public BigInteger nextProbablePrime() { 1048 if (sign < 0) { 1049 throw new ArithmeticException("sign < 0"); 1050 } 1051 return Primality.nextProbablePrime(this); 1052 } 1053 1054 /** 1055 * Returns a random positive {@code BigInteger} instance in the range {@code 1056 * [0, pow(2, bitLength)-1]} which is probably prime. The probability that 1057 * the returned {@code BigInteger} is prime is greater than {@code 1 - 1/2<sup>100</sup>)}. 1058 * 1059 * @param bitLength length of the new {@code BigInteger} in bits. 1060 * @return probably prime random {@code BigInteger} instance. 1061 * @throws IllegalArgumentException if {@code bitLength < 2}. 1062 */ 1063 @NonNull public static BigInteger probablePrime(int bitLength, @NonNull Random random) { 1064 return new BigInteger(bitLength, 100, random); 1065 } 1066 1067 /* Private Methods */ 1068 1069 /** 1070 * Returns the two's complement representation of this BigInteger in a byte 1071 * array. 1072 */ 1073 private byte[] twosComplement() { 1074 prepareJavaRepresentation(); 1075 if (this.sign == 0) { 1076 return new byte[] { 0 }; 1077 } 1078 BigInteger temp = this; 1079 int bitLen = bitLength(); 1080 int iThis = getFirstNonzeroDigit(); 1081 int bytesLen = (bitLen >> 3) + 1; 1082 /* Puts the little-endian int array representing the magnitude 1083 * of this BigInteger into the big-endian byte array. */ 1084 byte[] bytes = new byte[bytesLen]; 1085 int firstByteNumber = 0; 1086 int highBytes; 1087 int bytesInInteger = 4; 1088 int hB; 1089 1090 if (bytesLen - (numberLength << 2) == 1) { 1091 bytes[0] = (byte) ((sign < 0) ? -1 : 0); 1092 highBytes = 4; 1093 firstByteNumber++; 1094 } else { 1095 hB = bytesLen & 3; 1096 highBytes = (hB == 0) ? 4 : hB; 1097 } 1098 1099 int digitIndex = iThis; 1100 bytesLen -= iThis << 2; 1101 1102 if (sign < 0) { 1103 int digit = -temp.digits[digitIndex]; 1104 digitIndex++; 1105 if (digitIndex == numberLength) { 1106 bytesInInteger = highBytes; 1107 } 1108 for (int i = 0; i < bytesInInteger; i++, digit >>= 8) { 1109 bytes[--bytesLen] = (byte) digit; 1110 } 1111 while (bytesLen > firstByteNumber) { 1112 digit = ~temp.digits[digitIndex]; 1113 digitIndex++; 1114 if (digitIndex == numberLength) { 1115 bytesInInteger = highBytes; 1116 } 1117 for (int i = 0; i < bytesInInteger; i++, digit >>= 8) { 1118 bytes[--bytesLen] = (byte) digit; 1119 } 1120 } 1121 } else { 1122 while (bytesLen > firstByteNumber) { 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 } 1132 } 1133 return bytes; 1134 } 1135 1136 1137 static int multiplyByInt(int[] res, int[] a, int aSize, int factor) { 1138 long carry = 0; 1139 1140 for (int i = 0; i < aSize; i++) { 1141 carry += (a[i] & 0xFFFFFFFFL) * (factor & 0xFFFFFFFFL); 1142 res[i] = (int) carry; 1143 carry >>>= 32; 1144 } 1145 return (int) carry; 1146 } 1147 1148 static int inplaceAdd(int[] a, int aSize, int addend) { 1149 long carry = addend & 0xFFFFFFFFL; 1150 1151 for (int i = 0; (carry != 0) && (i < aSize); i++) { 1152 carry += a[i] & 0xFFFFFFFFL; 1153 a[i] = (int) carry; 1154 carry >>= 32; 1155 } 1156 return (int) carry; 1157 } 1158 1159 /** @see BigInteger#BigInteger(String, int) */ parseFromString(BigInteger bi, String value, int radix)1160 private static void parseFromString(BigInteger bi, String value, int radix) { 1161 int stringLength = value.length(); 1162 int endChar = stringLength; 1163 1164 int sign; 1165 int startChar; 1166 if (value.charAt(0) == '-') { 1167 sign = -1; 1168 startChar = 1; 1169 stringLength--; 1170 } else { 1171 sign = 1; 1172 startChar = 0; 1173 } 1174 1175 /* 1176 * We use the following algorithm: split a string into portions of n 1177 * characters and convert each portion to an integer according to the 1178 * radix. Then convert an pow(radix, n) based number to binary using the 1179 * multiplication method. See D. Knuth, The Art of Computer Programming, 1180 * vol. 2. 1181 */ 1182 1183 int charsPerInt = Conversion.digitFitInInt[radix]; 1184 int bigRadixDigitsLength = stringLength / charsPerInt; 1185 int topChars = stringLength % charsPerInt; 1186 1187 if (topChars != 0) { 1188 bigRadixDigitsLength++; 1189 } 1190 int[] digits = new int[bigRadixDigitsLength]; 1191 // Get the maximal power of radix that fits in int 1192 int bigRadix = Conversion.bigRadices[radix - 2]; 1193 // Parse an input string and accumulate the BigInteger's magnitude 1194 int digitIndex = 0; // index of digits array 1195 int substrEnd = startChar + ((topChars == 0) ? charsPerInt : topChars); 1196 1197 for (int substrStart = startChar; substrStart < endChar; 1198 substrStart = substrEnd, substrEnd = substrStart + charsPerInt) { 1199 int bigRadixDigit = Integer.parseInt(value.substring(substrStart, substrEnd), radix); 1200 int newDigit = multiplyByInt(digits, digits, digitIndex, bigRadix); 1201 newDigit += inplaceAdd(digits, digitIndex, bigRadixDigit); 1202 digits[digitIndex++] = newDigit; 1203 } 1204 int numberLength = digitIndex; 1205 bi.setJavaRepresentation(sign, numberLength, digits); 1206 } 1207 getFirstNonzeroDigit()1208 int getFirstNonzeroDigit() { 1209 if (firstNonzeroDigit == -2) { 1210 int i; 1211 if (this.sign == 0) { 1212 i = -1; 1213 } else { 1214 for (i = 0; digits[i] == 0; i++) { 1215 ; 1216 } 1217 } 1218 firstNonzeroDigit = i; 1219 } 1220 return firstNonzeroDigit; 1221 } 1222 1223 /** 1224 * Returns a copy of the current instance to achieve immutability 1225 */ copy()1226 BigInteger copy() { 1227 prepareJavaRepresentation(); 1228 int[] copyDigits = new int[numberLength]; 1229 System.arraycopy(digits, 0, copyDigits, 0, numberLength); 1230 return new BigInteger(sign, numberLength, copyDigits); 1231 } 1232 1233 /** 1234 * Assigns all transient fields upon deserialization of a {@code BigInteger} 1235 * instance. 1236 */ readObject(ObjectInputStream in)1237 private void readObject(ObjectInputStream in) 1238 throws IOException, ClassNotFoundException { 1239 in.defaultReadObject(); 1240 BigInt bigInt = new BigInt(); 1241 bigInt.putBigEndian(magnitude, signum < 0); 1242 setBigInt(bigInt); 1243 } 1244 1245 /** 1246 * Prepares this {@code BigInteger} for serialization, i.e. the 1247 * non-transient fields {@code signum} and {@code magnitude} are assigned. 1248 */ writeObject(ObjectOutputStream out)1249 private void writeObject(ObjectOutputStream out) throws IOException { 1250 BigInt bigInt = getBigInt(); 1251 signum = bigInt.sign(); 1252 magnitude = bigInt.bigEndianMagnitude(); 1253 out.defaultWriteObject(); 1254 } 1255 } 1256