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