1 /* 2 * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /* 27 * Portions Copyright (c) 1995 Colin Plumb. All rights reserved. 28 */ 29 30 package java.math; 31 32 import java.io.IOException; 33 import java.io.ObjectInputStream; 34 import java.io.ObjectOutputStream; 35 import java.io.ObjectStreamField; 36 import java.util.Arrays; 37 import java.util.Random; 38 import java.util.concurrent.ThreadLocalRandom; 39 import libcore.math.NativeBN; 40 import sun.misc.DoubleConsts; 41 import sun.misc.FloatConsts; 42 import libcore.util.NonNull; 43 44 /** 45 * Immutable arbitrary-precision integers. All operations behave as if 46 * BigIntegers were represented in two's-complement notation (like Java's 47 * primitive integer types). BigInteger provides analogues to all of Java's 48 * primitive integer operators, and all relevant methods from java.lang.Math. 49 * Additionally, BigInteger provides operations for modular arithmetic, GCD 50 * calculation, primality testing, prime generation, bit manipulation, 51 * and a few other miscellaneous operations. 52 * 53 * <p>Semantics of arithmetic operations exactly mimic those of Java's integer 54 * arithmetic operators, as defined in <i>The Java Language Specification</i>. 55 * For example, division by zero throws an {@code ArithmeticException}, and 56 * division of a negative by a positive yields a negative (or zero) remainder. 57 * All of the details in the Spec concerning overflow are ignored, as 58 * BigIntegers are made as large as necessary to accommodate the results of an 59 * operation. 60 * 61 * <p>Semantics of shift operations extend those of Java's shift operators 62 * to allow for negative shift distances. A right-shift with a negative 63 * shift distance results in a left shift, and vice-versa. The unsigned 64 * right shift operator ({@code >>>}) is omitted, as this operation makes 65 * little sense in combination with the "infinite word size" abstraction 66 * provided by this class. 67 * 68 * <p>Semantics of bitwise logical operations exactly mimic those of Java's 69 * bitwise integer operators. The binary operators ({@code and}, 70 * {@code or}, {@code xor}) implicitly perform sign extension on the shorter 71 * of the two operands prior to performing the operation. 72 * 73 * <p>Comparison operations perform signed integer comparisons, analogous to 74 * those performed by Java's relational and equality operators. 75 * 76 * <p>Modular arithmetic operations are provided to compute residues, perform 77 * exponentiation, and compute multiplicative inverses. These methods always 78 * return a non-negative result, between {@code 0} and {@code (modulus - 1)}, 79 * inclusive. 80 * 81 * <p>Bit operations operate on a single bit of the two's-complement 82 * representation of their operand. If necessary, the operand is sign- 83 * extended so that it contains the designated bit. None of the single-bit 84 * operations can produce a BigInteger with a different sign from the 85 * BigInteger being operated on, as they affect only a single bit, and the 86 * "infinite word size" abstraction provided by this class ensures that there 87 * are infinitely many "virtual sign bits" preceding each BigInteger. 88 * 89 * <p>For the sake of brevity and clarity, pseudo-code is used throughout the 90 * descriptions of BigInteger methods. The pseudo-code expression 91 * {@code (i + j)} is shorthand for "a BigInteger whose value is 92 * that of the BigInteger {@code i} plus that of the BigInteger {@code j}." 93 * The pseudo-code expression {@code (i == j)} is shorthand for 94 * "{@code true} if and only if the BigInteger {@code i} represents the same 95 * value as the BigInteger {@code j}." Other pseudo-code expressions are 96 * interpreted similarly. 97 * 98 * <p>All methods and constructors in this class throw 99 * {@code NullPointerException} when passed 100 * a null object reference for any input parameter. 101 * 102 * BigInteger must support values in the range 103 * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to 104 * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) 105 * and may support values outside of that range. 106 * 107 * The range of probable prime values is limited and may be less than 108 * the full supported positive range of {@code BigInteger}. 109 * The range must be at least 1 to 2<sup>500000000</sup>. 110 * 111 * @implNote 112 * BigInteger constructors and operations throw {@code ArithmeticException} when 113 * the result is out of the supported range of 114 * -2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive) to 115 * +2<sup>{@code Integer.MAX_VALUE}</sup> (exclusive). 116 * 117 * @see BigDecimal 118 * @author Josh Bloch 119 * @author Michael McCloskey 120 * @author Alan Eliasen 121 * @author Timothy Buktu 122 * @since JDK1.1 123 */ 124 125 public class BigInteger extends Number implements Comparable<BigInteger> { 126 // Android-changed: Added @NonNull annotations. 127 128 /** 129 * The signum of this BigInteger: -1 for negative, 0 for zero, or 130 * 1 for positive. Note that the BigInteger zero <i>must</i> have 131 * a signum of 0. This is necessary to ensures that there is exactly one 132 * representation for each BigInteger value. 133 * 134 * @serial 135 */ 136 final int signum; 137 138 /** 139 * The magnitude of this BigInteger, in <i>big-endian</i> order: the 140 * zeroth element of this array is the most-significant int of the 141 * magnitude. The magnitude must be "minimal" in that the most-significant 142 * int ({@code mag[0]}) must be non-zero. This is necessary to 143 * ensure that there is exactly one representation for each BigInteger 144 * value. Note that this implies that the BigInteger zero has a 145 * zero-length mag array. 146 */ 147 final int[] mag; 148 149 // These "redundant fields" are initialized with recognizable nonsense 150 // values, and cached the first time they are needed (or never, if they 151 // aren't needed). 152 153 /** 154 * One plus the bitCount of this BigInteger. Zeros means uninitialized. 155 * 156 * @serial 157 * @see #bitCount 158 * @deprecated Deprecated since logical value is offset from stored 159 * value and correction factor is applied in accessor method. 160 */ 161 @Deprecated 162 private int bitCount; 163 164 /** 165 * One plus the bitLength of this BigInteger. Zeros means uninitialized. 166 * (either value is acceptable). 167 * 168 * @serial 169 * @see #bitLength() 170 * @deprecated Deprecated since logical value is offset from stored 171 * value and correction factor is applied in accessor method. 172 */ 173 @Deprecated 174 private int bitLength; 175 176 /** 177 * Two plus the lowest set bit of this BigInteger, as returned by 178 * getLowestSetBit(). 179 * 180 * @serial 181 * @see #getLowestSetBit 182 * @deprecated Deprecated since logical value is offset from stored 183 * value and correction factor is applied in accessor method. 184 */ 185 @Deprecated 186 private int lowestSetBit; 187 188 /** 189 * Two plus the index of the lowest-order int in the magnitude of this 190 * BigInteger that contains a nonzero int, or -2 (either value is acceptable). 191 * The least significant int has int-number 0, the next int in order of 192 * increasing significance has int-number 1, and so forth. 193 * @deprecated Deprecated since logical value is offset from stored 194 * value and correction factor is applied in accessor method. 195 */ 196 @Deprecated 197 private int firstNonzeroIntNum; 198 199 /** 200 * This mask is used to obtain the value of an int as if it were unsigned. 201 */ 202 final static long LONG_MASK = 0xffffffffL; 203 204 /** 205 * This constant limits {@code mag.length} of BigIntegers to the supported 206 * range. 207 */ 208 private static final int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26) 209 210 /** 211 * Bit lengths larger than this constant can cause overflow in searchLen 212 * calculation and in BitSieve.singleSearch method. 213 */ 214 private static final int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000; 215 216 /** 217 * The threshold value for using Karatsuba multiplication. If the number 218 * of ints in both mag arrays are greater than this number, then 219 * Karatsuba multiplication will be used. This value is found 220 * experimentally to work well. 221 */ 222 private static final int KARATSUBA_THRESHOLD = 80; 223 224 /** 225 * The threshold value for using 3-way Toom-Cook multiplication. 226 * If the number of ints in each mag array is greater than the 227 * Karatsuba threshold, and the number of ints in at least one of 228 * the mag arrays is greater than this threshold, then Toom-Cook 229 * multiplication will be used. 230 */ 231 private static final int TOOM_COOK_THRESHOLD = 240; 232 233 /** 234 * The threshold value for using Karatsuba squaring. If the number 235 * of ints in the number are larger than this value, 236 * Karatsuba squaring will be used. This value is found 237 * experimentally to work well. 238 */ 239 private static final int KARATSUBA_SQUARE_THRESHOLD = 128; 240 241 /** 242 * The threshold value for using Toom-Cook squaring. If the number 243 * of ints in the number are larger than this value, 244 * Toom-Cook squaring will be used. This value is found 245 * experimentally to work well. 246 */ 247 private static final int TOOM_COOK_SQUARE_THRESHOLD = 216; 248 249 /** 250 * The threshold value for using Burnikel-Ziegler division. If the number 251 * of ints in the divisor are larger than this value, Burnikel-Ziegler 252 * division may be used. This value is found experimentally to work well. 253 */ 254 static final int BURNIKEL_ZIEGLER_THRESHOLD = 80; 255 256 /** 257 * The offset value for using Burnikel-Ziegler division. If the number 258 * of ints in the divisor exceeds the Burnikel-Ziegler threshold, and the 259 * number of ints in the dividend is greater than the number of ints in the 260 * divisor plus this value, Burnikel-Ziegler division will be used. This 261 * value is found experimentally to work well. 262 */ 263 static final int BURNIKEL_ZIEGLER_OFFSET = 40; 264 265 /** 266 * The threshold value for using Schoenhage recursive base conversion. If 267 * the number of ints in the number are larger than this value, 268 * the Schoenhage algorithm will be used. In practice, it appears that the 269 * Schoenhage routine is faster for any threshold down to 2, and is 270 * relatively flat for thresholds between 2-25, so this choice may be 271 * varied within this range for very small effect. 272 */ 273 private static final int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20; 274 275 /** 276 * The threshold value for using squaring code to perform multiplication 277 * of a {@code BigInteger} instance by itself. If the number of ints in 278 * the number are larger than this value, {@code multiply(this)} will 279 * return {@code square()}. 280 */ 281 private static final int MULTIPLY_SQUARE_THRESHOLD = 20; 282 283 /** 284 * The threshold for using an intrinsic version of 285 * implMontgomeryXXX to perform Montgomery multiplication. If the 286 * number of ints in the number is more than this value we do not 287 * use the intrinsic. 288 */ 289 private static final int MONTGOMERY_INTRINSIC_THRESHOLD = 512; 290 291 292 // Constructors 293 294 /** 295 * Translates a byte array containing the two's-complement binary 296 * representation of a BigInteger into a BigInteger. The input array is 297 * assumed to be in <i>big-endian</i> byte-order: the most significant 298 * byte is in the zeroth element. 299 * 300 * @param val big-endian two's-complement binary representation of 301 * BigInteger. 302 * @throws NumberFormatException {@code val} is zero bytes long. 303 */ BigInteger(byte[] val)304 public BigInteger(byte[] val) { 305 if (val.length == 0) 306 throw new NumberFormatException("Zero length BigInteger"); 307 308 if (val[0] < 0) { 309 mag = makePositive(val); 310 signum = -1; 311 } else { 312 mag = stripLeadingZeroBytes(val); 313 signum = (mag.length == 0 ? 0 : 1); 314 } 315 if (mag.length >= MAX_MAG_LENGTH) { 316 checkRange(); 317 } 318 } 319 320 /** 321 * This private constructor translates an int array containing the 322 * two's-complement binary representation of a BigInteger into a 323 * BigInteger. The input array is assumed to be in <i>big-endian</i> 324 * int-order: the most significant int is in the zeroth element. 325 */ BigInteger(int[] val)326 private BigInteger(int[] val) { 327 if (val.length == 0) 328 throw new NumberFormatException("Zero length BigInteger"); 329 330 if (val[0] < 0) { 331 mag = makePositive(val); 332 signum = -1; 333 } else { 334 mag = trustedStripLeadingZeroInts(val); 335 signum = (mag.length == 0 ? 0 : 1); 336 } 337 if (mag.length >= MAX_MAG_LENGTH) { 338 checkRange(); 339 } 340 } 341 342 /** 343 * Translates the sign-magnitude representation of a BigInteger into a 344 * BigInteger. The sign is represented as an integer signum value: -1 for 345 * negative, 0 for zero, or 1 for positive. The magnitude is a byte array 346 * in <i>big-endian</i> byte-order: the most significant byte is in the 347 * zeroth element. A zero-length magnitude array is permissible, and will 348 * result in a BigInteger value of 0, whether signum is -1, 0 or 1. 349 * 350 * @param signum signum of the number (-1 for negative, 0 for zero, 1 351 * for positive). 352 * @param magnitude big-endian binary representation of the magnitude of 353 * the number. 354 * @throws NumberFormatException {@code signum} is not one of the three 355 * legal values (-1, 0, and 1), or {@code signum} is 0 and 356 * {@code magnitude} contains one or more non-zero bytes. 357 */ BigInteger(int signum, byte[] magnitude)358 public BigInteger(int signum, byte[] magnitude) { 359 this.mag = stripLeadingZeroBytes(magnitude); 360 361 if (signum < -1 || signum > 1) 362 throw(new NumberFormatException("Invalid signum value")); 363 364 if (this.mag.length == 0) { 365 this.signum = 0; 366 } else { 367 if (signum == 0) 368 throw(new NumberFormatException("signum-magnitude mismatch")); 369 this.signum = signum; 370 } 371 if (mag.length >= MAX_MAG_LENGTH) { 372 checkRange(); 373 } 374 } 375 376 /** 377 * A constructor for internal use that translates the sign-magnitude 378 * representation of a BigInteger into a BigInteger. It checks the 379 * arguments and copies the magnitude so this constructor would be 380 * safe for external use. 381 */ BigInteger(int signum, int[] magnitude)382 private BigInteger(int signum, int[] magnitude) { 383 this.mag = stripLeadingZeroInts(magnitude); 384 385 if (signum < -1 || signum > 1) 386 throw(new NumberFormatException("Invalid signum value")); 387 388 if (this.mag.length == 0) { 389 this.signum = 0; 390 } else { 391 if (signum == 0) 392 throw(new NumberFormatException("signum-magnitude mismatch")); 393 this.signum = signum; 394 } 395 if (mag.length >= MAX_MAG_LENGTH) { 396 checkRange(); 397 } 398 } 399 400 /** 401 * Translates the String representation of a BigInteger in the 402 * specified radix into a BigInteger. The String representation 403 * consists of an optional minus or plus sign followed by a 404 * sequence of one or more digits in the specified radix. The 405 * character-to-digit mapping is provided by {@code 406 * Character.digit}. The String may not contain any extraneous 407 * characters (whitespace, for example). 408 * 409 * @param val String representation of BigInteger. 410 * @param radix radix to be used in interpreting {@code val}. 411 * @throws NumberFormatException {@code val} is not a valid representation 412 * of a BigInteger in the specified radix, or {@code radix} is 413 * outside the range from {@link Character#MIN_RADIX} to 414 * {@link Character#MAX_RADIX}, inclusive. 415 * @see Character#digit 416 */ BigInteger(@onNull String val, int radix)417 public BigInteger(@NonNull String val, int radix) { 418 int cursor = 0, numDigits; 419 final int len = val.length(); 420 421 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) 422 throw new NumberFormatException("Radix out of range"); 423 if (len == 0) 424 throw new NumberFormatException("Zero length BigInteger"); 425 426 // Check for at most one leading sign 427 int sign = 1; 428 int index1 = val.lastIndexOf('-'); 429 int index2 = val.lastIndexOf('+'); 430 if (index1 >= 0) { 431 if (index1 != 0 || index2 >= 0) { 432 throw new NumberFormatException("Illegal embedded sign character"); 433 } 434 sign = -1; 435 cursor = 1; 436 } else if (index2 >= 0) { 437 if (index2 != 0) { 438 throw new NumberFormatException("Illegal embedded sign character"); 439 } 440 cursor = 1; 441 } 442 if (cursor == len) 443 throw new NumberFormatException("Zero length BigInteger"); 444 445 // Skip leading zeros and compute number of digits in magnitude 446 while (cursor < len && 447 Character.digit(val.charAt(cursor), radix) == 0) { 448 cursor++; 449 } 450 451 if (cursor == len) { 452 signum = 0; 453 mag = ZERO.mag; 454 return; 455 } 456 457 numDigits = len - cursor; 458 signum = sign; 459 460 // Pre-allocate array of expected size. May be too large but can 461 // never be too small. Typically exact. 462 long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1; 463 if (numBits + 31 >= (1L << 32)) { 464 reportOverflow(); 465 } 466 int numWords = (int) (numBits + 31) >>> 5; 467 int[] magnitude = new int[numWords]; 468 469 // Process first (potentially short) digit group 470 int firstGroupLen = numDigits % digitsPerInt[radix]; 471 if (firstGroupLen == 0) 472 firstGroupLen = digitsPerInt[radix]; 473 String group = val.substring(cursor, cursor += firstGroupLen); 474 magnitude[numWords - 1] = Integer.parseInt(group, radix); 475 if (magnitude[numWords - 1] < 0) 476 throw new NumberFormatException("Illegal digit"); 477 478 // Process remaining digit groups 479 int superRadix = intRadix[radix]; 480 int groupVal = 0; 481 while (cursor < len) { 482 group = val.substring(cursor, cursor += digitsPerInt[radix]); 483 groupVal = Integer.parseInt(group, radix); 484 if (groupVal < 0) 485 throw new NumberFormatException("Illegal digit"); 486 destructiveMulAdd(magnitude, superRadix, groupVal); 487 } 488 // Required for cases where the array was overallocated. 489 mag = trustedStripLeadingZeroInts(magnitude); 490 if (mag.length >= MAX_MAG_LENGTH) { 491 checkRange(); 492 } 493 } 494 495 /* 496 * Constructs a new BigInteger using a char array with radix=10. 497 * Sign is precalculated outside and not allowed in the val. 498 */ BigInteger(char[] val, int sign, int len)499 BigInteger(char[] val, int sign, int len) { 500 int cursor = 0, numDigits; 501 502 // Skip leading zeros and compute number of digits in magnitude 503 while (cursor < len && Character.digit(val[cursor], 10) == 0) { 504 cursor++; 505 } 506 if (cursor == len) { 507 signum = 0; 508 mag = ZERO.mag; 509 return; 510 } 511 512 numDigits = len - cursor; 513 signum = sign; 514 // Pre-allocate array of expected size 515 int numWords; 516 if (len < 10) { 517 numWords = 1; 518 } else { 519 long numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1; 520 if (numBits + 31 >= (1L << 32)) { 521 reportOverflow(); 522 } 523 numWords = (int) (numBits + 31) >>> 5; 524 } 525 int[] magnitude = new int[numWords]; 526 527 // Process first (potentially short) digit group 528 int firstGroupLen = numDigits % digitsPerInt[10]; 529 if (firstGroupLen == 0) 530 firstGroupLen = digitsPerInt[10]; 531 magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen); 532 533 // Process remaining digit groups 534 while (cursor < len) { 535 int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]); 536 destructiveMulAdd(magnitude, intRadix[10], groupVal); 537 } 538 mag = trustedStripLeadingZeroInts(magnitude); 539 if (mag.length >= MAX_MAG_LENGTH) { 540 checkRange(); 541 } 542 } 543 544 // Create an integer with the digits between the two indexes 545 // Assumes start < end. The result may be negative, but it 546 // is to be treated as an unsigned value. parseInt(char[] source, int start, int end)547 private int parseInt(char[] source, int start, int end) { 548 int result = Character.digit(source[start++], 10); 549 if (result == -1) 550 throw new NumberFormatException(new String(source)); 551 552 for (int index = start; index < end; index++) { 553 int nextVal = Character.digit(source[index], 10); 554 if (nextVal == -1) 555 throw new NumberFormatException(new String(source)); 556 result = 10*result + nextVal; 557 } 558 559 return result; 560 } 561 562 // bitsPerDigit in the given radix times 1024 563 // Rounded up to avoid underallocation. 564 private static long bitsPerDigit[] = { 0, 0, 565 1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672, 566 3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633, 567 4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210, 568 5253, 5295}; 569 570 // Multiply x array times word y in place, and add word z destructiveMulAdd(int[] x, int y, int z)571 private static void destructiveMulAdd(int[] x, int y, int z) { 572 // Perform the multiplication word by word 573 long ylong = y & LONG_MASK; 574 long zlong = z & LONG_MASK; 575 int len = x.length; 576 577 long product = 0; 578 long carry = 0; 579 for (int i = len-1; i >= 0; i--) { 580 product = ylong * (x[i] & LONG_MASK) + carry; 581 x[i] = (int)product; 582 carry = product >>> 32; 583 } 584 585 // Perform the addition 586 long sum = (x[len-1] & LONG_MASK) + zlong; 587 x[len-1] = (int)sum; 588 carry = sum >>> 32; 589 for (int i = len-2; i >= 0; i--) { 590 sum = (x[i] & LONG_MASK) + carry; 591 x[i] = (int)sum; 592 carry = sum >>> 32; 593 } 594 } 595 596 /** 597 * Translates the decimal String representation of a BigInteger into a 598 * BigInteger. The String representation consists of an optional minus 599 * sign followed by a sequence of one or more decimal digits. The 600 * character-to-digit mapping is provided by {@code Character.digit}. 601 * The String may not contain any extraneous characters (whitespace, for 602 * example). 603 * 604 * @param val decimal String representation of BigInteger. 605 * @throws NumberFormatException {@code val} is not a valid representation 606 * of a BigInteger. 607 * @see Character#digit 608 */ BigInteger(@onNull String val)609 public BigInteger(@NonNull String val) { 610 this(val, 10); 611 } 612 613 /** 614 * Constructs a randomly generated BigInteger, uniformly distributed over 615 * the range 0 to (2<sup>{@code numBits}</sup> - 1), inclusive. 616 * The uniformity of the distribution assumes that a fair source of random 617 * bits is provided in {@code rnd}. Note that this constructor always 618 * constructs a non-negative BigInteger. 619 * 620 * @param numBits maximum bitLength of the new BigInteger. 621 * @param rnd source of randomness to be used in computing the new 622 * BigInteger. 623 * @throws IllegalArgumentException {@code numBits} is negative. 624 * @see #bitLength() 625 */ BigInteger(int numBits, @NonNull Random rnd)626 public BigInteger(int numBits, @NonNull Random rnd) { 627 this(1, randomBits(numBits, rnd)); 628 } 629 randomBits(int numBits, Random rnd)630 private static byte[] randomBits(int numBits, Random rnd) { 631 if (numBits < 0) 632 throw new IllegalArgumentException("numBits must be non-negative"); 633 int numBytes = (int)(((long)numBits+7)/8); // avoid overflow 634 byte[] randomBits = new byte[numBytes]; 635 636 // Generate random bytes and mask out any excess bits 637 if (numBytes > 0) { 638 rnd.nextBytes(randomBits); 639 int excessBits = 8*numBytes - numBits; 640 randomBits[0] &= (1 << (8-excessBits)) - 1; 641 } 642 return randomBits; 643 } 644 645 /** 646 * Constructs a randomly generated positive BigInteger that is probably 647 * prime, with the specified bitLength. 648 * 649 * <p>It is recommended that the {@link #probablePrime probablePrime} 650 * method be used in preference to this constructor unless there 651 * is a compelling need to specify a certainty. 652 * 653 * @param bitLength bitLength of the returned BigInteger. 654 * @param certainty a measure of the uncertainty that the caller is 655 * willing to tolerate. The probability that the new BigInteger 656 * represents a prime number will exceed 657 * (1 - 1/2<sup>{@code certainty}</sup>). The execution time of 658 * this constructor is proportional to the value of this parameter. 659 * @param rnd source of random bits used to select candidates to be 660 * tested for primality. 661 * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large. 662 * @see #bitLength() 663 */ BigInteger(int bitLength, int certainty, @NonNull Random rnd)664 public BigInteger(int bitLength, int certainty, @NonNull Random rnd) { 665 BigInteger prime; 666 667 if (bitLength < 2) 668 throw new ArithmeticException("bitLength < 2"); 669 prime = (bitLength < SMALL_PRIME_THRESHOLD 670 ? smallPrime(bitLength, certainty, rnd) 671 : largePrime(bitLength, certainty, rnd)); 672 signum = 1; 673 mag = prime.mag; 674 } 675 676 // Minimum size in bits that the requested prime number has 677 // before we use the large prime number generating algorithms. 678 // The cutoff of 95 was chosen empirically for best performance. 679 private static final int SMALL_PRIME_THRESHOLD = 95; 680 681 // Certainty required to meet the spec of probablePrime 682 private static final int DEFAULT_PRIME_CERTAINTY = 100; 683 684 /** 685 * Returns a positive BigInteger that is probably prime, with the 686 * specified bitLength. The probability that a BigInteger returned 687 * by this method is composite does not exceed 2<sup>-100</sup>. 688 * 689 * @param bitLength bitLength of the returned BigInteger. 690 * @param rnd source of random bits used to select candidates to be 691 * tested for primality. 692 * @return a BigInteger of {@code bitLength} bits that is probably prime 693 * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large. 694 * @see #bitLength() 695 * @since 1.4 696 */ probablePrime(int bitLength, @NonNull Random rnd)697 @NonNull public static BigInteger probablePrime(int bitLength, @NonNull Random rnd) { 698 if (bitLength < 2) 699 throw new ArithmeticException("bitLength < 2"); 700 701 return (bitLength < SMALL_PRIME_THRESHOLD ? 702 smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) : 703 largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd)); 704 } 705 706 /** 707 * Find a random number of the specified bitLength that is probably prime. 708 * This method is used for smaller primes, its performance degrades on 709 * larger bitlengths. 710 * 711 * This method assumes bitLength > 1. 712 */ smallPrime(int bitLength, int certainty, @NonNull Random rnd)713 private static BigInteger smallPrime(int bitLength, int certainty, @NonNull Random rnd) { 714 int magLen = (bitLength + 31) >>> 5; 715 int temp[] = new int[magLen]; 716 int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int 717 int highMask = (highBit << 1) - 1; // Bits to keep in high int 718 719 while (true) { 720 // Construct a candidate 721 for (int i=0; i < magLen; i++) 722 temp[i] = rnd.nextInt(); 723 temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length 724 if (bitLength > 2) 725 temp[magLen-1] |= 1; // Make odd if bitlen > 2 726 727 BigInteger p = new BigInteger(temp, 1); 728 729 // Do cheap "pre-test" if applicable 730 if (bitLength > 6) { 731 long r = p.remainder(SMALL_PRIME_PRODUCT).longValue(); 732 if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) || 733 (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) || 734 (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) 735 continue; // Candidate is composite; try another 736 } 737 738 // All candidates of bitLength 2 and 3 are prime by this point 739 if (bitLength < 4) 740 return p; 741 742 // Do expensive test if we survive pre-test (or it's inapplicable) 743 if (p.primeToCertainty(certainty, rnd)) 744 return p; 745 } 746 } 747 748 private static final BigInteger SMALL_PRIME_PRODUCT 749 = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41); 750 751 /** 752 * Find a random number of the specified bitLength that is probably prime. 753 * This method is more appropriate for larger bitlengths since it uses 754 * a sieve to eliminate most composites before using a more expensive 755 * test. 756 */ largePrime(int bitLength, int certainty, @NonNull Random rnd)757 private static BigInteger largePrime(int bitLength, int certainty, @NonNull Random rnd) { 758 BigInteger p; 759 p = new BigInteger(bitLength, rnd).setBit(bitLength-1); 760 p.mag[p.mag.length-1] &= 0xfffffffe; 761 762 // Use a sieve length likely to contain the next prime number 763 int searchLen = getPrimeSearchLen(bitLength); 764 BitSieve searchSieve = new BitSieve(p, searchLen); 765 BigInteger candidate = searchSieve.retrieve(p, certainty, rnd); 766 767 while ((candidate == null) || (candidate.bitLength() != bitLength)) { 768 p = p.add(BigInteger.valueOf(2*searchLen)); 769 if (p.bitLength() != bitLength) 770 p = new BigInteger(bitLength, rnd).setBit(bitLength-1); 771 p.mag[p.mag.length-1] &= 0xfffffffe; 772 searchSieve = new BitSieve(p, searchLen); 773 candidate = searchSieve.retrieve(p, certainty, rnd); 774 } 775 return candidate; 776 } 777 778 /** 779 * Returns the first integer greater than this {@code BigInteger} that 780 * is probably prime. The probability that the number returned by this 781 * method is composite does not exceed 2<sup>-100</sup>. This method will 782 * never skip over a prime when searching: if it returns {@code p}, there 783 * is no prime {@code q} such that {@code this < q < p}. 784 * 785 * @return the first integer greater than this {@code BigInteger} that 786 * is probably prime. 787 * @throws ArithmeticException {@code this < 0} or {@code this} is too large. 788 * @since 1.5 789 */ nextProbablePrime()790 @NonNull public BigInteger nextProbablePrime() { 791 if (this.signum < 0) 792 throw new ArithmeticException("start < 0: " + this); 793 794 // Handle trivial cases 795 if ((this.signum == 0) || this.equals(ONE)) 796 return TWO; 797 798 BigInteger result = this.add(ONE); 799 800 // Fastpath for small numbers 801 if (result.bitLength() < SMALL_PRIME_THRESHOLD) { 802 803 // Ensure an odd number 804 if (!result.testBit(0)) 805 result = result.add(ONE); 806 807 while (true) { 808 // Do cheap "pre-test" if applicable 809 if (result.bitLength() > 6) { 810 long r = result.remainder(SMALL_PRIME_PRODUCT).longValue(); 811 if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) || 812 (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) || 813 (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) { 814 result = result.add(TWO); 815 continue; // Candidate is composite; try another 816 } 817 } 818 819 // All candidates of bitLength 2 and 3 are prime by this point 820 if (result.bitLength() < 4) 821 return result; 822 823 // The expensive test 824 if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null)) 825 return result; 826 827 result = result.add(TWO); 828 } 829 } 830 831 // Start at previous even number 832 if (result.testBit(0)) 833 result = result.subtract(ONE); 834 835 // Looking for the next large prime 836 int searchLen = getPrimeSearchLen(result.bitLength()); 837 838 while (true) { 839 BitSieve searchSieve = new BitSieve(result, searchLen); 840 BigInteger candidate = searchSieve.retrieve(result, 841 DEFAULT_PRIME_CERTAINTY, null); 842 if (candidate != null) 843 return candidate; 844 result = result.add(BigInteger.valueOf(2 * searchLen)); 845 } 846 } 847 getPrimeSearchLen(int bitLength)848 private static int getPrimeSearchLen(int bitLength) { 849 if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) { 850 throw new ArithmeticException("Prime search implementation restriction on bitLength"); 851 } 852 return bitLength / 20 * 64; 853 } 854 855 /** 856 * Returns {@code true} if this BigInteger is probably prime, 857 * {@code false} if it's definitely composite. 858 * 859 * This method assumes bitLength > 2. 860 * 861 * @param certainty a measure of the uncertainty that the caller is 862 * willing to tolerate: if the call returns {@code true} 863 * the probability that this BigInteger is prime exceeds 864 * {@code (1 - 1/2<sup>certainty</sup>)}. The execution time of 865 * this method is proportional to the value of this parameter. 866 * @return {@code true} if this BigInteger is probably prime, 867 * {@code false} if it's definitely composite. 868 */ primeToCertainty(int certainty, @NonNull Random random)869 boolean primeToCertainty(int certainty, @NonNull Random random) { 870 int rounds = 0; 871 int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2; 872 873 // The relationship between the certainty and the number of rounds 874 // we perform is given in the draft standard ANSI X9.80, "PRIME 875 // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES". 876 int sizeInBits = this.bitLength(); 877 if (sizeInBits < 100) { 878 rounds = 50; 879 rounds = n < rounds ? n : rounds; 880 return passesMillerRabin(rounds, random); 881 } 882 883 if (sizeInBits < 256) { 884 rounds = 27; 885 } else if (sizeInBits < 512) { 886 rounds = 15; 887 } else if (sizeInBits < 768) { 888 rounds = 8; 889 } else if (sizeInBits < 1024) { 890 rounds = 4; 891 } else { 892 rounds = 2; 893 } 894 rounds = n < rounds ? n : rounds; 895 896 return passesMillerRabin(rounds, random) && passesLucasLehmer(); 897 } 898 899 /** 900 * Returns true iff this BigInteger is a Lucas-Lehmer probable prime. 901 * 902 * The following assumptions are made: 903 * This BigInteger is a positive, odd number. 904 */ 905 private boolean passesLucasLehmer() { 906 BigInteger thisPlusOne = this.add(ONE); 907 908 // Step 1 909 int d = 5; 910 while (jacobiSymbol(d, this) != -1) { 911 // 5, -7, 9, -11, ... 912 d = (d < 0) ? Math.abs(d)+2 : -(d+2); 913 } 914 915 // Step 2 916 BigInteger u = lucasLehmerSequence(d, thisPlusOne, this); 917 918 // Step 3 919 return u.mod(this).equals(ZERO); 920 } 921 922 /** 923 * Computes Jacobi(p,n). 924 * Assumes n positive, odd, n>=3. 925 */ 926 private static int jacobiSymbol(int p, @NonNull BigInteger n) { 927 if (p == 0) 928 return 0; 929 930 // Algorithm and comments adapted from Colin Plumb's C library. 931 int j = 1; 932 int u = n.mag[n.mag.length-1]; 933 934 // Make p positive 935 if (p < 0) { 936 p = -p; 937 int n8 = u & 7; 938 if ((n8 == 3) || (n8 == 7)) 939 j = -j; // 3 (011) or 7 (111) mod 8 940 } 941 942 // Get rid of factors of 2 in p 943 while ((p & 3) == 0) 944 p >>= 2; 945 if ((p & 1) == 0) { 946 p >>= 1; 947 if (((u ^ (u>>1)) & 2) != 0) 948 j = -j; // 3 (011) or 5 (101) mod 8 949 } 950 if (p == 1) 951 return j; 952 // Then, apply quadratic reciprocity 953 if ((p & u & 2) != 0) // p = u = 3 (mod 4)? 954 j = -j; 955 // And reduce u mod p 956 u = n.mod(BigInteger.valueOf(p)).intValue(); 957 958 // Now compute Jacobi(u,p), u < p 959 while (u != 0) { 960 while ((u & 3) == 0) 961 u >>= 2; 962 if ((u & 1) == 0) { 963 u >>= 1; 964 if (((p ^ (p>>1)) & 2) != 0) 965 j = -j; // 3 (011) or 5 (101) mod 8 966 } 967 if (u == 1) 968 return j; 969 // Now both u and p are odd, so use quadratic reciprocity assert(u < p); int t = u; u = p; p = t; if ((u & p & 2) != 0) j = -j; u %= p; } return 0; } @NonNull private static BigInteger lucasLehmerSequence(int z, @NonNull BigInteger k, @NonNull BigInteger n) { BigInteger d = BigInteger.valueOf(z); BigInteger u = ONE; BigInteger u2; BigInteger v = ONE; BigInteger v2; for (int i=k.bitLength()-2; i >= 0; i--)970 assert (u < p); 971 int t = u; u = p; p = t; 972 if ((u & p & 2) != 0) // u = p = 3 (mod 4)? 973 j = -j; 974 // Now u >= p, so it can be reduced 975 u %= p; 976 } 977 return 0; 978 } 979 980 @NonNull private static BigInteger lucasLehmerSequence(int z, @NonNull BigInteger k, @NonNull BigInteger n) { 981 BigInteger d = BigInteger.valueOf(z); 982 BigInteger u = ONE; BigInteger u2; 983 BigInteger v = ONE; BigInteger v2; 984 985 for (int i=k.bitLength()-2; i >= 0; i--) { 986 u2 = u.multiply(v).mod(n); 987 988 v2 = v.square().add(d.multiply(u.square())).mod(n); 989 if (v2.testBit(0)) 990 v2 = v2.subtract(n); 991 992 v2 = v2.shiftRight(1); 993 994 u = u2; v = v2; 995 if (k.testBit(i)) { 996 u2 = u.add(v).mod(n); 997 if (u2.testBit(0)) 998 u2 = u2.subtract(n); 999 1000 u2 = u2.shiftRight(1); 1001 v2 = v.add(d.multiply(u)).mod(n); 1002 if (v2.testBit(0)) 1003 v2 = v2.subtract(n); 1004 v2 = v2.shiftRight(1); 1005 1006 u = u2; v = v2; 1007 } 1008 } 1009 return u; 1010 } 1011 1012 /** 1013 * Returns true iff this BigInteger passes the specified number of 1014 * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS 1015 * 186-2). 1016 * 1017 * The following assumptions are made: 1018 * This BigInteger is a positive, odd number greater than 2. 1019 * iterations<=50. 1020 */ passesMillerRabin(int iterations, @NonNull Random rnd)1021 private boolean passesMillerRabin(int iterations, @NonNull Random rnd) { 1022 // Find a and m such that m is odd and this == 1 + 2**a * m 1023 BigInteger thisMinusOne = this.subtract(ONE); 1024 BigInteger m = thisMinusOne; 1025 int a = m.getLowestSetBit(); 1026 m = m.shiftRight(a); 1027 1028 // Do the tests 1029 if (rnd == null) { 1030 rnd = ThreadLocalRandom.current(); 1031 } 1032 for (int i=0; i < iterations; i++) { 1033 // Generate a uniform random on (1, this) 1034 BigInteger b; 1035 do { 1036 b = new BigInteger(this.bitLength(), rnd); 1037 } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0); 1038 1039 int j = 0; 1040 BigInteger z = b.modPow(m, this); 1041 while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) { 1042 if (j > 0 && z.equals(ONE) || ++j == a) 1043 return false; 1044 z = z.modPow(TWO, this); 1045 } 1046 } 1047 return true; 1048 } 1049 1050 /** 1051 * This internal constructor differs from its public cousin 1052 * with the arguments reversed in two ways: it assumes that its 1053 * arguments are correct, and it doesn't copy the magnitude array. 1054 */ BigInteger(int[] magnitude, int signum)1055 BigInteger(int[] magnitude, int signum) { 1056 this.signum = (magnitude.length == 0 ? 0 : signum); 1057 this.mag = magnitude; 1058 if (mag.length >= MAX_MAG_LENGTH) { 1059 checkRange(); 1060 } 1061 } 1062 1063 /** 1064 * This private constructor is for internal use and assumes that its 1065 * arguments are correct. 1066 */ BigInteger(byte[] magnitude, int signum)1067 private BigInteger(byte[] magnitude, int signum) { 1068 this.signum = (magnitude.length == 0 ? 0 : signum); 1069 this.mag = stripLeadingZeroBytes(magnitude); 1070 if (mag.length >= MAX_MAG_LENGTH) { 1071 checkRange(); 1072 } 1073 } 1074 1075 /** 1076 * Throws an {@code ArithmeticException} if the {@code BigInteger} would be 1077 * out of the supported range. 1078 * 1079 * @throws ArithmeticException if {@code this} exceeds the supported range. 1080 */ checkRange()1081 private void checkRange() { 1082 if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) { 1083 reportOverflow(); 1084 } 1085 } 1086 reportOverflow()1087 private static void reportOverflow() { 1088 throw new ArithmeticException("BigInteger would overflow supported range"); 1089 } 1090 1091 //Static Factory Methods 1092 1093 /** 1094 * Returns a BigInteger whose value is equal to that of the 1095 * specified {@code long}. This "static factory method" is 1096 * provided in preference to a ({@code long}) constructor 1097 * because it allows for reuse of frequently used BigIntegers. 1098 * 1099 * @param val value of the BigInteger to return. 1100 * @return a BigInteger with the specified value. 1101 */ valueOf(long val)1102 @NonNull public static BigInteger valueOf(long val) { 1103 // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant 1104 if (val == 0) 1105 return ZERO; 1106 if (val > 0 && val <= MAX_CONSTANT) 1107 return posConst[(int) val]; 1108 else if (val < 0 && val >= -MAX_CONSTANT) 1109 return negConst[(int) -val]; 1110 1111 return new BigInteger(val); 1112 } 1113 1114 /** 1115 * Constructs a BigInteger with the specified value, which may not be zero. 1116 */ BigInteger(long val)1117 @NonNull private BigInteger(long val) { 1118 if (val < 0) { 1119 val = -val; 1120 signum = -1; 1121 } else { 1122 signum = 1; 1123 } 1124 1125 int highWord = (int)(val >>> 32); 1126 if (highWord == 0) { 1127 mag = new int[1]; 1128 mag[0] = (int)val; 1129 } else { 1130 mag = new int[2]; 1131 mag[0] = highWord; 1132 mag[1] = (int)val; 1133 } 1134 } 1135 1136 /** 1137 * Returns a BigInteger with the given two's complement representation. 1138 * Assumes that the input array will not be modified (the returned 1139 * BigInteger will reference the input array if feasible). 1140 */ valueOf(int val[])1141 @NonNull private static BigInteger valueOf(int val[]) { 1142 return (val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val)); 1143 } 1144 1145 // Constants 1146 1147 /** 1148 * Initialize static constant array when class is loaded. 1149 */ 1150 private final static int MAX_CONSTANT = 16; 1151 private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1]; 1152 private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1]; 1153 1154 /** 1155 * The cache of powers of each radix. This allows us to not have to 1156 * recalculate powers of radix^(2^n) more than once. This speeds 1157 * Schoenhage recursive base conversion significantly. 1158 */ 1159 private static volatile BigInteger[][] powerCache; 1160 1161 /** The cache of logarithms of radices for base conversion. */ 1162 private static final double[] logCache; 1163 1164 /** The natural log of 2. This is used in computing cache indices. */ 1165 private static final double LOG_TWO = Math.log(2.0); 1166 1167 static { 1168 assert 0 < KARATSUBA_THRESHOLD 1169 && KARATSUBA_THRESHOLD < TOOM_COOK_THRESHOLD 1170 && TOOM_COOK_THRESHOLD < Integer.MAX_VALUE 1171 && 0 < KARATSUBA_SQUARE_THRESHOLD 1172 && KARATSUBA_SQUARE_THRESHOLD < TOOM_COOK_SQUARE_THRESHOLD 1173 && TOOM_COOK_SQUARE_THRESHOLD < Integer.MAX_VALUE : 1174 "Algorithm thresholds are inconsistent"; 1175 1176 for (int i = 1; i <= MAX_CONSTANT; i++) { 1177 int[] magnitude = new int[1]; 1178 magnitude[0] = i; 1179 posConst[i] = new BigInteger(magnitude, 1); 1180 negConst[i] = new BigInteger(magnitude, -1); 1181 } 1182 1183 /* 1184 * Initialize the cache of radix^(2^x) values used for base conversion 1185 * with just the very first value. Additional values will be created 1186 * on demand. 1187 */ 1188 powerCache = new BigInteger[Character.MAX_RADIX+1][]; 1189 logCache = new double[Character.MAX_RADIX+1]; 1190 1191 for (int i=Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) { 1192 powerCache[i] = new BigInteger[] { BigInteger.valueOf(i) }; 1193 logCache[i] = Math.log(i); 1194 } 1195 } 1196 1197 /** 1198 * The BigInteger constant zero. 1199 * 1200 * @since 1.2 1201 */ 1202 @NonNull public static final BigInteger ZERO = new BigInteger(new int[0], 0); 1203 1204 /** 1205 * The BigInteger constant one. 1206 * 1207 * @since 1.2 1208 */ 1209 @NonNull public static final BigInteger ONE = valueOf(1); 1210 1211 /** 1212 * The BigInteger constant two. (Not exported.) 1213 */ 1214 @NonNull private static final BigInteger TWO = valueOf(2); 1215 1216 /** 1217 * The BigInteger constant -1. (Not exported.) 1218 */ 1219 @NonNull private static final BigInteger NEGATIVE_ONE = valueOf(-1); 1220 1221 /** 1222 * The BigInteger constant ten. 1223 * 1224 * @since 1.5 1225 */ 1226 @NonNull public static final BigInteger TEN = valueOf(10); 1227 1228 // Arithmetic Operations 1229 1230 /** 1231 * Returns a BigInteger whose value is {@code (this + val)}. 1232 * 1233 * @param val value to be added to this BigInteger. 1234 * @return {@code this + val} 1235 */ 1236 @NonNull public BigInteger add(@NonNull BigInteger val) { 1237 if (val.signum == 0) 1238 return this; 1239 if (signum == 0) 1240 return val; 1241 if (val.signum == signum) 1242 return new BigInteger(add(mag, val.mag), signum); 1243 1244 int cmp = compareMagnitude(val); 1245 if (cmp == 0) 1246 return ZERO; 1247 int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) 1248 : subtract(val.mag, mag)); 1249 resultMag = trustedStripLeadingZeroInts(resultMag); 1250 1251 return new BigInteger(resultMag, cmp == signum ? 1 : -1); 1252 } 1253 1254 /** 1255 * Package private methods used by BigDecimal code to add a BigInteger 1256 * with a long. Assumes val is not equal to INFLATED. 1257 */ 1258 @NonNull BigInteger add(long val) { 1259 if (val == 0) 1260 return this; 1261 if (signum == 0) 1262 return valueOf(val); 1263 if (Long.signum(val) == signum) 1264 return new BigInteger(add(mag, Math.abs(val)), signum); 1265 int cmp = compareMagnitude(val); 1266 if (cmp == 0) 1267 return ZERO; 1268 int[] resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag)); 1269 resultMag = trustedStripLeadingZeroInts(resultMag); 1270 return new BigInteger(resultMag, cmp == signum ? 1 : -1); 1271 } 1272 1273 /** 1274 * Adds the contents of the int array x and long value val. This 1275 * method allocates a new int array to hold the answer and returns 1276 * a reference to that array. Assumes x.length > 0 and val is 1277 * non-negative 1278 */ 1279 private static int[] add(int[] x, long val) { 1280 int[] y; 1281 long sum = 0; 1282 int xIndex = x.length; 1283 int[] result; 1284 int highWord = (int)(val >>> 32); 1285 if (highWord == 0) { 1286 result = new int[xIndex]; 1287 sum = (x[--xIndex] & LONG_MASK) + val; 1288 result[xIndex] = (int)sum; 1289 } else { 1290 if (xIndex == 1) { 1291 result = new int[2]; 1292 sum = val + (x[0] & LONG_MASK); 1293 result[1] = (int)sum; 1294 result[0] = (int)(sum >>> 32); 1295 return result; 1296 } else { 1297 result = new int[xIndex]; 1298 sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK); 1299 result[xIndex] = (int)sum; 1300 sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32); 1301 result[xIndex] = (int)sum; 1302 } 1303 } 1304 // Copy remainder of longer number while carry propagation is required 1305 boolean carry = (sum >>> 32 != 0); 1306 while (xIndex > 0 && carry) 1307 carry = ((result[--xIndex] = x[xIndex] + 1) == 0); 1308 // Copy remainder of longer number 1309 while (xIndex > 0) 1310 result[--xIndex] = x[xIndex]; 1311 // Grow result if necessary 1312 if (carry) { 1313 int bigger[] = new int[result.length + 1]; System.arraycopy(result, 0, bigger, 1, result.length)1314 System.arraycopy(result, 0, bigger, 1, result.length); 1315 bigger[0] = 0x01; 1316 return bigger; 1317 } 1318 return result; 1319 } 1320 1321 /** 1322 * Adds the contents of the int arrays x and y. This method allocates 1323 * a new int array to hold the answer and returns a reference to that 1324 * array. 1325 */ add(int[] x, int[] y)1326 private static int[] add(int[] x, int[] y) { 1327 // If x is shorter, swap the two arrays 1328 if (x.length < y.length) { 1329 int[] tmp = x; 1330 x = y; 1331 y = tmp; 1332 } 1333 1334 int xIndex = x.length; 1335 int yIndex = y.length; 1336 int result[] = new int[xIndex]; 1337 long sum = 0; 1338 if (yIndex == 1) { 1339 sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ; 1340 result[xIndex] = (int)sum; 1341 } else { 1342 // Add common parts of both numbers 1343 while (yIndex > 0) { 1344 sum = (x[--xIndex] & LONG_MASK) + 1345 (y[--yIndex] & LONG_MASK) + (sum >>> 32); 1346 result[xIndex] = (int)sum; 1347 } 1348 } 1349 // Copy remainder of longer number while carry propagation is required 1350 boolean carry = (sum >>> 32 != 0); 1351 while (xIndex > 0 && carry) 1352 carry = ((result[--xIndex] = x[xIndex] + 1) == 0); 1353 1354 // Copy remainder of longer number 1355 while (xIndex > 0) 1356 result[--xIndex] = x[xIndex]; 1357 1358 // Grow result if necessary 1359 if (carry) { 1360 int bigger[] = new int[result.length + 1]; 1361 System.arraycopy(result, 0, bigger, 1, result.length); 1362 bigger[0] = 0x01; 1363 return bigger; 1364 } 1365 return result; 1366 } 1367 subtract(long val, int[] little)1368 private static int[] subtract(long val, int[] little) { 1369 int highWord = (int)(val >>> 32); 1370 if (highWord == 0) { 1371 int result[] = new int[1]; 1372 result[0] = (int)(val - (little[0] & LONG_MASK)); 1373 return result; 1374 } else { 1375 int result[] = new int[2]; 1376 if (little.length == 1) { 1377 long difference = ((int)val & LONG_MASK) - (little[0] & LONG_MASK); 1378 result[1] = (int)difference; 1379 // Subtract remainder of longer number while borrow propagates 1380 boolean borrow = (difference >> 32 != 0); 1381 if (borrow) { 1382 result[0] = highWord - 1; 1383 } else { // Copy remainder of longer number 1384 result[0] = highWord; 1385 } 1386 return result; 1387 } else { // little.length == 2 1388 long difference = ((int)val & LONG_MASK) - (little[1] & LONG_MASK); 1389 result[1] = (int)difference; 1390 difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32); 1391 result[0] = (int)difference; 1392 return result; 1393 } 1394 } 1395 } 1396 1397 /** 1398 * Subtracts the contents of the second argument (val) from the 1399 * first (big). The first int array (big) must represent a larger number 1400 * than the second. This method allocates the space necessary to hold the 1401 * answer. 1402 * assumes val >= 0 1403 */ subtract(int[] big, long val)1404 private static int[] subtract(int[] big, long val) { 1405 int highWord = (int)(val >>> 32); 1406 int bigIndex = big.length; 1407 int result[] = new int[bigIndex]; 1408 long difference = 0; 1409 1410 if (highWord == 0) { 1411 difference = (big[--bigIndex] & LONG_MASK) - val; 1412 result[bigIndex] = (int)difference; 1413 } else { 1414 difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK); 1415 result[bigIndex] = (int)difference; 1416 difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32); 1417 result[bigIndex] = (int)difference; 1418 } 1419 1420 // Subtract remainder of longer number while borrow propagates 1421 boolean borrow = (difference >> 32 != 0); 1422 while (bigIndex > 0 && borrow) 1423 borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1); 1424 1425 // Copy remainder of longer number 1426 while (bigIndex > 0) 1427 result[--bigIndex] = big[bigIndex]; 1428 1429 return result; 1430 } 1431 1432 /** 1433 * Returns a BigInteger whose value is {@code (this - val)}. 1434 * 1435 * @param val value to be subtracted from this BigInteger. 1436 * @return {@code this - val} 1437 */ subtract(@onNull BigInteger val)1438 @NonNull public BigInteger subtract(@NonNull BigInteger val) { 1439 if (val.signum == 0) 1440 return this; 1441 if (signum == 0) 1442 return val.negate(); 1443 if (val.signum != signum) 1444 return new BigInteger(add(mag, val.mag), signum); 1445 1446 int cmp = compareMagnitude(val); 1447 if (cmp == 0) 1448 return ZERO; 1449 int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) 1450 : subtract(val.mag, mag)); 1451 resultMag = trustedStripLeadingZeroInts(resultMag); 1452 return new BigInteger(resultMag, cmp == signum ? 1 : -1); 1453 } 1454 1455 /** 1456 * Subtracts the contents of the second int arrays (little) from the 1457 * first (big). The first int array (big) must represent a larger number 1458 * than the second. This method allocates the space necessary to hold the 1459 * answer. 1460 */ subtract(int[] big, int[] little)1461 private static int[] subtract(int[] big, int[] little) { 1462 int bigIndex = big.length; 1463 int result[] = new int[bigIndex]; 1464 int littleIndex = little.length; 1465 long difference = 0; 1466 1467 // Subtract common parts of both numbers 1468 while (littleIndex > 0) { 1469 difference = (big[--bigIndex] & LONG_MASK) - 1470 (little[--littleIndex] & LONG_MASK) + 1471 (difference >> 32); 1472 result[bigIndex] = (int)difference; 1473 } 1474 1475 // Subtract remainder of longer number while borrow propagates 1476 boolean borrow = (difference >> 32 != 0); 1477 while (bigIndex > 0 && borrow) 1478 borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1); 1479 1480 // Copy remainder of longer number 1481 while (bigIndex > 0) 1482 result[--bigIndex] = big[bigIndex]; 1483 1484 return result; 1485 } 1486 1487 /** 1488 * Returns a BigInteger whose value is {@code (this * val)}. 1489 * 1490 * @implNote An implementation may offer better algorithmic 1491 * performance when {@code val == this}. 1492 * 1493 * @param val value to be multiplied by this BigInteger. 1494 * @return {@code this * val} 1495 */ multiply(@onNull BigInteger val)1496 @NonNull public BigInteger multiply(@NonNull BigInteger val) { 1497 return multiply(val, false); 1498 } 1499 1500 /** 1501 * Returns a BigInteger whose value is {@code (this * val)}. If 1502 * the invocation is recursive certain overflow checks are skipped. 1503 * 1504 * @param val value to be multiplied by this BigInteger. 1505 * @param isRecursion whether this is a recursive invocation 1506 * @return {@code this * val} 1507 */ multiply(@onNull BigInteger val, boolean isRecursion)1508 @NonNull private BigInteger multiply(@NonNull BigInteger val, boolean isRecursion) { 1509 if (val.signum == 0 || signum == 0) 1510 return ZERO; 1511 1512 int xlen = mag.length; 1513 1514 // BEGIN Android-changed: Fall back to the boringssl implementation for 1515 // large arguments. 1516 int ylen = val.mag.length; 1517 1518 final int BORINGSSL_MUL_THRESHOLD = 50; 1519 1520 int resultSign = signum == val.signum ? 1 : -1; 1521 if ((xlen < BORINGSSL_MUL_THRESHOLD) || (ylen < BORINGSSL_MUL_THRESHOLD)) { 1522 if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD) { 1523 // Helps less than boringssl fallback; prefer that. 1524 return square(); 1525 } 1526 1527 if (val.mag.length == 1) { 1528 return multiplyByInt(mag,val.mag[0], resultSign); 1529 } 1530 if (mag.length == 1) { 1531 return multiplyByInt(val.mag,mag[0], resultSign); 1532 } 1533 int[] result = multiplyToLen(mag, xlen, 1534 val.mag, ylen, null); 1535 result = trustedStripLeadingZeroInts(result); 1536 return new BigInteger(result, resultSign); 1537 } else { 1538 long xBN = 0, yBN = 0, resultBN = 0; 1539 try { 1540 xBN = bigEndInts2NewBN(mag, /* neg= */false); 1541 yBN = bigEndInts2NewBN(val.mag, /* neg= */false); 1542 resultBN = NativeBN.BN_new(); 1543 NativeBN.BN_mul(resultBN, xBN, yBN); 1544 return new BigInteger(resultSign, bn2BigEndInts(resultBN)); 1545 } finally { 1546 NativeBN.BN_free(xBN); 1547 NativeBN.BN_free(yBN); 1548 NativeBN.BN_free(resultBN); 1549 } 1550 1551 /* 1552 if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) { 1553 return multiplyKaratsuba(this, val); 1554 } else { 1555 // 1556 // In "Hacker's Delight" section 2-13, p.33, it is explained 1557 // that if x and y are unsigned 32-bit quantities and m and n 1558 // are their respective numbers of leading zeros within 32 bits, 1559 // then the number of leading zeros within their product as a 1560 // 64-bit unsigned quantity is either m + n or m + n + 1. If 1561 // their product is not to overflow, it cannot exceed 32 bits, 1562 // and so the number of leading zeros of the product within 64 1563 // bits must be at least 32, i.e., the leftmost set bit is at 1564 // zero-relative position 31 or less. 1565 // 1566 // From the above there are three cases: 1567 // 1568 // m + n leftmost set bit condition 1569 // ----- ---------------- --------- 1570 // >= 32 x <= 64 - 32 = 32 no overflow 1571 // == 31 x >= 64 - 32 = 32 possible overflow 1572 // <= 30 x >= 64 - 31 = 33 definite overflow 1573 // 1574 // The "possible overflow" condition cannot be detected by 1575 // examning data lengths alone and requires further calculation. 1576 // 1577 // By analogy, if 'this' and 'val' have m and n as their 1578 // respective numbers of leading zeros within 32*MAX_MAG_LENGTH 1579 // bits, then: 1580 // 1581 // m + n >= 32*MAX_MAG_LENGTH no overflow 1582 // m + n == 32*MAX_MAG_LENGTH - 1 possible overflow 1583 // m + n <= 32*MAX_MAG_LENGTH - 2 definite overflow 1584 // 1585 // Note however that if the number of ints in the result 1586 // were to be MAX_MAG_LENGTH and mag[0] < 0, then there would 1587 // be overflow. As a result the leftmost bit (of mag[0]) cannot 1588 // be used and the constraints must be adjusted by one bit to: 1589 // 1590 // m + n > 32*MAX_MAG_LENGTH no overflow 1591 // m + n == 32*MAX_MAG_LENGTH possible overflow 1592 // m + n < 32*MAX_MAG_LENGTH definite overflow 1593 // 1594 // The foregoing leading zero-based discussion is for clarity 1595 // only. The actual calculations use the estimated bit length 1596 // of the product as this is more natural to the internal 1597 // array representation of the magnitude which has no leading 1598 // zero elements. 1599 // 1600 if (!isRecursion) { 1601 // The bitLength() instance method is not used here as we 1602 // are only considering the magnitudes as non-negative. The 1603 // Toom-Cook multiplication algorithm determines the sign 1604 // at its end from the two signum values. 1605 if (bitLength(mag, mag.length) + 1606 bitLength(val.mag, val.mag.length) > 1607 32L*MAX_MAG_LENGTH) { 1608 reportOverflow(); 1609 } 1610 } 1611 1612 return multiplyToomCook3(this, val); 1613 } 1614 */ 1615 } 1616 } 1617 multiplyByInt(int[] x, int y, int sign)1618 @NonNull private static BigInteger multiplyByInt(int[] x, int y, int sign) { 1619 if (Integer.bitCount(y) == 1) { 1620 return new BigInteger(shiftLeft(x,Integer.numberOfTrailingZeros(y)), sign); 1621 } 1622 int xlen = x.length; 1623 int[] rmag = new int[xlen + 1]; 1624 long carry = 0; 1625 long yl = y & LONG_MASK; 1626 int rstart = rmag.length - 1; 1627 for (int i = xlen - 1; i >= 0; i--) { 1628 long product = (x[i] & LONG_MASK) * yl + carry; 1629 rmag[rstart--] = (int)product; 1630 carry = product >>> 32; 1631 } 1632 if (carry == 0L) { 1633 rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length); 1634 } else { 1635 rmag[rstart] = (int)carry; 1636 } 1637 return new BigInteger(rmag, sign); 1638 } 1639 1640 /** 1641 * Package private methods used by BigDecimal code to multiply a BigInteger 1642 * with a long. Assumes v is not equal to INFLATED. 1643 */ multiply(long v)1644 @NonNull BigInteger multiply(long v) { 1645 if (v == 0 || signum == 0) 1646 return ZERO; 1647 if (v == BigDecimal.INFLATED) 1648 return multiply(BigInteger.valueOf(v)); 1649 int rsign = (v > 0 ? signum : -signum); 1650 if (v < 0) 1651 v = -v; 1652 long dh = v >>> 32; // higher order bits 1653 long dl = v & LONG_MASK; // lower order bits 1654 1655 int xlen = mag.length; 1656 int[] value = mag; 1657 int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]); 1658 long carry = 0; 1659 int rstart = rmag.length - 1; 1660 for (int i = xlen - 1; i >= 0; i--) { 1661 long product = (value[i] & LONG_MASK) * dl + carry; 1662 rmag[rstart--] = (int)product; 1663 carry = product >>> 32; 1664 } 1665 rmag[rstart] = (int)carry; 1666 if (dh != 0L) { 1667 carry = 0; 1668 rstart = rmag.length - 2; 1669 for (int i = xlen - 1; i >= 0; i--) { 1670 long product = (value[i] & LONG_MASK) * dh + 1671 (rmag[rstart] & LONG_MASK) + carry; 1672 rmag[rstart--] = (int)product; 1673 carry = product >>> 32; 1674 } 1675 rmag[0] = (int)carry; 1676 } 1677 if (carry == 0L) 1678 rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length); 1679 return new BigInteger(rmag, rsign); 1680 } 1681 1682 /** 1683 * Multiplies int arrays x and y to the specified lengths and places 1684 * the result into z. There will be no leading zeros in the resultant array. 1685 */ multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z)1686 private static int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) { 1687 int xstart = xlen - 1; 1688 int ystart = ylen - 1; 1689 1690 if (z == null || z.length < (xlen+ ylen)) 1691 z = new int[xlen+ylen]; 1692 1693 long carry = 0; 1694 for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) { 1695 long product = (y[j] & LONG_MASK) * 1696 (x[xstart] & LONG_MASK) + carry; 1697 z[k] = (int)product; 1698 carry = product >>> 32; 1699 } 1700 z[xstart] = (int)carry; 1701 1702 for (int i = xstart-1; i >= 0; i--) { 1703 carry = 0; 1704 for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) { 1705 long product = (y[j] & LONG_MASK) * 1706 (x[i] & LONG_MASK) + 1707 (z[k] & LONG_MASK) + carry; 1708 z[k] = (int)product; 1709 carry = product >>> 32; 1710 } 1711 z[i] = (int)carry; 1712 } 1713 return z; 1714 } 1715 1716 /** 1717 * Multiplies two BigIntegers using the Karatsuba multiplication 1718 * algorithm. This is a recursive divide-and-conquer algorithm which is 1719 * more efficient for large numbers than what is commonly called the 1720 * "grade-school" algorithm used in multiplyToLen. If the numbers to be 1721 * multiplied have length n, the "grade-school" algorithm has an 1722 * asymptotic complexity of O(n^2). In contrast, the Karatsuba algorithm 1723 * has complexity of O(n^(log2(3))), or O(n^1.585). It achieves this 1724 * increased performance by doing 3 multiplies instead of 4 when 1725 * evaluating the product. As it has some overhead, should be used when 1726 * both numbers are larger than a certain threshold (found 1727 * experimentally). 1728 * 1729 * See: http://en.wikipedia.org/wiki/Karatsuba_algorithm 1730 */ multiplyKaratsuba(@onNull BigInteger x, @NonNull BigInteger y)1731 @NonNull private static BigInteger multiplyKaratsuba(@NonNull BigInteger x, @NonNull BigInteger y) { 1732 int xlen = x.mag.length; 1733 int ylen = y.mag.length; 1734 1735 // The number of ints in each half of the number. 1736 int half = (Math.max(xlen, ylen)+1) / 2; 1737 1738 // xl and yl are the lower halves of x and y respectively, 1739 // xh and yh are the upper halves. 1740 BigInteger xl = x.getLower(half); 1741 BigInteger xh = x.getUpper(half); 1742 BigInteger yl = y.getLower(half); 1743 BigInteger yh = y.getUpper(half); 1744 1745 BigInteger p1 = xh.multiply(yh); // p1 = xh*yh 1746 BigInteger p2 = xl.multiply(yl); // p2 = xl*yl 1747 1748 // p3=(xh+xl)*(yh+yl) 1749 BigInteger p3 = xh.add(xl).multiply(yh.add(yl)); 1750 1751 // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2 1752 BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2); 1753 1754 if (x.signum != y.signum) { 1755 return result.negate(); 1756 } else { 1757 return result; 1758 } 1759 } 1760 1761 /** 1762 * Multiplies two BigIntegers using a 3-way Toom-Cook multiplication 1763 * algorithm. This is a recursive divide-and-conquer algorithm which is 1764 * more efficient for large numbers than what is commonly called the 1765 * "grade-school" algorithm used in multiplyToLen. If the numbers to be 1766 * multiplied have length n, the "grade-school" algorithm has an 1767 * asymptotic complexity of O(n^2). In contrast, 3-way Toom-Cook has a 1768 * complexity of about O(n^1.465). It achieves this increased asymptotic 1769 * performance by breaking each number into three parts and by doing 5 1770 * multiplies instead of 9 when evaluating the product. Due to overhead 1771 * (additions, shifts, and one division) in the Toom-Cook algorithm, it 1772 * should only be used when both numbers are larger than a certain 1773 * threshold (found experimentally). This threshold is generally larger 1774 * than that for Karatsuba multiplication, so this algorithm is generally 1775 * only used when numbers become significantly larger. 1776 * 1777 * The algorithm used is the "optimal" 3-way Toom-Cook algorithm outlined 1778 * by Marco Bodrato. 1779 * 1780 * See: http://bodrato.it/toom-cook/ 1781 * http://bodrato.it/papers/#WAIFI2007 1782 * 1783 * "Towards Optimal Toom-Cook Multiplication for Univariate and 1784 * Multivariate Polynomials in Characteristic 2 and 0." by Marco BODRATO; 1785 * In C.Carlet and B.Sunar, Eds., "WAIFI'07 proceedings", p. 116-133, 1786 * LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007. 1787 * 1788 */ multiplyToomCook3(@onNull BigInteger a, @NonNull BigInteger b)1789 @NonNull private static BigInteger multiplyToomCook3(@NonNull BigInteger a, @NonNull BigInteger b) { 1790 int alen = a.mag.length; 1791 int blen = b.mag.length; 1792 1793 int largest = Math.max(alen, blen); 1794 1795 // k is the size (in ints) of the lower-order slices. 1796 int k = (largest+2)/3; // Equal to ceil(largest/3) 1797 1798 // r is the size (in ints) of the highest-order slice. 1799 int r = largest - 2*k; 1800 1801 // Obtain slices of the numbers. a2 and b2 are the most significant 1802 // bits of the numbers a and b, and a0 and b0 the least significant. 1803 BigInteger a0, a1, a2, b0, b1, b2; 1804 a2 = a.getToomSlice(k, r, 0, largest); 1805 a1 = a.getToomSlice(k, r, 1, largest); 1806 a0 = a.getToomSlice(k, r, 2, largest); 1807 b2 = b.getToomSlice(k, r, 0, largest); 1808 b1 = b.getToomSlice(k, r, 1, largest); 1809 b0 = b.getToomSlice(k, r, 2, largest); 1810 1811 BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1; 1812 1813 v0 = a0.multiply(b0, true); 1814 da1 = a2.add(a0); 1815 db1 = b2.add(b0); 1816 vm1 = da1.subtract(a1).multiply(db1.subtract(b1), true); 1817 da1 = da1.add(a1); 1818 db1 = db1.add(b1); 1819 v1 = da1.multiply(db1, true); 1820 v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply( 1821 db1.add(b2).shiftLeft(1).subtract(b0), true); 1822 vinf = a2.multiply(b2, true); 1823 1824 // The algorithm requires two divisions by 2 and one by 3. 1825 // All divisions are known to be exact, that is, they do not produce 1826 // remainders, and all results are positive. The divisions by 2 are 1827 // implemented as right shifts which are relatively efficient, leaving 1828 // only an exact division by 3, which is done by a specialized 1829 // linear-time algorithm. 1830 t2 = v2.subtract(vm1).exactDivideBy3(); 1831 tm1 = v1.subtract(vm1).shiftRight(1); 1832 t1 = v1.subtract(v0); 1833 t2 = t2.subtract(t1).shiftRight(1); 1834 t1 = t1.subtract(tm1).subtract(vinf); 1835 t2 = t2.subtract(vinf.shiftLeft(1)); 1836 tm1 = tm1.subtract(t2); 1837 1838 // Number of bits to shift left. 1839 int ss = k*32; 1840 1841 BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0); 1842 1843 if (a.signum != b.signum) { 1844 return result.negate(); 1845 } else { 1846 return result; 1847 } 1848 } 1849 1850 1851 /** 1852 * Returns a slice of a BigInteger for use in Toom-Cook multiplication. 1853 * 1854 * @param lowerSize The size of the lower-order bit slices. 1855 * @param upperSize The size of the higher-order bit slices. 1856 * @param slice The index of which slice is requested, which must be a 1857 * number from 0 to size-1. Slice 0 is the highest-order bits, and slice 1858 * size-1 are the lowest-order bits. Slice 0 may be of different size than 1859 * the other slices. 1860 * @param fullsize The size of the larger integer array, used to align 1861 * slices to the appropriate position when multiplying different-sized 1862 * numbers. 1863 */ getToomSlice(int lowerSize, int upperSize, int slice, int fullsize)1864 @NonNull private BigInteger getToomSlice(int lowerSize, int upperSize, int slice, 1865 int fullsize) { 1866 int start, end, sliceSize, len, offset; 1867 1868 len = mag.length; 1869 offset = fullsize - len; 1870 1871 if (slice == 0) { 1872 start = 0 - offset; 1873 end = upperSize - 1 - offset; 1874 } else { 1875 start = upperSize + (slice-1)*lowerSize - offset; 1876 end = start + lowerSize - 1; 1877 } 1878 1879 if (start < 0) { 1880 start = 0; 1881 } 1882 if (end < 0) { 1883 return ZERO; 1884 } 1885 1886 sliceSize = (end-start) + 1; 1887 1888 if (sliceSize <= 0) { 1889 return ZERO; 1890 } 1891 1892 // While performing Toom-Cook, all slices are positive and 1893 // the sign is adjusted when the final number is composed. 1894 if (start == 0 && sliceSize >= len) { 1895 return this.abs(); 1896 } 1897 1898 int intSlice[] = new int[sliceSize]; 1899 System.arraycopy(mag, start, intSlice, 0, sliceSize); 1900 1901 return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1); 1902 } 1903 1904 /** 1905 * Does an exact division (that is, the remainder is known to be zero) 1906 * of the specified number by 3. This is used in Toom-Cook 1907 * multiplication. This is an efficient algorithm that runs in linear 1908 * time. If the argument is not exactly divisible by 3, results are 1909 * undefined. Note that this is expected to be called with positive 1910 * arguments only. 1911 */ exactDivideBy3()1912 @NonNull private BigInteger exactDivideBy3() { 1913 int len = mag.length; 1914 int[] result = new int[len]; 1915 long x, w, q, borrow; 1916 borrow = 0L; 1917 for (int i=len-1; i >= 0; i--) { 1918 x = (mag[i] & LONG_MASK); 1919 w = x - borrow; 1920 if (borrow > x) { // Did we make the number go negative? 1921 borrow = 1L; 1922 } else { 1923 borrow = 0L; 1924 } 1925 1926 // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32). Thus, 1927 // the effect of this is to divide by 3 (mod 2^32). 1928 // This is much faster than division on most architectures. 1929 q = (w * 0xAAAAAAABL) & LONG_MASK; 1930 result[i] = (int) q; 1931 1932 // Now check the borrow. The second check can of course be 1933 // eliminated if the first fails. 1934 if (q >= 0x55555556L) { 1935 borrow++; 1936 if (q >= 0xAAAAAAABL) 1937 borrow++; 1938 } 1939 } 1940 result = trustedStripLeadingZeroInts(result); 1941 return new BigInteger(result, signum); 1942 } 1943 1944 /** 1945 * Returns a new BigInteger representing n lower ints of the number. 1946 * This is used by Karatsuba multiplication and Karatsuba squaring. 1947 */ getLower(int n)1948 @NonNull private BigInteger getLower(int n) { 1949 int len = mag.length; 1950 1951 if (len <= n) { 1952 return abs(); 1953 } 1954 1955 int lowerInts[] = new int[n]; 1956 System.arraycopy(mag, len-n, lowerInts, 0, n); 1957 1958 return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1); 1959 } 1960 1961 /** 1962 * Returns a new BigInteger representing mag.length-n upper 1963 * ints of the number. This is used by Karatsuba multiplication and 1964 * Karatsuba squaring. 1965 */ getUpper(int n)1966 @NonNull private BigInteger getUpper(int n) { 1967 int len = mag.length; 1968 1969 if (len <= n) { 1970 return ZERO; 1971 } 1972 1973 int upperLen = len - n; 1974 int upperInts[] = new int[upperLen]; 1975 System.arraycopy(mag, 0, upperInts, 0, upperLen); 1976 1977 return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1); 1978 } 1979 1980 // Squaring 1981 1982 /** 1983 * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}. 1984 * 1985 * @return {@code this<sup>2</sup>} 1986 */ square()1987 @NonNull private BigInteger square() { 1988 return square(false); 1989 } 1990 1991 /** 1992 * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}. If 1993 * the invocation is recursive certain overflow checks are skipped. 1994 * 1995 * @param isRecursion whether this is a recursive invocation 1996 * @return {@code this<sup>2</sup>} 1997 */ square(boolean isRecursion)1998 @NonNull private BigInteger square(boolean isRecursion) { 1999 if (signum == 0) { 2000 return ZERO; 2001 } 2002 int len = mag.length; 2003 2004 if (len < KARATSUBA_SQUARE_THRESHOLD) { 2005 int[] z = squareToLen(mag, len, null); 2006 return new BigInteger(trustedStripLeadingZeroInts(z), 1); 2007 } else { 2008 if (len < TOOM_COOK_SQUARE_THRESHOLD) { 2009 return squareKaratsuba(); 2010 } else { 2011 // 2012 // For a discussion of overflow detection see multiply() 2013 // 2014 if (!isRecursion) { 2015 if (bitLength(mag, mag.length) > 16L*MAX_MAG_LENGTH) { 2016 reportOverflow(); 2017 } 2018 } 2019 2020 return squareToomCook3(); 2021 } 2022 } 2023 } 2024 2025 /** 2026 * Squares the contents of the int array x. The result is placed into the 2027 * int array z. The contents of x are not changed. 2028 */ squareToLen(int[] x, int len, int[] z)2029 private static final int[] squareToLen(int[] x, int len, int[] z) { 2030 int zlen = len << 1; 2031 if (z == null || z.length < zlen) 2032 z = new int[zlen]; 2033 2034 // Execute checks before calling intrinsified method. 2035 implSquareToLenChecks(x, len, z, zlen); 2036 return implSquareToLen(x, len, z, zlen); 2037 } 2038 2039 /** 2040 * Parameters validation. 2041 */ implSquareToLenChecks(int[] x, int len, int[] z, int zlen)2042 private static void implSquareToLenChecks(int[] x, int len, int[] z, int zlen) throws RuntimeException { 2043 if (len < 1) { 2044 throw new IllegalArgumentException("invalid input length: " + len); 2045 } 2046 if (len > x.length) { 2047 throw new IllegalArgumentException("input length out of bound: " + 2048 len + " > " + x.length); 2049 } 2050 if (len * 2 > z.length) { 2051 throw new IllegalArgumentException("input length out of bound: " + 2052 (len * 2) + " > " + z.length); 2053 } 2054 if (zlen < 1) { 2055 throw new IllegalArgumentException("invalid input length: " + zlen); 2056 } 2057 if (zlen > z.length) { 2058 throw new IllegalArgumentException("input length out of bound: " + 2059 len + " > " + z.length); 2060 } 2061 } 2062 2063 /** 2064 * Java Runtime may use intrinsic for this method. 2065 */ implSquareToLen(int[] x, int len, int[] z, int zlen)2066 private static final int[] implSquareToLen(int[] x, int len, int[] z, int zlen) { 2067 /* 2068 * The algorithm used here is adapted from Colin Plumb's C library. 2069 * Technique: Consider the partial products in the multiplication 2070 * of "abcde" by itself: 2071 * 2072 * a b c d e 2073 * * a b c d e 2074 * ================== 2075 * ae be ce de ee 2076 * ad bd cd dd de 2077 * ac bc cc cd ce 2078 * ab bb bc bd be 2079 * aa ab ac ad ae 2080 * 2081 * Note that everything above the main diagonal: 2082 * ae be ce de = (abcd) * e 2083 * ad bd cd = (abc) * d 2084 * ac bc = (ab) * c 2085 * ab = (a) * b 2086 * 2087 * is a copy of everything below the main diagonal: 2088 * de 2089 * cd ce 2090 * bc bd be 2091 * ab ac ad ae 2092 * 2093 * Thus, the sum is 2 * (off the diagonal) + diagonal. 2094 * 2095 * This is accumulated beginning with the diagonal (which 2096 * consist of the squares of the digits of the input), which is then 2097 * divided by two, the off-diagonal added, and multiplied by two 2098 * again. The low bit is simply a copy of the low bit of the 2099 * input, so it doesn't need special care. 2100 */ 2101 2102 // Store the squares, right shifted one bit (i.e., divided by 2) 2103 int lastProductLowWord = 0; 2104 for (int j=0, i=0; j < len; j++) { 2105 long piece = (x[j] & LONG_MASK); 2106 long product = piece * piece; 2107 z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33); 2108 z[i++] = (int)(product >>> 1); 2109 lastProductLowWord = (int)product; 2110 } 2111 2112 // Add in off-diagonal sums 2113 for (int i=len, offset=1; i > 0; i--, offset+=2) { 2114 int t = x[i-1]; 2115 t = mulAdd(z, x, offset, i-1, t); 2116 addOne(z, offset-1, i, t); 2117 } 2118 2119 // Shift back up and set low bit 2120 primitiveLeftShift(z, zlen, 1); 2121 z[zlen-1] |= x[len-1] & 1; 2122 2123 return z; 2124 } 2125 2126 /** 2127 * Squares a BigInteger using the Karatsuba squaring algorithm. It should 2128 * be used when both numbers are larger than a certain threshold (found 2129 * experimentally). It is a recursive divide-and-conquer algorithm that 2130 * has better asymptotic performance than the algorithm used in 2131 * squareToLen. 2132 */ squareKaratsuba()2133 @NonNull private BigInteger squareKaratsuba() { 2134 int half = (mag.length+1) / 2; 2135 2136 BigInteger xl = getLower(half); 2137 BigInteger xh = getUpper(half); 2138 2139 BigInteger xhs = xh.square(); // xhs = xh^2 2140 BigInteger xls = xl.square(); // xls = xl^2 2141 2142 // xh^2 << 64 + (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2 2143 return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls); 2144 } 2145 2146 /** 2147 * Squares a BigInteger using the 3-way Toom-Cook squaring algorithm. It 2148 * should be used when both numbers are larger than a certain threshold 2149 * (found experimentally). It is a recursive divide-and-conquer algorithm 2150 * that has better asymptotic performance than the algorithm used in 2151 * squareToLen or squareKaratsuba. 2152 */ squareToomCook3()2153 @NonNull private BigInteger squareToomCook3() { 2154 int len = mag.length; 2155 2156 // k is the size (in ints) of the lower-order slices. 2157 int k = (len+2)/3; // Equal to ceil(largest/3) 2158 2159 // r is the size (in ints) of the highest-order slice. 2160 int r = len - 2*k; 2161 2162 // Obtain slices of the numbers. a2 is the most significant 2163 // bits of the number, and a0 the least significant. 2164 BigInteger a0, a1, a2; 2165 a2 = getToomSlice(k, r, 0, len); 2166 a1 = getToomSlice(k, r, 1, len); 2167 a0 = getToomSlice(k, r, 2, len); 2168 BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1; 2169 2170 v0 = a0.square(true); 2171 da1 = a2.add(a0); 2172 vm1 = da1.subtract(a1).square(true); 2173 da1 = da1.add(a1); 2174 v1 = da1.square(true); 2175 vinf = a2.square(true); 2176 v2 = da1.add(a2).shiftLeft(1).subtract(a0).square(true); 2177 2178 // The algorithm requires two divisions by 2 and one by 3. 2179 // All divisions are known to be exact, that is, they do not produce 2180 // remainders, and all results are positive. The divisions by 2 are 2181 // implemented as right shifts which are relatively efficient, leaving 2182 // only a division by 3. 2183 // The division by 3 is done by an optimized algorithm for this case. 2184 t2 = v2.subtract(vm1).exactDivideBy3(); 2185 tm1 = v1.subtract(vm1).shiftRight(1); 2186 t1 = v1.subtract(v0); 2187 t2 = t2.subtract(t1).shiftRight(1); 2188 t1 = t1.subtract(tm1).subtract(vinf); 2189 t2 = t2.subtract(vinf.shiftLeft(1)); 2190 tm1 = tm1.subtract(t2); 2191 2192 // Number of bits to shift left. 2193 int ss = k*32; 2194 2195 return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0); 2196 } 2197 2198 // Division 2199 2200 2201 // BEGIN Android-modified: Fall back to boringssl for large problems. 2202 private static final int BORINGSSL_DIV_THRESHOLD = 40; 2203 private static final int BORINGSSL_DIV_OFFSET = 20; 2204 2205 /** 2206 * Returns a BigInteger whose value is {@code (this / val)}. 2207 * 2208 * @param val value by which this BigInteger is to be divided. 2209 * @return {@code this / val} 2210 * @throws ArithmeticException if {@code val} is zero. 2211 */ divide(@onNull BigInteger val)2212 @NonNull public BigInteger divide(@NonNull BigInteger val) { 2213 // if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || 2214 // mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) { 2215 if (mag.length < BORINGSSL_DIV_THRESHOLD || 2216 mag.length - val.mag.length < BORINGSSL_DIV_OFFSET) { 2217 return divideKnuth(val); 2218 } else { 2219 return divideAndRemainder(val)[0]; 2220 // return divideBurnikelZiegler(val); 2221 } 2222 } 2223 // END Android-modified: Fall back to boringssl for large problems. 2224 2225 2226 /** 2227 * Returns a BigInteger whose value is {@code (this / val)} using an O(n^2) algorithm from Knuth. 2228 * 2229 * @param val value by which this BigInteger is to be divided. 2230 * @return {@code this / val} 2231 * @throws ArithmeticException if {@code val} is zero. 2232 * @see MutableBigInteger#divideKnuth(MutableBigInteger, MutableBigInteger, boolean) 2233 */ divideKnuth(@onNull BigInteger val)2234 @NonNull private BigInteger divideKnuth(@NonNull BigInteger val) { 2235 MutableBigInteger q = new MutableBigInteger(), 2236 a = new MutableBigInteger(this.mag), 2237 b = new MutableBigInteger(val.mag); 2238 2239 a.divideKnuth(b, q, false); 2240 return q.toBigInteger(this.signum * val.signum); 2241 } 2242 2243 /** 2244 * Returns an array of two BigIntegers containing {@code (this / val)} 2245 * followed by {@code (this % val)}. 2246 * 2247 * @param val value by which this BigInteger is to be divided, and the 2248 * remainder computed. 2249 * @return an array of two BigIntegers: the quotient {@code (this / val)} 2250 * is the initial element, and the remainder {@code (this % val)} 2251 * is the final element. 2252 * @throws ArithmeticException if {@code val} is zero. 2253 */ divideAndRemainder(@onNull BigInteger val)2254 @NonNull public BigInteger[] divideAndRemainder(@NonNull BigInteger val) { 2255 // BEGIN Android-modified: Fall back to boringssl for large problems. 2256 2257 // if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || 2258 // mag.length - val.mag < BURNIKEL_ZIEGLER_OFFSET) { 2259 if (val.mag.length < BORINGSSL_DIV_THRESHOLD || 2260 mag.length < BORINGSSL_DIV_OFFSET || 2261 mag.length - val.mag.length < BORINGSSL_DIV_OFFSET) { 2262 return divideAndRemainderKnuth(val); 2263 } else { 2264 int quotSign = signum == val.signum ? 1 : -1; // 0 divided doesn't get here. 2265 long xBN = 0, yBN = 0, quotBN = 0, remBN = 0; 2266 try { 2267 xBN = bigEndInts2NewBN(mag, /* neg= */false); 2268 yBN = bigEndInts2NewBN(val.mag, /* neg= */false); 2269 quotBN = NativeBN.BN_new(); 2270 remBN = NativeBN.BN_new(); 2271 NativeBN.BN_div(quotBN, remBN, xBN, yBN); 2272 BigInteger quotient = new BigInteger(quotSign, bn2BigEndInts(quotBN)); 2273 // The sign of a zero quotient is fixed by the constructor. 2274 BigInteger remainder = new BigInteger(signum, bn2BigEndInts(remBN)); 2275 BigInteger[] result = {quotient, remainder}; 2276 return result; 2277 } finally { 2278 NativeBN.BN_free(xBN); 2279 NativeBN.BN_free(yBN); 2280 NativeBN.BN_free(quotBN); 2281 NativeBN.BN_free(remBN); 2282 } 2283 // return divideAndRemainderBurnikelZiegler(val); 2284 } 2285 // END Android-modified: Fall back to boringssl for large problems. 2286 } 2287 2288 /** Long division */ divideAndRemainderKnuth(@onNull BigInteger val)2289 @NonNull private BigInteger[] divideAndRemainderKnuth(@NonNull BigInteger val) { 2290 BigInteger[] result = new BigInteger[2]; 2291 MutableBigInteger q = new MutableBigInteger(), 2292 a = new MutableBigInteger(this.mag), 2293 b = new MutableBigInteger(val.mag); 2294 MutableBigInteger r = a.divideKnuth(b, q); 2295 result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1); 2296 result[1] = r.toBigInteger(this.signum); 2297 return result; 2298 } 2299 2300 /** 2301 * Returns a BigInteger whose value is {@code (this % val)}. 2302 * 2303 * @param val value by which this BigInteger is to be divided, and the 2304 * remainder computed. 2305 * @return {@code this % val} 2306 * @throws ArithmeticException if {@code val} is zero. 2307 */ remainder(@onNull BigInteger val)2308 @NonNull public BigInteger remainder(@NonNull BigInteger val) { 2309 // BEGIN Android-modified: Fall back to boringssl for large problems. 2310 // if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || 2311 // mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) { 2312 if (val.mag.length < BORINGSSL_DIV_THRESHOLD || 2313 mag.length - val.mag.length < BORINGSSL_DIV_THRESHOLD) { 2314 return remainderKnuth(val); 2315 } else { 2316 return divideAndRemainder(val)[1]; 2317 // return remainderBurnikelZiegler(val); 2318 } 2319 // END Android-modified: Fall back to boringssl for large problems. 2320 } 2321 2322 /** Long division */ remainderKnuth(@onNull BigInteger val)2323 @NonNull private BigInteger remainderKnuth(@NonNull BigInteger val) { 2324 MutableBigInteger q = new MutableBigInteger(), 2325 a = new MutableBigInteger(this.mag), 2326 b = new MutableBigInteger(val.mag); 2327 2328 return a.divideKnuth(b, q).toBigInteger(this.signum); 2329 } 2330 2331 /** 2332 * Calculates {@code this / val} using the Burnikel-Ziegler algorithm. 2333 * @param val the divisor 2334 * @return {@code this / val} 2335 */ divideBurnikelZiegler(@onNull BigInteger val)2336 @NonNull private BigInteger divideBurnikelZiegler(@NonNull BigInteger val) { 2337 return divideAndRemainderBurnikelZiegler(val)[0]; 2338 } 2339 2340 /** 2341 * Calculates {@code this % val} using the Burnikel-Ziegler algorithm. 2342 * @param val the divisor 2343 * @return {@code this % val} 2344 */ remainderBurnikelZiegler(@onNull BigInteger val)2345 @NonNull private BigInteger remainderBurnikelZiegler(@NonNull BigInteger val) { 2346 return divideAndRemainderBurnikelZiegler(val)[1]; 2347 } 2348 2349 /** 2350 * Computes {@code this / val} and {@code this % val} using the 2351 * Burnikel-Ziegler algorithm. 2352 * @param val the divisor 2353 * @return an array containing the quotient and remainder 2354 */ divideAndRemainderBurnikelZiegler(@onNull BigInteger val)2355 @NonNull private BigInteger[] divideAndRemainderBurnikelZiegler(@NonNull BigInteger val) { 2356 MutableBigInteger q = new MutableBigInteger(); 2357 MutableBigInteger r = new MutableBigInteger(this).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q); 2358 BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum); 2359 BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum); 2360 return new BigInteger[] {qBigInt, rBigInt}; 2361 } 2362 2363 /** 2364 * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>. 2365 * Note that {@code exponent} is an integer rather than a BigInteger. 2366 * 2367 * @param exponent exponent to which this BigInteger is to be raised. 2368 * @return <tt>this<sup>exponent</sup></tt> 2369 * @throws ArithmeticException {@code exponent} is negative. (This would 2370 * cause the operation to yield a non-integer value.) 2371 */ pow(int exponent)2372 @NonNull public BigInteger pow(int exponent) { 2373 if (exponent < 0) { 2374 throw new ArithmeticException("Negative exponent"); 2375 } 2376 if (signum == 0) { 2377 return (exponent == 0 ? ONE : this); 2378 } 2379 2380 BigInteger partToSquare = this.abs(); 2381 2382 // Factor out powers of two from the base, as the exponentiation of 2383 // these can be done by left shifts only. 2384 // The remaining part can then be exponentiated faster. The 2385 // powers of two will be multiplied back at the end. 2386 int powersOfTwo = partToSquare.getLowestSetBit(); 2387 long bitsToShiftLong = (long)powersOfTwo * exponent; 2388 if (bitsToShiftLong > Integer.MAX_VALUE) { 2389 reportOverflow(); 2390 } 2391 int bitsToShift = (int)bitsToShiftLong; 2392 2393 int remainingBits; 2394 2395 // Factor the powers of two out quickly by shifting right, if needed. 2396 if (powersOfTwo > 0) { 2397 partToSquare = partToSquare.shiftRight(powersOfTwo); 2398 remainingBits = partToSquare.bitLength(); 2399 if (remainingBits == 1) { // Nothing left but +/- 1? 2400 if (signum < 0 && (exponent&1) == 1) { 2401 return NEGATIVE_ONE.shiftLeft(bitsToShift); 2402 } else { 2403 return ONE.shiftLeft(bitsToShift); 2404 } 2405 } 2406 } else { 2407 remainingBits = partToSquare.bitLength(); 2408 if (remainingBits == 1) { // Nothing left but +/- 1? 2409 if (signum < 0 && (exponent&1) == 1) { 2410 return NEGATIVE_ONE; 2411 } else { 2412 return ONE; 2413 } 2414 } 2415 } 2416 2417 // This is a quick way to approximate the size of the result, 2418 // similar to doing log2[n] * exponent. This will give an upper bound 2419 // of how big the result can be, and which algorithm to use. 2420 long scaleFactor = (long)remainingBits * exponent; 2421 2422 // Use slightly different algorithms for small and large operands. 2423 // See if the result will safely fit into a long. (Largest 2^63-1) 2424 if (partToSquare.mag.length == 1 && scaleFactor <= 62) { 2425 // Small number algorithm. Everything fits into a long. 2426 int newSign = (signum <0 && (exponent&1) == 1 ? -1 : 1); 2427 long result = 1; 2428 long baseToPow2 = partToSquare.mag[0] & LONG_MASK; 2429 2430 int workingExponent = exponent; 2431 2432 // Perform exponentiation using repeated squaring trick 2433 while (workingExponent != 0) { 2434 if ((workingExponent & 1) == 1) { 2435 result = result * baseToPow2; 2436 } 2437 2438 if ((workingExponent >>>= 1) != 0) { 2439 baseToPow2 = baseToPow2 * baseToPow2; 2440 } 2441 } 2442 2443 // Multiply back the powers of two (quickly, by shifting left) 2444 if (powersOfTwo > 0) { 2445 if (bitsToShift + scaleFactor <= 62) { // Fits in long? 2446 return valueOf((result << bitsToShift) * newSign); 2447 } else { 2448 return valueOf(result*newSign).shiftLeft(bitsToShift); 2449 } 2450 } else { 2451 return valueOf(result*newSign); 2452 } 2453 } else { 2454 if ((long)bitLength() * exponent / Integer.SIZE > MAX_MAG_LENGTH) { 2455 reportOverflow(); 2456 } 2457 2458 // Large number algorithm. This is basically identical to 2459 // the algorithm above, but calls multiply() and square() 2460 // which may use more efficient algorithms for large numbers. 2461 BigInteger answer = ONE; 2462 2463 int workingExponent = exponent; 2464 // Perform exponentiation using repeated squaring trick 2465 while (workingExponent != 0) { 2466 if ((workingExponent & 1) == 1) { 2467 answer = answer.multiply(partToSquare); 2468 } 2469 2470 if ((workingExponent >>>= 1) != 0) { 2471 partToSquare = partToSquare.square(); 2472 } 2473 } 2474 // Multiply back the (exponentiated) powers of two (quickly, 2475 // by shifting left) 2476 if (powersOfTwo > 0) { 2477 answer = answer.shiftLeft(bitsToShift); 2478 } 2479 2480 if (signum < 0 && (exponent&1) == 1) { 2481 return answer.negate(); 2482 } else { 2483 return answer; 2484 } 2485 } 2486 } 2487 2488 /** 2489 * Returns a BigInteger whose value is the greatest common divisor of 2490 * {@code abs(this)} and {@code abs(val)}. Returns 0 if 2491 * {@code this == 0 && val == 0}. 2492 * 2493 * @param val value with which the GCD is to be computed. 2494 * @return {@code GCD(abs(this), abs(val))} 2495 */ gcd(@onNull BigInteger val)2496 @NonNull public BigInteger gcd(@NonNull BigInteger val) { 2497 if (val.signum == 0) 2498 return this.abs(); 2499 else if (this.signum == 0) 2500 return val.abs(); 2501 2502 MutableBigInteger a = new MutableBigInteger(this); 2503 MutableBigInteger b = new MutableBigInteger(val); 2504 2505 MutableBigInteger result = a.hybridGCD(b); 2506 2507 return result.toBigInteger(1); 2508 } 2509 2510 /** 2511 * Package private method to return bit length for an integer. 2512 */ bitLengthForInt(int n)2513 static int bitLengthForInt(int n) { 2514 return 32 - Integer.numberOfLeadingZeros(n); 2515 } 2516 2517 /** 2518 * Left shift int array a up to len by n bits. Returns the array that 2519 * results from the shift since space may have to be reallocated. 2520 */ leftShift(int[] a, int len, int n)2521 private static int[] leftShift(int[] a, int len, int n) { 2522 int nInts = n >>> 5; 2523 int nBits = n&0x1F; 2524 int bitsInHighWord = bitLengthForInt(a[0]); 2525 2526 // If shift can be done without recopy, do so 2527 if (n <= (32-bitsInHighWord)) { 2528 primitiveLeftShift(a, len, nBits); 2529 return a; 2530 } else { // Array must be resized 2531 if (nBits <= (32-bitsInHighWord)) { 2532 int result[] = new int[nInts+len]; 2533 System.arraycopy(a, 0, result, 0, len); 2534 primitiveLeftShift(result, result.length, nBits); 2535 return result; 2536 } else { 2537 int result[] = new int[nInts+len+1]; 2538 System.arraycopy(a, 0, result, 0, len); 2539 primitiveRightShift(result, result.length, 32 - nBits); 2540 return result; 2541 } 2542 } 2543 } 2544 2545 // shifts a up to len right n bits assumes no leading zeros, 0<n<32 primitiveRightShift(int[] a, int len, int n)2546 static void primitiveRightShift(int[] a, int len, int n) { 2547 int n2 = 32 - n; 2548 for (int i=len-1, c=a[i]; i > 0; i--) { 2549 int b = c; 2550 c = a[i-1]; 2551 a[i] = (c << n2) | (b >>> n); 2552 } 2553 a[0] >>>= n; 2554 } 2555 2556 // shifts a up to len left n bits assumes no leading zeros, 0<=n<32 primitiveLeftShift(int[] a, int len, int n)2557 static void primitiveLeftShift(int[] a, int len, int n) { 2558 if (len == 0 || n == 0) 2559 return; 2560 2561 int n2 = 32 - n; 2562 for (int i=0, c=a[i], m=i+len-1; i < m; i++) { 2563 int b = c; 2564 c = a[i+1]; 2565 a[i] = (b << n) | (c >>> n2); 2566 } 2567 a[len-1] <<= n; 2568 } 2569 2570 /** 2571 * Calculate bitlength of contents of the first len elements an int array, 2572 * assuming there are no leading zero ints. 2573 */ bitLength(int[] val, int len)2574 private static int bitLength(int[] val, int len) { 2575 if (len == 0) 2576 return 0; 2577 return ((len - 1) << 5) + bitLengthForInt(val[0]); 2578 } 2579 2580 /** 2581 * Returns a BigInteger whose value is the absolute value of this 2582 * BigInteger. 2583 * 2584 * @return {@code abs(this)} 2585 */ abs()2586 @NonNull public BigInteger abs() { 2587 return (signum >= 0 ? this : this.negate()); 2588 } 2589 2590 /** 2591 * Returns a BigInteger whose value is {@code (-this)}. 2592 * 2593 * @return {@code -this} 2594 */ negate()2595 @NonNull public BigInteger negate() { 2596 return new BigInteger(this.mag, -this.signum); 2597 } 2598 2599 /** 2600 * Returns the signum function of this BigInteger. 2601 * 2602 * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or 2603 * positive. 2604 */ signum()2605 public int signum() { 2606 return this.signum; 2607 } 2608 2609 // Modular Arithmetic Operations 2610 2611 /** 2612 * Returns a BigInteger whose value is {@code (this mod m}). This method 2613 * differs from {@code remainder} in that it always returns a 2614 * <i>non-negative</i> BigInteger. 2615 * 2616 * @param m the modulus. 2617 * @return {@code this mod m} 2618 * @throws ArithmeticException {@code m} ≤ 0 2619 * @see #remainder 2620 */ mod(@onNull BigInteger m)2621 @NonNull public BigInteger mod(@NonNull BigInteger m) { 2622 if (m.signum <= 0) 2623 throw new ArithmeticException("BigInteger: modulus not positive"); 2624 2625 BigInteger result = this.remainder(m); 2626 return (result.signum >= 0 ? result : result.add(m)); 2627 } 2628 2629 // BEGIN Android-added: Support fallback to boringssl where it makes sense. 2630 // The conversion itself takes linear time, so this only makes sense for largish superlinear 2631 // operations. 2632 reverse(int[] arg)2633 private static int[] reverse(int[] arg) { 2634 int len = arg.length; 2635 int[] result = new int[len]; 2636 for (int i = 0; i < len; ++i) { 2637 result[i] = arg[len - i - 1]; 2638 } 2639 return result; 2640 } 2641 bigEndInts2NewBN(int[] beArray, boolean neg)2642 private static long /* BN */ bigEndInts2NewBN(int[] beArray, boolean neg) { 2643 // The input is an array of ints arranged in big-endian order, i.e. most significant int 2644 // first. BN deals with big-endian or little-endian byte arrays, so we need to reverse order. 2645 int[] leArray = reverse(beArray); 2646 long resultBN = NativeBN.BN_new(); 2647 NativeBN.litEndInts2bn(leArray, leArray.length, neg, resultBN); 2648 return resultBN; 2649 } 2650 bn2BigEndInts(long bn)2651 private int[] bn2BigEndInts(long bn) { 2652 return reverse(NativeBN.bn2litEndInts(bn)); 2653 } 2654 2655 // END Android-added: Support fallback to boringssl. 2656 2657 2658 /** 2659 * Returns a BigInteger whose value is 2660 * <tt>(this<sup>exponent</sup> mod m)</tt>. (Unlike {@code pow}, this 2661 * method permits negative exponents.) 2662 * 2663 * @param exponent the exponent. 2664 * @param m the modulus. 2665 * @return <tt>this<sup>exponent</sup> mod m</tt> 2666 * @throws ArithmeticException {@code m} ≤ 0 or the exponent is 2667 * negative and this BigInteger is not <i>relatively 2668 * prime</i> to {@code m}. 2669 * @see #modInverse 2670 */ modPow(@onNull BigInteger exponent, @NonNull BigInteger m)2671 @NonNull public BigInteger modPow(@NonNull BigInteger exponent, @NonNull BigInteger m) { 2672 if (m.signum <= 0) 2673 throw new ArithmeticException("BigInteger: modulus not positive"); 2674 2675 // Trivial cases 2676 if (exponent.signum == 0) 2677 return (m.equals(ONE) ? ZERO : ONE); 2678 2679 if (this.equals(ONE)) 2680 return (m.equals(ONE) ? ZERO : ONE); 2681 2682 if (this.equals(ZERO) && exponent.signum >= 0) 2683 return ZERO; 2684 2685 if (this.equals(negConst[1]) && (!exponent.testBit(0))) 2686 return (m.equals(ONE) ? ZERO : ONE); 2687 2688 boolean invertResult; 2689 if ((invertResult = (exponent.signum < 0))) 2690 exponent = exponent.negate(); 2691 2692 BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0 2693 ? this.mod(m) : this); 2694 BigInteger result; 2695 // BEGIN Android-added: Fall back to the boringssl implementation, which 2696 // is usually faster. 2697 final int BORINGSSL_MOD_EXP_THRESHOLD = 3; 2698 if (m.mag.length >= BORINGSSL_MOD_EXP_THRESHOLD) { 2699 long baseBN = 0, expBN = 0, modBN = 0, resultBN = 0; 2700 try { 2701 baseBN = bigEndInts2NewBN(base.mag, /* neg= */false); 2702 expBN = bigEndInts2NewBN(exponent.mag, /* neg= */false); 2703 modBN = bigEndInts2NewBN(m.mag, /* neg= */false); 2704 resultBN = NativeBN.BN_new(); 2705 NativeBN.BN_mod_exp(resultBN, baseBN, expBN, modBN); 2706 result = new BigInteger(1, bn2BigEndInts(resultBN)); 2707 // The sign of a zero result is fixed by the constructor. 2708 return (invertResult ? result.modInverse(m) : result); 2709 } finally { 2710 NativeBN.BN_free(baseBN); 2711 NativeBN.BN_free(expBN); 2712 NativeBN.BN_free(modBN); 2713 NativeBN.BN_free(resultBN); 2714 } 2715 } 2716 // END Android-added: Fall back to the boringssl implementation. 2717 if (m.testBit(0)) { // odd modulus 2718 result = base.oddModPow(exponent, m); 2719 } else { 2720 /* 2721 * Even modulus. Tear it into an "odd part" (m1) and power of two 2722 * (m2), exponentiate mod m1, manually exponentiate mod m2, and 2723 * use Chinese Remainder Theorem to combine results. 2724 */ 2725 2726 // Tear m apart into odd part (m1) and power of 2 (m2) 2727 int p = m.getLowestSetBit(); // Max pow of 2 that divides m 2728 2729 BigInteger m1 = m.shiftRight(p); // m/2**p 2730 BigInteger m2 = ONE.shiftLeft(p); // 2**p 2731 2732 // Calculate new base from m1 2733 BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0 2734 ? this.mod(m1) : this); 2735 2736 // Calculate (base ** exponent) mod m1. 2737 BigInteger a1 = (m1.equals(ONE) ? ZERO : 2738 base2.oddModPow(exponent, m1)); 2739 2740 // Calculate (this ** exponent) mod m2 2741 BigInteger a2 = base.modPow2(exponent, p); 2742 2743 // Combine results using Chinese Remainder Theorem 2744 BigInteger y1 = m2.modInverse(m1); 2745 BigInteger y2 = m1.modInverse(m2); 2746 2747 if (m.mag.length < MAX_MAG_LENGTH / 2) { 2748 result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m); 2749 } else { 2750 MutableBigInteger t1 = new MutableBigInteger(); 2751 new MutableBigInteger(a1.multiply(m2)).multiply(new MutableBigInteger(y1), t1); 2752 MutableBigInteger t2 = new MutableBigInteger(); 2753 new MutableBigInteger(a2.multiply(m1)).multiply(new MutableBigInteger(y2), t2); 2754 t1.add(t2); 2755 MutableBigInteger q = new MutableBigInteger(); 2756 result = t1.divide(new MutableBigInteger(m), q).toBigInteger(); 2757 } 2758 } 2759 2760 return (invertResult ? result.modInverse(m) : result); 2761 } 2762 2763 // Montgomery multiplication. These are wrappers for 2764 // implMontgomeryXX routines which are expected to be replaced by 2765 // virtual machine intrinsics. We don't use the intrinsics for 2766 // very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be 2767 // larger than any reasonable crypto key. montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv, int[] product)2768 private static int[] montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv, 2769 int[] product) { 2770 implMontgomeryMultiplyChecks(a, b, n, len, product); 2771 if (len > MONTGOMERY_INTRINSIC_THRESHOLD) { 2772 // Very long argument: do not use an intrinsic 2773 product = multiplyToLen(a, len, b, len, product); 2774 return montReduce(product, n, len, (int)inv); 2775 } else { 2776 return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len)); 2777 } 2778 } montgomerySquare(int[] a, int[] n, int len, long inv, int[] product)2779 private static int[] montgomerySquare(int[] a, int[] n, int len, long inv, 2780 int[] product) { 2781 implMontgomeryMultiplyChecks(a, a, n, len, product); 2782 if (len > MONTGOMERY_INTRINSIC_THRESHOLD) { 2783 // Very long argument: do not use an intrinsic 2784 product = squareToLen(a, len, product); 2785 return montReduce(product, n, len, (int)inv); 2786 } else { 2787 return implMontgomerySquare(a, n, len, inv, materialize(product, len)); 2788 } 2789 } 2790 2791 // Range-check everything. implMontgomeryMultiplyChecks(int[] a, int[] b, int[] n, int len, int[] product)2792 private static void implMontgomeryMultiplyChecks 2793 (int[] a, int[] b, int[] n, int len, int[] product) throws RuntimeException { 2794 if (len % 2 != 0) { 2795 throw new IllegalArgumentException("input array length must be even: " + len); 2796 } 2797 2798 if (len < 1) { 2799 throw new IllegalArgumentException("invalid input length: " + len); 2800 } 2801 2802 if (len > a.length || 2803 len > b.length || 2804 len > n.length || 2805 (product != null && len > product.length)) { 2806 throw new IllegalArgumentException("input array length out of bound: " + len); 2807 } 2808 } 2809 2810 // Make sure that the int array z (which is expected to contain 2811 // the result of a Montgomery multiplication) is present and 2812 // sufficiently large. materialize(int[] z, int len)2813 private static int[] materialize(int[] z, int len) { 2814 if (z == null || z.length < len) 2815 z = new int[len]; 2816 return z; 2817 } 2818 2819 // These methods are intended to be be replaced by virtual machine 2820 // intrinsics. implMontgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv, int[] product)2821 private static int[] implMontgomeryMultiply(int[] a, int[] b, int[] n, int len, 2822 long inv, int[] product) { 2823 product = multiplyToLen(a, len, b, len, product); 2824 return montReduce(product, n, len, (int)inv); 2825 } implMontgomerySquare(int[] a, int[] n, int len, long inv, int[] product)2826 private static int[] implMontgomerySquare(int[] a, int[] n, int len, 2827 long inv, int[] product) { 2828 product = squareToLen(a, len, product); 2829 return montReduce(product, n, len, (int)inv); 2830 } 2831 2832 static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793, 2833 Integer.MAX_VALUE}; // Sentinel 2834 2835 /** 2836 * Returns a BigInteger whose value is x to the power of y mod z. 2837 * Assumes: z is odd && x < z. 2838 */ oddModPow(@onNull BigInteger y, @NonNull BigInteger z)2839 @NonNull private BigInteger oddModPow(@NonNull BigInteger y, @NonNull BigInteger z) { 2840 /* 2841 * The algorithm is adapted from Colin Plumb's C library. 2842 * 2843 * The window algorithm: 2844 * The idea is to keep a running product of b1 = n^(high-order bits of exp) 2845 * and then keep appending exponent bits to it. The following patterns 2846 * apply to a 3-bit window (k = 3): 2847 * To append 0: square 2848 * To append 1: square, multiply by n^1 2849 * To append 10: square, multiply by n^1, square 2850 * To append 11: square, square, multiply by n^3 2851 * To append 100: square, multiply by n^1, square, square 2852 * To append 101: square, square, square, multiply by n^5 2853 * To append 110: square, square, multiply by n^3, square 2854 * To append 111: square, square, square, multiply by n^7 2855 * 2856 * Since each pattern involves only one multiply, the longer the pattern 2857 * the better, except that a 0 (no multiplies) can be appended directly. 2858 * We precompute a table of odd powers of n, up to 2^k, and can then 2859 * multiply k bits of exponent at a time. Actually, assuming random 2860 * exponents, there is on average one zero bit between needs to 2861 * multiply (1/2 of the time there's none, 1/4 of the time there's 1, 2862 * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so 2863 * you have to do one multiply per k+1 bits of exponent. 2864 * 2865 * The loop walks down the exponent, squaring the result buffer as 2866 * it goes. There is a wbits+1 bit lookahead buffer, buf, that is 2867 * filled with the upcoming exponent bits. (What is read after the 2868 * end of the exponent is unimportant, but it is filled with zero here.) 2869 * When the most-significant bit of this buffer becomes set, i.e. 2870 * (buf & tblmask) != 0, we have to decide what pattern to multiply 2871 * by, and when to do it. We decide, remember to do it in future 2872 * after a suitable number of squarings have passed (e.g. a pattern 2873 * of "100" in the buffer requires that we multiply by n^1 immediately; 2874 * a pattern of "110" calls for multiplying by n^3 after one more 2875 * squaring), clear the buffer, and continue. 2876 * 2877 * When we start, there is one more optimization: the result buffer 2878 * is implcitly one, so squaring it or multiplying by it can be 2879 * optimized away. Further, if we start with a pattern like "100" 2880 * in the lookahead window, rather than placing n into the buffer 2881 * and then starting to square it, we have already computed n^2 2882 * to compute the odd-powers table, so we can place that into 2883 * the buffer and save a squaring. 2884 * 2885 * This means that if you have a k-bit window, to compute n^z, 2886 * where z is the high k bits of the exponent, 1/2 of the time 2887 * it requires no squarings. 1/4 of the time, it requires 1 2888 * squaring, ... 1/2^(k-1) of the time, it requires k-2 squarings. 2889 * And the remaining 1/2^(k-1) of the time, the top k bits are a 2890 * 1 followed by k-1 0 bits, so it again only requires k-2 2891 * squarings, not k-1. The average of these is 1. Add that 2892 * to the one squaring we have to do to compute the table, 2893 * and you'll see that a k-bit window saves k-2 squarings 2894 * as well as reducing the multiplies. (It actually doesn't 2895 * hurt in the case k = 1, either.) 2896 */ 2897 // Special case for exponent of one 2898 if (y.equals(ONE)) 2899 return this; 2900 2901 // Special case for base of zero 2902 if (signum == 0) 2903 return ZERO; 2904 2905 int[] base = mag.clone(); 2906 int[] exp = y.mag; 2907 int[] mod = z.mag; 2908 int modLen = mod.length; 2909 2910 // Make modLen even. It is conventional to use a cryptographic 2911 // modulus that is 512, 768, 1024, or 2048 bits, so this code 2912 // will not normally be executed. However, it is necessary for 2913 // the correct functioning of the HotSpot intrinsics. 2914 if ((modLen & 1) != 0) { 2915 int[] x = new int[modLen + 1]; 2916 System.arraycopy(mod, 0, x, 1, modLen); 2917 mod = x; 2918 modLen++; 2919 } 2920 2921 // Select an appropriate window size 2922 int wbits = 0; 2923 int ebits = bitLength(exp, exp.length); 2924 // if exponent is 65537 (0x10001), use minimum window size 2925 if ((ebits != 17) || (exp[0] != 65537)) { 2926 while (ebits > bnExpModThreshTable[wbits]) { 2927 wbits++; 2928 } 2929 } 2930 2931 // Calculate appropriate table size 2932 int tblmask = 1 << wbits; 2933 2934 // Allocate table for precomputed odd powers of base in Montgomery form 2935 int[][] table = new int[tblmask][]; 2936 for (int i=0; i < tblmask; i++) 2937 table[i] = new int[modLen]; 2938 2939 // Compute the modular inverse of the least significant 64-bit 2940 // digit of the modulus 2941 long n0 = (mod[modLen-1] & LONG_MASK) + ((mod[modLen-2] & LONG_MASK) << 32); 2942 long inv = -MutableBigInteger.inverseMod64(n0); 2943 2944 // Convert base to Montgomery form 2945 int[] a = leftShift(base, base.length, modLen << 5); 2946 2947 MutableBigInteger q = new MutableBigInteger(), 2948 a2 = new MutableBigInteger(a), 2949 b2 = new MutableBigInteger(mod); 2950 b2.normalize(); // MutableBigInteger.divide() assumes that its 2951 // divisor is in normal form. 2952 2953 MutableBigInteger r= a2.divide(b2, q); 2954 table[0] = r.toIntArray(); 2955 2956 // Pad table[0] with leading zeros so its length is at least modLen 2957 if (table[0].length < modLen) { 2958 int offset = modLen - table[0].length; 2959 int[] t2 = new int[modLen]; 2960 System.arraycopy(table[0], 0, t2, offset, table[0].length); 2961 table[0] = t2; 2962 } 2963 2964 // Set b to the square of the base 2965 int[] b = montgomerySquare(table[0], mod, modLen, inv, null); 2966 2967 // Set t to high half of b 2968 int[] t = Arrays.copyOf(b, modLen); 2969 2970 // Fill in the table with odd powers of the base 2971 for (int i=1; i < tblmask; i++) { 2972 table[i] = montgomeryMultiply(t, table[i-1], mod, modLen, inv, null); 2973 } 2974 2975 // Pre load the window that slides over the exponent 2976 int bitpos = 1 << ((ebits-1) & (32-1)); 2977 2978 int buf = 0; 2979 int elen = exp.length; 2980 int eIndex = 0; 2981 for (int i = 0; i <= wbits; i++) { 2982 buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0); 2983 bitpos >>>= 1; 2984 if (bitpos == 0) { 2985 eIndex++; 2986 bitpos = 1 << (32-1); 2987 elen--; 2988 } 2989 } 2990 2991 int multpos = ebits; 2992 2993 // The first iteration, which is hoisted out of the main loop 2994 ebits--; 2995 boolean isone = true; 2996 2997 multpos = ebits - wbits; 2998 while ((buf & 1) == 0) { 2999 buf >>>= 1; 3000 multpos++; 3001 } 3002 3003 int[] mult = table[buf >>> 1]; 3004 3005 buf = 0; 3006 if (multpos == ebits) 3007 isone = false; 3008 3009 // The main loop 3010 while (true) { 3011 ebits--; 3012 // Advance the window 3013 buf <<= 1; 3014 3015 if (elen != 0) { 3016 buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0; 3017 bitpos >>>= 1; 3018 if (bitpos == 0) { 3019 eIndex++; 3020 bitpos = 1 << (32-1); 3021 elen--; 3022 } 3023 } 3024 3025 // Examine the window for pending multiplies 3026 if ((buf & tblmask) != 0) { 3027 multpos = ebits - wbits; 3028 while ((buf & 1) == 0) { 3029 buf >>>= 1; 3030 multpos++; 3031 } 3032 mult = table[buf >>> 1]; 3033 buf = 0; 3034 } 3035 3036 // Perform multiply 3037 if (ebits == multpos) { 3038 if (isone) { 3039 b = mult.clone(); 3040 isone = false; 3041 } else { 3042 t = b; 3043 a = montgomeryMultiply(t, mult, mod, modLen, inv, a); 3044 t = a; a = b; b = t; 3045 } 3046 } 3047 3048 // Check if done 3049 if (ebits == 0) 3050 break; 3051 3052 // Square the input 3053 if (!isone) { 3054 t = b; 3055 a = montgomerySquare(t, mod, modLen, inv, a); 3056 t = a; a = b; b = t; 3057 } 3058 } 3059 3060 // Convert result out of Montgomery form and return 3061 int[] t2 = new int[2*modLen]; 3062 System.arraycopy(b, 0, t2, modLen, modLen); 3063 3064 b = montReduce(t2, mod, modLen, (int)inv); 3065 3066 t2 = Arrays.copyOf(b, modLen); 3067 3068 return new BigInteger(1, t2); 3069 } 3070 3071 /** 3072 * Montgomery reduce n, modulo mod. This reduces modulo mod and divides 3073 * by 2^(32*mlen). Adapted from Colin Plumb's C library. 3074 */ montReduce(int[] n, int[] mod, int mlen, int inv)3075 private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) { 3076 int c=0; 3077 int len = mlen; 3078 int offset=0; 3079 3080 do { 3081 int nEnd = n[n.length-1-offset]; 3082 int carry = mulAdd(n, mod, offset, mlen, inv * nEnd); 3083 c += addOne(n, offset, mlen, carry); 3084 offset++; 3085 } while (--len > 0); 3086 3087 while (c > 0) 3088 c += subN(n, mod, mlen); 3089 3090 while (intArrayCmpToLen(n, mod, mlen) >= 0) 3091 subN(n, mod, mlen); 3092 3093 return n; 3094 } 3095 3096 3097 /* 3098 * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than, 3099 * equal to, or greater than arg2 up to length len. 3100 */ intArrayCmpToLen(int[] arg1, int[] arg2, int len)3101 private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) { 3102 for (int i=0; i < len; i++) { 3103 long b1 = arg1[i] & LONG_MASK; 3104 long b2 = arg2[i] & LONG_MASK; 3105 if (b1 < b2) 3106 return -1; 3107 if (b1 > b2) 3108 return 1; 3109 } 3110 return 0; 3111 } 3112 3113 /** 3114 * Subtracts two numbers of same length, returning borrow. 3115 */ subN(int[] a, int[] b, int len)3116 private static int subN(int[] a, int[] b, int len) { 3117 long sum = 0; 3118 3119 while (--len >= 0) { 3120 sum = (a[len] & LONG_MASK) - 3121 (b[len] & LONG_MASK) + (sum >> 32); 3122 a[len] = (int)sum; 3123 } 3124 3125 return (int)(sum >> 32); 3126 } 3127 3128 /** 3129 * Multiply an array by one word k and add to result, return the carry 3130 */ mulAdd(int[] out, int[] in, int offset, int len, int k)3131 static int mulAdd(int[] out, int[] in, int offset, int len, int k) { 3132 implMulAddCheck(out, in, offset, len, k); 3133 return implMulAdd(out, in, offset, len, k); 3134 } 3135 3136 /** 3137 * Parameters validation. 3138 */ implMulAddCheck(int[] out, int[] in, int offset, int len, int k)3139 private static void implMulAddCheck(int[] out, int[] in, int offset, int len, int k) { 3140 if (len > in.length) { 3141 throw new IllegalArgumentException("input length is out of bound: " + len + " > " + in.length); 3142 } 3143 if (offset < 0) { 3144 throw new IllegalArgumentException("input offset is invalid: " + offset); 3145 } 3146 if (offset > (out.length - 1)) { 3147 throw new IllegalArgumentException("input offset is out of bound: " + offset + " > " + (out.length - 1)); 3148 } 3149 if (len > (out.length - offset)) { 3150 throw new IllegalArgumentException("input len is out of bound: " + len + " > " + (out.length - offset)); 3151 } 3152 } 3153 3154 /** 3155 * Java Runtime may use intrinsic for this method. 3156 */ implMulAdd(int[] out, int[] in, int offset, int len, int k)3157 private static int implMulAdd(int[] out, int[] in, int offset, int len, int k) { 3158 long kLong = k & LONG_MASK; 3159 long carry = 0; 3160 3161 offset = out.length-offset - 1; 3162 for (int j=len-1; j >= 0; j--) { 3163 long product = (in[j] & LONG_MASK) * kLong + 3164 (out[offset] & LONG_MASK) + carry; 3165 out[offset--] = (int)product; 3166 carry = product >>> 32; 3167 } 3168 return (int)carry; 3169 } 3170 3171 /** 3172 * Add one word to the number a mlen words into a. Return the resulting 3173 * carry. 3174 */ addOne(int[] a, int offset, int mlen, int carry)3175 static int addOne(int[] a, int offset, int mlen, int carry) { 3176 offset = a.length-1-mlen-offset; 3177 long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK); 3178 3179 a[offset] = (int)t; 3180 if ((t >>> 32) == 0) 3181 return 0; 3182 while (--mlen >= 0) { 3183 if (--offset < 0) { // Carry out of number 3184 return 1; 3185 } else { 3186 a[offset]++; 3187 if (a[offset] != 0) 3188 return 0; 3189 } 3190 } 3191 return 1; 3192 } 3193 3194 /** 3195 * Returns a BigInteger whose value is (this ** exponent) mod (2**p) 3196 */ modPow2(@onNull BigInteger exponent, int p)3197 @NonNull private BigInteger modPow2(@NonNull BigInteger exponent, int p) { 3198 /* 3199 * Perform exponentiation using repeated squaring trick, chopping off 3200 * high order bits as indicated by modulus. 3201 */ 3202 BigInteger result = ONE; 3203 BigInteger baseToPow2 = this.mod2(p); 3204 int expOffset = 0; 3205 3206 int limit = exponent.bitLength(); 3207 3208 if (this.testBit(0)) 3209 limit = (p-1) < limit ? (p-1) : limit; 3210 3211 while (expOffset < limit) { 3212 if (exponent.testBit(expOffset)) 3213 result = result.multiply(baseToPow2).mod2(p); 3214 expOffset++; 3215 if (expOffset < limit) 3216 baseToPow2 = baseToPow2.square().mod2(p); 3217 } 3218 3219 return result; 3220 } 3221 3222 /** 3223 * Returns a BigInteger whose value is this mod(2**p). 3224 * Assumes that this {@code BigInteger >= 0} and {@code p > 0}. 3225 */ 3226 @NonNull private BigInteger mod2(int p) { 3227 if (bitLength() <= p) 3228 return this; 3229 3230 // Copy remaining ints of mag 3231 int numInts = (p + 31) >>> 5; 3232 int[] mag = new int[numInts]; 3233 System.arraycopy(this.mag, (this.mag.length - numInts), mag, 0, numInts); 3234 3235 // Mask out any excess bits 3236 int excessBits = (numInts << 5) - p; 3237 mag[0] &= (1L << (32-excessBits)) - 1; 3238 3239 return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1)); 3240 } 3241 3242 /** 3243 * Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}. 3244 * 3245 * @param m the modulus. 3246 * @return {@code this}<sup>-1</sup> {@code mod m}. 3247 * @throws ArithmeticException {@code m} ≤ 0, or this BigInteger 3248 * has no multiplicative inverse mod m (that is, this BigInteger 3249 * is not <i>relatively prime</i> to m). 3250 */ 3251 @NonNull public BigInteger modInverse(@NonNull BigInteger m) { 3252 if (m.signum != 1) 3253 throw new ArithmeticException("BigInteger: modulus not positive"); 3254 3255 if (m.equals(ONE)) 3256 return ZERO; 3257 3258 // Calculate (this mod m) 3259 BigInteger modVal = this; 3260 if (signum < 0 || (this.compareMagnitude(m) >= 0)) 3261 modVal = this.mod(m); 3262 3263 if (modVal.equals(ONE)) 3264 return ONE; 3265 3266 MutableBigInteger a = new MutableBigInteger(modVal); 3267 MutableBigInteger b = new MutableBigInteger(m); 3268 3269 MutableBigInteger result = a.mutableModInverse(b); 3270 return result.toBigInteger(1); 3271 } 3272 3273 // Shift Operations 3274 3275 /** 3276 * Returns a BigInteger whose value is {@code (this << n)}. 3277 * The shift distance, {@code n}, may be negative, in which case 3278 * this method performs a right shift. 3279 * (Computes <tt>floor(this * 2<sup>n</sup>)</tt>.) 3280 * 3281 * @param n shift distance, in bits. 3282 * @return {@code this << n} 3283 * @see #shiftRight 3284 */ 3285 @NonNull public BigInteger shiftLeft(int n) { 3286 if (signum == 0) 3287 return ZERO; 3288 if (n > 0) { 3289 return new BigInteger(shiftLeft(mag, n), signum); 3290 } else if (n == 0) { 3291 return this; 3292 } else { 3293 // Possible int overflow in (-n) is not a trouble, 3294 // because shiftRightImpl considers its argument unsigned 3295 return shiftRightImpl(-n); 3296 } 3297 } 3298 3299 /** 3300 * Returns a magnitude array whose value is {@code (mag << n)}. 3301 * The shift distance, {@code n}, is considered unnsigned. 3302 * (Computes <tt>this * 2<sup>n</sup></tt>.) 3303 * 3304 * @param mag magnitude, the most-significant int ({@code mag[0]}) must be non-zero. 3305 * @param n unsigned shift distance, in bits. 3306 * @return {@code mag << n} 3307 */ 3308 private static int[] shiftLeft(int[] mag, int n) { 3309 int nInts = n >>> 5; 3310 int nBits = n & 0x1f; 3311 int magLen = mag.length; 3312 int newMag[] = null; 3313 3314 if (nBits == 0) { 3315 newMag = new int[magLen + nInts]; 3316 System.arraycopy(mag, 0, newMag, 0, magLen); 3317 } else { 3318 int i = 0; 3319 int nBits2 = 32 - nBits; 3320 int highBits = mag[0] >>> nBits2; 3321 if (highBits != 0) { 3322 newMag = new int[magLen + nInts + 1]; 3323 newMag[i++] = highBits; 3324 } else { 3325 newMag = new int[magLen + nInts]; 3326 } 3327 int j=0; 3328 while (j < magLen-1) 3329 newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2; 3330 newMag[i] = mag[j] << nBits; 3331 } 3332 return newMag; 3333 } 3334 3335 /** 3336 * Returns a BigInteger whose value is {@code (this >> n)}. Sign 3337 * extension is performed. The shift distance, {@code n}, may be 3338 * negative, in which case this method performs a left shift. 3339 * (Computes <tt>floor(this / 2<sup>n</sup>)</tt>.) 3340 * 3341 * @param n shift distance, in bits. 3342 * @return {@code this >> n} 3343 * @see #shiftLeft 3344 */ 3345 @NonNull public BigInteger shiftRight(int n) { 3346 if (signum == 0) 3347 return ZERO; 3348 if (n > 0) { 3349 return shiftRightImpl(n); 3350 } else if (n == 0) { 3351 return this; 3352 } else { 3353 // Possible int overflow in {@code -n} is not a trouble, 3354 // because shiftLeft considers its argument unsigned 3355 return new BigInteger(shiftLeft(mag, -n), signum); 3356 } 3357 } 3358 3359 /** 3360 * Returns a BigInteger whose value is {@code (this >> n)}. The shift 3361 * distance, {@code n}, is considered unsigned. 3362 * (Computes <tt>floor(this * 2<sup>-n</sup>)</tt>.) 3363 * 3364 * @param n unsigned shift distance, in bits. 3365 * @return {@code this >> n} 3366 */ 3367 @NonNull private BigInteger shiftRightImpl(int n) { 3368 int nInts = n >>> 5; 3369 int nBits = n & 0x1f; 3370 int magLen = mag.length; 3371 int newMag[] = null; 3372 3373 // Special case: entire contents shifted off the end 3374 if (nInts >= magLen) 3375 return (signum >= 0 ? ZERO : negConst[1]); 3376 3377 if (nBits == 0) { 3378 int newMagLen = magLen - nInts; 3379 newMag = Arrays.copyOf(mag, newMagLen); 3380 } else { 3381 int i = 0; 3382 int highBits = mag[0] >>> nBits; 3383 if (highBits != 0) { 3384 newMag = new int[magLen - nInts]; 3385 newMag[i++] = highBits; 3386 } else { 3387 newMag = new int[magLen - nInts -1]; 3388 } 3389 3390 int nBits2 = 32 - nBits; 3391 int j=0; 3392 while (j < magLen - nInts - 1) 3393 newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits); 3394 } 3395 3396 if (signum < 0) { 3397 // Find out whether any one-bits were shifted off the end. 3398 boolean onesLost = false; 3399 for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--) 3400 onesLost = (mag[i] != 0); 3401 if (!onesLost && nBits != 0) 3402 onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0); 3403 3404 if (onesLost) 3405 newMag = javaIncrement(newMag); 3406 } 3407 3408 return new BigInteger(newMag, signum); 3409 } 3410 3411 int[] javaIncrement(int[] val) { 3412 int lastSum = 0; 3413 for (int i=val.length-1; i >= 0 && lastSum == 0; i--) 3414 lastSum = (val[i] += 1); 3415 if (lastSum == 0) { 3416 val = new int[val.length+1]; 3417 val[0] = 1; 3418 } 3419 return val; 3420 } 3421 3422 // Bitwise Operations 3423 3424 /** 3425 * Returns a BigInteger whose value is {@code (this & val)}. (This 3426 * method returns a negative BigInteger if and only if this and val are 3427 * both negative.) 3428 * 3429 * @param val value to be AND'ed with this BigInteger. 3430 * @return {@code this & val} 3431 */ 3432 @NonNull public BigInteger and(@NonNull BigInteger val) { 3433 int[] result = new int[Math.max(intLength(), val.intLength())]; 3434 for (int i=0; i < result.length; i++) 3435 result[i] = (getInt(result.length-i-1) 3436 & val.getInt(result.length-i-1)); 3437 3438 return valueOf(result); 3439 } 3440 3441 /** 3442 * Returns a BigInteger whose value is {@code (this | val)}. (This method 3443 * returns a negative BigInteger if and only if either this or val is 3444 * negative.) 3445 * 3446 * @param val value to be OR'ed with this BigInteger. 3447 * @return {@code this | val} 3448 */ 3449 @NonNull public BigInteger or(@NonNull BigInteger val) { 3450 int[] result = new int[Math.max(intLength(), val.intLength())]; 3451 for (int i=0; i < result.length; i++) 3452 result[i] = (getInt(result.length-i-1) 3453 | val.getInt(result.length-i-1)); 3454 3455 return valueOf(result); 3456 } 3457 3458 /** 3459 * Returns a BigInteger whose value is {@code (this ^ val)}. (This method 3460 * returns a negative BigInteger if and only if exactly one of this and 3461 * val are negative.) 3462 * 3463 * @param val value to be XOR'ed with this BigInteger. 3464 * @return {@code this ^ val} 3465 */ 3466 @NonNull public BigInteger xor(@NonNull BigInteger val) { 3467 int[] result = new int[Math.max(intLength(), val.intLength())]; 3468 for (int i=0; i < result.length; i++) 3469 result[i] = (getInt(result.length-i-1) 3470 ^ val.getInt(result.length-i-1)); 3471 3472 return valueOf(result); 3473 } 3474 3475 /** 3476 * Returns a BigInteger whose value is {@code (~this)}. (This method 3477 * returns a negative value if and only if this BigInteger is 3478 * non-negative.) 3479 * 3480 * @return {@code ~this} 3481 */ 3482 @NonNull public BigInteger not() { 3483 int[] result = new int[intLength()]; 3484 for (int i=0; i < result.length; i++) 3485 result[i] = ~getInt(result.length-i-1); 3486 3487 return valueOf(result); 3488 } 3489 3490 /** 3491 * Returns a BigInteger whose value is {@code (this & ~val)}. This 3492 * method, which is equivalent to {@code and(val.not())}, is provided as 3493 * a convenience for masking operations. (This method returns a negative 3494 * BigInteger if and only if {@code this} is negative and {@code val} is 3495 * positive.) 3496 * 3497 * @param val value to be complemented and AND'ed with this BigInteger. 3498 * @return {@code this & ~val} 3499 */ 3500 @NonNull public BigInteger andNot(@NonNull BigInteger val) { 3501 int[] result = new int[Math.max(intLength(), val.intLength())]; 3502 for (int i=0; i < result.length; i++) 3503 result[i] = (getInt(result.length-i-1) 3504 & ~val.getInt(result.length-i-1)); 3505 3506 return valueOf(result); 3507 } 3508 3509 3510 // Single Bit Operations 3511 3512 /** 3513 * Returns {@code true} if and only if the designated bit is set. 3514 * (Computes {@code ((this & (1<<n)) != 0)}.) 3515 * 3516 * @param n index of bit to test. 3517 * @return {@code true} if and only if the designated bit is set. 3518 * @throws ArithmeticException {@code n} is negative. 3519 */ 3520 public boolean testBit(int n) { 3521 if (n < 0) 3522 throw new ArithmeticException("Negative bit address"); 3523 3524 return (getInt(n >>> 5) & (1 << (n & 31))) != 0; 3525 } 3526 3527 /** 3528 * Returns a BigInteger whose value is equivalent to this BigInteger 3529 * with the designated bit set. (Computes {@code (this | (1<<n))}.) 3530 * 3531 * @param n index of bit to set. 3532 * @return {@code this | (1<<n)} 3533 * @throws ArithmeticException {@code n} is negative. 3534 */ 3535 @NonNull public BigInteger setBit(int n) { 3536 if (n < 0) 3537 throw new ArithmeticException("Negative bit address"); 3538 3539 int intNum = n >>> 5; 3540 int[] result = new int[Math.max(intLength(), intNum+2)]; 3541 3542 for (int i=0; i < result.length; i++) 3543 result[result.length-i-1] = getInt(i); 3544 3545 result[result.length-intNum-1] |= (1 << (n & 31)); 3546 3547 return valueOf(result); 3548 } 3549 3550 /** 3551 * Returns a BigInteger whose value is equivalent to this BigInteger 3552 * with the designated bit cleared. 3553 * (Computes {@code (this & ~(1<<n))}.) 3554 * 3555 * @param n index of bit to clear. 3556 * @return {@code this & ~(1<<n)} 3557 * @throws ArithmeticException {@code n} is negative. 3558 */ 3559 @NonNull public BigInteger clearBit(int n) { 3560 if (n < 0) 3561 throw new ArithmeticException("Negative bit address"); 3562 3563 int intNum = n >>> 5; 3564 int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)]; 3565 3566 for (int i=0; i < result.length; i++) 3567 result[result.length-i-1] = getInt(i); 3568 3569 result[result.length-intNum-1] &= ~(1 << (n & 31)); 3570 3571 return valueOf(result); 3572 } 3573 3574 /** 3575 * Returns a BigInteger whose value is equivalent to this BigInteger 3576 * with the designated bit flipped. 3577 * (Computes {@code (this ^ (1<<n))}.) 3578 * 3579 * @param n index of bit to flip. 3580 * @return {@code this ^ (1<<n)} 3581 * @throws ArithmeticException {@code n} is negative. 3582 */ 3583 @NonNull public BigInteger flipBit(int n) { 3584 if (n < 0) 3585 throw new ArithmeticException("Negative bit address"); 3586 3587 int intNum = n >>> 5; 3588 int[] result = new int[Math.max(intLength(), intNum+2)]; 3589 3590 for (int i=0; i < result.length; i++) 3591 result[result.length-i-1] = getInt(i); 3592 3593 result[result.length-intNum-1] ^= (1 << (n & 31)); 3594 3595 return valueOf(result); 3596 } 3597 3598 /** 3599 * Returns the index of the rightmost (lowest-order) one bit in this 3600 * BigInteger (the number of zero bits to the right of the rightmost 3601 * one bit). Returns -1 if this BigInteger contains no one bits. 3602 * (Computes {@code (this == 0? -1 : log2(this & -this))}.) 3603 * 3604 * @return index of the rightmost one bit in this BigInteger. 3605 */ 3606 public int getLowestSetBit() { 3607 @SuppressWarnings("deprecation") int lsb = lowestSetBit - 2; 3608 if (lsb == -2) { // lowestSetBit not initialized yet 3609 lsb = 0; 3610 if (signum == 0) { 3611 lsb -= 1; 3612 } else { 3613 // Search for lowest order nonzero int 3614 int i,b; 3615 for (i=0; (b = getInt(i)) == 0; i++) 3616 ; 3617 lsb += (i << 5) + Integer.numberOfTrailingZeros(b); 3618 } 3619 lowestSetBit = lsb + 2; 3620 } 3621 return lsb; 3622 } 3623 3624 3625 // Miscellaneous Bit Operations 3626 3627 /** 3628 * Returns the number of bits in the minimal two's-complement 3629 * representation of this BigInteger, <i>excluding</i> a sign bit. 3630 * For positive BigIntegers, this is equivalent to the number of bits in 3631 * the ordinary binary representation. (Computes 3632 * {@code (ceil(log2(this < 0 ? -this : this+1)))}.) 3633 * 3634 * @return number of bits in the minimal two's-complement 3635 * representation of this BigInteger, <i>excluding</i> a sign bit. 3636 */ 3637 public int bitLength() { 3638 @SuppressWarnings("deprecation") int n = bitLength - 1; 3639 if (n == -1) { // bitLength not initialized yet 3640 int[] m = mag; 3641 int len = m.length; 3642 if (len == 0) { 3643 n = 0; // offset by one to initialize 3644 } else { 3645 // Calculate the bit length of the magnitude 3646 int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]); 3647 if (signum < 0) { 3648 // Check if magnitude is a power of two 3649 boolean pow2 = (Integer.bitCount(mag[0]) == 1); 3650 for (int i=1; i< len && pow2; i++) 3651 pow2 = (mag[i] == 0); 3652 3653 n = (pow2 ? magBitLength - 1 : magBitLength); 3654 } else { 3655 n = magBitLength; 3656 } 3657 } 3658 bitLength = n + 1; 3659 } 3660 return n; 3661 } 3662 3663 /** 3664 * Returns the number of bits in the two's complement representation 3665 * of this BigInteger that differ from its sign bit. This method is 3666 * useful when implementing bit-vector style sets atop BigIntegers. 3667 * 3668 * @return number of bits in the two's complement representation 3669 * of this BigInteger that differ from its sign bit. 3670 */ 3671 public int bitCount() { 3672 @SuppressWarnings("deprecation") int bc = bitCount - 1; 3673 if (bc == -1) { // bitCount not initialized yet 3674 bc = 0; // offset by one to initialize 3675 // Count the bits in the magnitude 3676 for (int i=0; i < mag.length; i++) 3677 bc += Integer.bitCount(mag[i]); 3678 if (signum < 0) { 3679 // Count the trailing zeros in the magnitude 3680 int magTrailingZeroCount = 0, j; 3681 for (j=mag.length-1; mag[j] == 0; j--) 3682 magTrailingZeroCount += 32; 3683 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]); 3684 bc += magTrailingZeroCount - 1; 3685 } 3686 bitCount = bc + 1; 3687 } 3688 return bc; 3689 } 3690 3691 // Primality Testing 3692 3693 /** 3694 * Returns {@code true} if this BigInteger is probably prime, 3695 * {@code false} if it's definitely composite. If 3696 * {@code certainty} is ≤ 0, {@code true} is 3697 * returned. 3698 * 3699 * @param certainty a measure of the uncertainty that the caller is 3700 * willing to tolerate: if the call returns {@code true} 3701 * the probability that this BigInteger is prime exceeds 3702 * (1 - 1/2<sup>{@code certainty}</sup>). The execution time of 3703 * this method is proportional to the value of this parameter. 3704 * @return {@code true} if this BigInteger is probably prime, 3705 * {@code false} if it's definitely composite. 3706 */ 3707 public boolean isProbablePrime(int certainty) { 3708 if (certainty <= 0) 3709 return true; 3710 BigInteger w = this.abs(); 3711 if (w.equals(TWO)) 3712 return true; 3713 if (!w.testBit(0) || w.equals(ONE)) 3714 return false; 3715 3716 return w.primeToCertainty(certainty, null); 3717 } 3718 3719 // Comparison Operations 3720 3721 /** 3722 * Compares this BigInteger with the specified BigInteger. This 3723 * method is provided in preference to individual methods for each 3724 * of the six boolean comparison operators ({@literal <}, ==, 3725 * {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested 3726 * idiom for performing these comparisons is: {@code 3727 * (x.compareTo(y)} <<i>op</i>> {@code 0)}, where 3728 * <<i>op</i>> is one of the six comparison operators. 3729 * 3730 * @param val BigInteger to which this BigInteger is to be compared. 3731 * @return -1, 0 or 1 as this BigInteger is numerically less than, equal 3732 * to, or greater than {@code val}. 3733 */ 3734 public int compareTo(@NonNull BigInteger val) { 3735 if (signum == val.signum) { 3736 switch (signum) { 3737 case 1: 3738 return compareMagnitude(val); 3739 case -1: 3740 return val.compareMagnitude(this); 3741 default: 3742 return 0; 3743 } 3744 } 3745 return signum > val.signum ? 1 : -1; 3746 } 3747 3748 /** 3749 * Compares the magnitude array of this BigInteger with the specified 3750 * BigInteger's. This is the version of compareTo ignoring sign. 3751 * 3752 * @param val BigInteger whose magnitude array to be compared. 3753 * @return -1, 0 or 1 as this magnitude array is less than, equal to or 3754 * greater than the magnitude aray for the specified BigInteger's. 3755 */ 3756 final int compareMagnitude(@NonNull BigInteger val) { 3757 int[] m1 = mag; 3758 int len1 = m1.length; 3759 int[] m2 = val.mag; 3760 int len2 = m2.length; 3761 if (len1 < len2) 3762 return -1; 3763 if (len1 > len2) 3764 return 1; 3765 for (int i = 0; i < len1; i++) { 3766 int a = m1[i]; 3767 int b = m2[i]; 3768 if (a != b) 3769 return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1; 3770 } 3771 return 0; 3772 } 3773 3774 /** 3775 * Version of compareMagnitude that compares magnitude with long value. 3776 * val can't be Long.MIN_VALUE. 3777 */ 3778 final int compareMagnitude(long val) { 3779 assert val != Long.MIN_VALUE; 3780 int[] m1 = mag; 3781 int len = m1.length; 3782 if (len > 2) { 3783 return 1; 3784 } 3785 if (val < 0) { 3786 val = -val; 3787 } 3788 int highWord = (int)(val >>> 32); 3789 if (highWord == 0) { 3790 if (len < 1) 3791 return -1; 3792 if (len > 1) 3793 return 1; 3794 int a = m1[0]; 3795 int b = (int)val; 3796 if (a != b) { 3797 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1; 3798 } 3799 return 0; 3800 } else { 3801 if (len < 2) 3802 return -1; 3803 int a = m1[0]; 3804 int b = highWord; 3805 if (a != b) { 3806 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1; 3807 } 3808 a = m1[1]; 3809 b = (int)val; 3810 if (a != b) { 3811 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1; 3812 } 3813 return 0; 3814 } 3815 } 3816 3817 /** 3818 * Compares this BigInteger with the specified Object for equality. 3819 * 3820 * @param x Object to which this BigInteger is to be compared. 3821 * @return {@code true} if and only if the specified Object is a 3822 * BigInteger whose value is numerically equal to this BigInteger. 3823 */ 3824 public boolean equals(@NonNull Object x) { 3825 // This test is just an optimization, which may or may not help 3826 if (x == this) 3827 return true; 3828 3829 if (!(x instanceof BigInteger)) 3830 return false; 3831 3832 BigInteger xInt = (BigInteger) x; 3833 if (xInt.signum != signum) 3834 return false; 3835 3836 int[] m = mag; 3837 int len = m.length; 3838 int[] xm = xInt.mag; 3839 if (len != xm.length) 3840 return false; 3841 3842 for (int i = 0; i < len; i++) 3843 if (xm[i] != m[i]) 3844 return false; 3845 3846 return true; 3847 } 3848 3849 /** 3850 * Returns the minimum of this BigInteger and {@code val}. 3851 * 3852 * @param val value with which the minimum is to be computed. 3853 * @return the BigInteger whose value is the lesser of this BigInteger and 3854 * {@code val}. If they are equal, either may be returned. 3855 */ 3856 @NonNull public BigInteger min(@NonNull BigInteger val) { 3857 return (compareTo(val) < 0 ? this : val); 3858 } 3859 3860 /** 3861 * Returns the maximum of this BigInteger and {@code val}. 3862 * 3863 * @param val value with which the maximum is to be computed. 3864 * @return the BigInteger whose value is the greater of this and 3865 * {@code val}. If they are equal, either may be returned. 3866 */ 3867 @NonNull public BigInteger max(@NonNull BigInteger val) { 3868 return (compareTo(val) > 0 ? this : val); 3869 } 3870 3871 3872 // Hash Function 3873 3874 /** 3875 * Returns the hash code for this BigInteger. 3876 * 3877 * @return hash code for this BigInteger. 3878 */ 3879 public int hashCode() { 3880 int hashCode = 0; 3881 3882 for (int i=0; i < mag.length; i++) 3883 hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK)); 3884 3885 return hashCode * signum; 3886 } 3887 3888 /** 3889 * Returns the String representation of this BigInteger in the 3890 * given radix. If the radix is outside the range from {@link 3891 * Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive, 3892 * it will default to 10 (as is the case for 3893 * {@code Integer.toString}). The digit-to-character mapping 3894 * provided by {@code Character.forDigit} is used, and a minus 3895 * sign is prepended if appropriate. (This representation is 3896 * compatible with the {@link #BigInteger(String, int) (String, 3897 * int)} constructor.) 3898 * 3899 * @param radix radix of the String representation. 3900 * @return String representation of this BigInteger in the given radix. 3901 * @see Integer#toString 3902 * @see Character#forDigit 3903 * @see #BigInteger(java.lang.String, int) 3904 */ 3905 @NonNull public String toString(int radix) { 3906 if (signum == 0) 3907 return "0"; 3908 if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) 3909 radix = 10; 3910 3911 // If it's small enough, use smallToString. 3912 if (mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) 3913 return smallToString(radix); 3914 3915 // Otherwise use recursive toString, which requires positive arguments. 3916 // The results will be concatenated into this StringBuilder 3917 StringBuilder sb = new StringBuilder(); 3918 if (signum < 0) { 3919 toString(this.negate(), sb, radix, 0); 3920 sb.insert(0, '-'); 3921 } 3922 else 3923 toString(this, sb, radix, 0); 3924 3925 return sb.toString(); 3926 } 3927 3928 /** This method is used to perform toString when arguments are small. */ 3929 @NonNull private String smallToString(int radix) { 3930 if (signum == 0) { 3931 return "0"; 3932 } 3933 3934 // Compute upper bound on number of digit groups and allocate space 3935 int maxNumDigitGroups = (4*mag.length + 6)/7; 3936 String digitGroup[] = new String[maxNumDigitGroups]; 3937 3938 // Translate number to string, a digit group at a time 3939 BigInteger tmp = this.abs(); 3940 int numGroups = 0; 3941 while (tmp.signum != 0) { 3942 BigInteger d = longRadix[radix]; 3943 3944 MutableBigInteger q = new MutableBigInteger(), 3945 a = new MutableBigInteger(tmp.mag), 3946 b = new MutableBigInteger(d.mag); 3947 MutableBigInteger r = a.divide(b, q); 3948 BigInteger q2 = q.toBigInteger(tmp.signum * d.signum); 3949 BigInteger r2 = r.toBigInteger(tmp.signum * d.signum); 3950 3951 digitGroup[numGroups++] = Long.toString(r2.longValue(), radix); 3952 tmp = q2; 3953 } 3954 3955 // Put sign (if any) and first digit group into result buffer 3956 StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1); 3957 if (signum < 0) { 3958 buf.append('-'); 3959 } 3960 buf.append(digitGroup[numGroups-1]); 3961 3962 // Append remaining digit groups padded with leading zeros 3963 for (int i=numGroups-2; i >= 0; i--) { 3964 // Prepend (any) leading zeros for this digit group 3965 int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length(); 3966 if (numLeadingZeros != 0) { 3967 buf.append(zeros[numLeadingZeros]); 3968 } 3969 buf.append(digitGroup[i]); 3970 } 3971 return buf.toString(); 3972 } 3973 3974 /** 3975 * Converts the specified BigInteger to a string and appends to 3976 * {@code sb}. This implements the recursive Schoenhage algorithm 3977 * for base conversions. 3978 * <p/> 3979 * See Knuth, Donald, _The Art of Computer Programming_, Vol. 2, 3980 * Answers to Exercises (4.4) Question 14. 3981 * 3982 * @param u The number to convert to a string. 3983 * @param sb The StringBuilder that will be appended to in place. 3984 * @param radix The base to convert to. 3985 * @param digits The minimum number of digits to pad to. 3986 */ 3987 private static void toString(@NonNull BigInteger u, StringBuilder sb, int radix, 3988 int digits) { 3989 /* If we're smaller than a certain threshold, use the smallToString 3990 method, padding with leading zeroes when necessary. */ 3991 if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) { 3992 String s = u.smallToString(radix); 3993 3994 // Pad with internal zeros if necessary. 3995 // Don't pad if we're at the beginning of the string. 3996 if ((s.length() < digits) && (sb.length() > 0)) { 3997 for (int i=s.length(); i < digits; i++) { // May be a faster way to 3998 sb.append('0'); // do this? 3999 } 4000 } 4001 4002 sb.append(s); 4003 return; 4004 } 4005 4006 int b, n; 4007 b = u.bitLength(); 4008 4009 // Calculate a value for n in the equation radix^(2^n) = u 4010 // and subtract 1 from that value. This is used to find the 4011 // cache index that contains the best value to divide u. 4012 n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0); 4013 BigInteger v = getRadixConversionCache(radix, n); 4014 BigInteger[] results; 4015 results = u.divideAndRemainder(v); 4016 4017 int expectedDigits = 1 << n; 4018 4019 // Now recursively build the two halves of each number. 4020 toString(results[0], sb, radix, digits-expectedDigits); 4021 toString(results[1], sb, radix, expectedDigits); 4022 } 4023 4024 /** 4025 * Returns the value radix^(2^exponent) from the cache. 4026 * If this value doesn't already exist in the cache, it is added. 4027 * <p/> 4028 * This could be changed to a more complicated caching method using 4029 * {@code Future}. 4030 */ 4031 @NonNull private static BigInteger getRadixConversionCache(int radix, int exponent) { 4032 BigInteger[] cacheLine = powerCache[radix]; // volatile read 4033 if (exponent < cacheLine.length) { 4034 return cacheLine[exponent]; 4035 } 4036 4037 int oldLength = cacheLine.length; 4038 cacheLine = Arrays.copyOf(cacheLine, exponent + 1); 4039 for (int i = oldLength; i <= exponent; i++) { 4040 cacheLine[i] = cacheLine[i - 1].pow(2); 4041 } 4042 4043 BigInteger[][] pc = powerCache; // volatile read again 4044 if (exponent >= pc[radix].length) { 4045 pc = pc.clone(); 4046 pc[radix] = cacheLine; 4047 powerCache = pc; // volatile write, publish 4048 } 4049 return cacheLine[exponent]; 4050 } 4051 4052 /* zero[i] is a string of i consecutive zeros. */ 4053 private static String zeros[] = new String[64]; 4054 static { 4055 zeros[63] = 4056 "000000000000000000000000000000000000000000000000000000000000000"; 4057 for (int i=0; i < 63; i++) 4058 zeros[i] = zeros[63].substring(0, i); 4059 } 4060 4061 /** 4062 * Returns the decimal String representation of this BigInteger. 4063 * The digit-to-character mapping provided by 4064 * {@code Character.forDigit} is used, and a minus sign is 4065 * prepended if appropriate. (This representation is compatible 4066 * with the {@link #BigInteger(String) (String)} constructor, and 4067 * allows for String concatenation with Java's + operator.) 4068 * 4069 * @return decimal String representation of this BigInteger. 4070 * @see Character#forDigit 4071 * @see #BigInteger(java.lang.String) 4072 */ 4073 @NonNull public String toString() { 4074 return toString(10); 4075 } 4076 4077 /** 4078 * Returns a byte array containing the two's-complement 4079 * representation of this BigInteger. The byte array will be in 4080 * <i>big-endian</i> byte-order: the most significant byte is in 4081 * the zeroth element. The array will contain the minimum number 4082 * of bytes required to represent this BigInteger, including at 4083 * least one sign bit, which is {@code (ceil((this.bitLength() + 4084 * 1)/8))}. (This representation is compatible with the 4085 * {@link #BigInteger(byte[]) (byte[])} constructor.) 4086 * 4087 * @return a byte array containing the two's-complement representation of 4088 * this BigInteger. 4089 * @see #BigInteger(byte[]) 4090 */ 4091 public byte[] toByteArray() { 4092 int byteLen = bitLength()/8 + 1; 4093 byte[] byteArray = new byte[byteLen]; 4094 4095 for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) { 4096 if (bytesCopied == 4) { 4097 nextInt = getInt(intIndex++); 4098 bytesCopied = 1; 4099 } else { 4100 nextInt >>>= 8; 4101 bytesCopied++; 4102 } 4103 byteArray[i] = (byte)nextInt; 4104 } 4105 return byteArray; 4106 } 4107 4108 /** 4109 * Converts this BigInteger to an {@code int}. This 4110 * conversion is analogous to a 4111 * <i>narrowing primitive conversion</i> from {@code long} to 4112 * {@code int} as defined in section 5.1.3 of 4113 * <cite>The Java™ Language Specification</cite>: 4114 * if this BigInteger is too big to fit in an 4115 * {@code int}, only the low-order 32 bits are returned. 4116 * Note that this conversion can lose information about the 4117 * overall magnitude of the BigInteger value as well as return a 4118 * result with the opposite sign. 4119 * 4120 * @return this BigInteger converted to an {@code int}. 4121 * @see #intValueExact() 4122 */ 4123 public int intValue() { 4124 int result = 0; 4125 result = getInt(0); 4126 return result; 4127 } 4128 4129 /** 4130 * Converts this BigInteger to a {@code long}. This 4131 * conversion is analogous to a 4132 * <i>narrowing primitive conversion</i> from {@code long} to 4133 * {@code int} as defined in section 5.1.3 of 4134 * <cite>The Java™ Language Specification</cite>: 4135 * if this BigInteger is too big to fit in a 4136 * {@code long}, only the low-order 64 bits are returned. 4137 * Note that this conversion can lose information about the 4138 * overall magnitude of the BigInteger value as well as return a 4139 * result with the opposite sign. 4140 * 4141 * @return this BigInteger converted to a {@code long}. 4142 * @see #longValueExact() 4143 */ 4144 public long longValue() { 4145 long result = 0; 4146 4147 for (int i=1; i >= 0; i--) 4148 result = (result << 32) + (getInt(i) & LONG_MASK); 4149 return result; 4150 } 4151 4152 /** 4153 * Converts this BigInteger to a {@code float}. This 4154 * conversion is similar to the 4155 * <i>narrowing primitive conversion</i> from {@code double} to 4156 * {@code float} as defined in section 5.1.3 of 4157 * <cite>The Java™ Language Specification</cite>: 4158 * if this BigInteger has too great a magnitude 4159 * to represent as a {@code float}, it will be converted to 4160 * {@link Float#NEGATIVE_INFINITY} or {@link 4161 * Float#POSITIVE_INFINITY} as appropriate. Note that even when 4162 * the return value is finite, this conversion can lose 4163 * information about the precision of the BigInteger value. 4164 * 4165 * @return this BigInteger converted to a {@code float}. 4166 */ 4167 public float floatValue() { 4168 if (signum == 0) { 4169 return 0.0f; 4170 } 4171 4172 int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1; 4173 4174 // exponent == floor(log2(abs(this))) 4175 if (exponent < Long.SIZE - 1) { 4176 return longValue(); 4177 } else if (exponent > Float.MAX_EXPONENT) { 4178 return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY; 4179 } 4180 4181 /* 4182 * We need the top SIGNIFICAND_WIDTH bits, including the "implicit" 4183 * one bit. To make rounding easier, we pick out the top 4184 * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or 4185 * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1 4186 * bits, and signifFloor the top SIGNIFICAND_WIDTH. 4187 * 4188 * It helps to consider the real number signif = abs(this) * 4189 * 2^(SIGNIFICAND_WIDTH - 1 - exponent). 4190 */ 4191 int shift = exponent - FloatConsts.SIGNIFICAND_WIDTH; 4192 4193 int twiceSignifFloor; 4194 // twiceSignifFloor will be == abs().shiftRight(shift).intValue() 4195 // We do the shift into an int directly to improve performance. 4196 4197 int nBits = shift & 0x1f; 4198 int nBits2 = 32 - nBits; 4199 4200 if (nBits == 0) { 4201 twiceSignifFloor = mag[0]; 4202 } else { 4203 twiceSignifFloor = mag[0] >>> nBits; 4204 if (twiceSignifFloor == 0) { 4205 twiceSignifFloor = (mag[0] << nBits2) | (mag[1] >>> nBits); 4206 } 4207 } 4208 4209 int signifFloor = twiceSignifFloor >> 1; 4210 signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit 4211 4212 /* 4213 * We round up if either the fractional part of signif is strictly 4214 * greater than 0.5 (which is true if the 0.5 bit is set and any lower 4215 * bit is set), or if the fractional part of signif is >= 0.5 and 4216 * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit 4217 * are set). This is equivalent to the desired HALF_EVEN rounding. 4218 */ 4219 boolean increment = (twiceSignifFloor & 1) != 0 4220 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift); 4221 int signifRounded = increment ? signifFloor + 1 : signifFloor; 4222 int bits = ((exponent + FloatConsts.EXP_BIAS)) 4223 << (FloatConsts.SIGNIFICAND_WIDTH - 1); 4224 bits += signifRounded; 4225 /* 4226 * If signifRounded == 2^24, we'd need to set all of the significand 4227 * bits to zero and add 1 to the exponent. This is exactly the behavior 4228 * we get from just adding signifRounded to bits directly. If the 4229 * exponent is Float.MAX_EXPONENT, we round up (correctly) to 4230 * Float.POSITIVE_INFINITY. 4231 */ 4232 bits |= signum & FloatConsts.SIGN_BIT_MASK; 4233 return Float.intBitsToFloat(bits); 4234 } 4235 4236 /** 4237 * Converts this BigInteger to a {@code double}. This 4238 * conversion is similar to the 4239 * <i>narrowing primitive conversion</i> from {@code double} to 4240 * {@code float} as defined in section 5.1.3 of 4241 * <cite>The Java™ Language Specification</cite>: 4242 * if this BigInteger has too great a magnitude 4243 * to represent as a {@code double}, it will be converted to 4244 * {@link Double#NEGATIVE_INFINITY} or {@link 4245 * Double#POSITIVE_INFINITY} as appropriate. Note that even when 4246 * the return value is finite, this conversion can lose 4247 * information about the precision of the BigInteger value. 4248 * 4249 * @return this BigInteger converted to a {@code double}. 4250 */ 4251 public double doubleValue() { 4252 if (signum == 0) { 4253 return 0.0; 4254 } 4255 4256 int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1; 4257 4258 // exponent == floor(log2(abs(this))Double) 4259 if (exponent < Long.SIZE - 1) { 4260 return longValue(); 4261 } else if (exponent > Double.MAX_EXPONENT) { 4262 return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY; 4263 } 4264 4265 /* 4266 * We need the top SIGNIFICAND_WIDTH bits, including the "implicit" 4267 * one bit. To make rounding easier, we pick out the top 4268 * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or 4269 * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1 4270 * bits, and signifFloor the top SIGNIFICAND_WIDTH. 4271 * 4272 * It helps to consider the real number signif = abs(this) * 4273 * 2^(SIGNIFICAND_WIDTH - 1 - exponent). 4274 */ 4275 int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH; 4276 4277 long twiceSignifFloor; 4278 // twiceSignifFloor will be == abs().shiftRight(shift).longValue() 4279 // We do the shift into a long directly to improve performance. 4280 4281 int nBits = shift & 0x1f; 4282 int nBits2 = 32 - nBits; 4283 4284 int highBits; 4285 int lowBits; 4286 if (nBits == 0) { 4287 highBits = mag[0]; 4288 lowBits = mag[1]; 4289 } else { 4290 highBits = mag[0] >>> nBits; 4291 lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits); 4292 if (highBits == 0) { 4293 highBits = lowBits; 4294 lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits); 4295 } 4296 } 4297 4298 twiceSignifFloor = ((highBits & LONG_MASK) << 32) 4299 | (lowBits & LONG_MASK); 4300 4301 long signifFloor = twiceSignifFloor >> 1; 4302 signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit 4303 4304 /* 4305 * We round up if either the fractional part of signif is strictly 4306 * greater than 0.5 (which is true if the 0.5 bit is set and any lower 4307 * bit is set), or if the fractional part of signif is >= 0.5 and 4308 * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit 4309 * are set). This is equivalent to the desired HALF_EVEN rounding. 4310 */ 4311 boolean increment = (twiceSignifFloor & 1) != 0 4312 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift); 4313 long signifRounded = increment ? signifFloor + 1 : signifFloor; 4314 long bits = (long) ((exponent + DoubleConsts.EXP_BIAS)) 4315 << (DoubleConsts.SIGNIFICAND_WIDTH - 1); 4316 bits += signifRounded; 4317 /* 4318 * If signifRounded == 2^53, we'd need to set all of the significand 4319 * bits to zero and add 1 to the exponent. This is exactly the behavior 4320 * we get from just adding signifRounded to bits directly. If the 4321 * exponent is Double.MAX_EXPONENT, we round up (correctly) to 4322 * Double.POSITIVE_INFINITY. 4323 */ 4324 bits |= signum & DoubleConsts.SIGN_BIT_MASK; 4325 return Double.longBitsToDouble(bits); 4326 } 4327 4328 /** 4329 * Returns a copy of the input array stripped of any leading zero bytes. 4330 */ 4331 private static int[] stripLeadingZeroInts(int val[]) { 4332 int vlen = val.length; 4333 int keep; 4334 4335 // Find first nonzero byte 4336 for (keep = 0; keep < vlen && val[keep] == 0; keep++) 4337 ; 4338 return java.util.Arrays.copyOfRange(val, keep, vlen); 4339 } 4340 4341 /** 4342 * Returns the input array stripped of any leading zero bytes. 4343 * Since the source is trusted the copying may be skipped. 4344 */ 4345 private static int[] trustedStripLeadingZeroInts(int val[]) { 4346 int vlen = val.length; 4347 int keep; 4348 4349 // Find first nonzero byte 4350 for (keep = 0; keep < vlen && val[keep] == 0; keep++) 4351 ; 4352 return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen); 4353 } 4354 4355 /** 4356 * Returns a copy of the input array stripped of any leading zero bytes. 4357 */ 4358 private static int[] stripLeadingZeroBytes(byte a[]) { 4359 int byteLength = a.length; 4360 int keep; 4361 4362 // Find first nonzero byte 4363 for (keep = 0; keep < byteLength && a[keep] == 0; keep++) 4364 ; 4365 4366 // Allocate new array and copy relevant part of input array 4367 int intLength = ((byteLength - keep) + 3) >>> 2; 4368 int[] result = new int[intLength]; 4369 int b = byteLength - 1; 4370 for (int i = intLength-1; i >= 0; i--) { 4371 result[i] = a[b--] & 0xff; 4372 int bytesRemaining = b - keep + 1; 4373 int bytesToTransfer = Math.min(3, bytesRemaining); 4374 for (int j=8; j <= (bytesToTransfer << 3); j += 8) 4375 result[i] |= ((a[b--] & 0xff) << j); 4376 } 4377 return result; 4378 } 4379 4380 /** 4381 * Takes an array a representing a negative 2's-complement number and 4382 * returns the minimal (no leading zero bytes) unsigned whose value is -a. 4383 */ 4384 private static int[] makePositive(byte a[]) { 4385 int keep, k; 4386 int byteLength = a.length; 4387 4388 // Find first non-sign (0xff) byte of input 4389 for (keep=0; keep < byteLength && a[keep] == -1; keep++) 4390 ; 4391 4392 4393 /* Allocate output array. If all non-sign bytes are 0x00, we must 4394 * allocate space for one extra output byte. */ 4395 for (k=keep; k < byteLength && a[k] == 0; k++) 4396 ; 4397 4398 int extraByte = (k == byteLength) ? 1 : 0; 4399 int intLength = ((byteLength - keep + extraByte) + 3) >>> 2; 4400 int result[] = new int[intLength]; 4401 4402 /* Copy one's complement of input into output, leaving extra 4403 * byte (if it exists) == 0x00 */ 4404 int b = byteLength - 1; 4405 for (int i = intLength-1; i >= 0; i--) { 4406 result[i] = a[b--] & 0xff; 4407 int numBytesToTransfer = Math.min(3, b-keep+1); 4408 if (numBytesToTransfer < 0) 4409 numBytesToTransfer = 0; 4410 for (int j=8; j <= 8*numBytesToTransfer; j += 8) 4411 result[i] |= ((a[b--] & 0xff) << j); 4412 4413 // Mask indicates which bits must be complemented 4414 int mask = -1 >>> (8*(3-numBytesToTransfer)); 4415 result[i] = ~result[i] & mask; 4416 } 4417 4418 // Add one to one's complement to generate two's complement 4419 for (int i=result.length-1; i >= 0; i--) { 4420 result[i] = (int)((result[i] & LONG_MASK) + 1); 4421 if (result[i] != 0) 4422 break; 4423 } 4424 4425 return result; 4426 } 4427 4428 /** 4429 * Takes an array a representing a negative 2's-complement number and 4430 * returns the minimal (no leading zero ints) unsigned whose value is -a. 4431 */ 4432 private static int[] makePositive(int a[]) { 4433 int keep, j; 4434 4435 // Find first non-sign (0xffffffff) int of input 4436 for (keep=0; keep < a.length && a[keep] == -1; keep++) 4437 ; 4438 4439 /* Allocate output array. If all non-sign ints are 0x00, we must 4440 * allocate space for one extra output int. */ 4441 for (j=keep; j < a.length && a[j] == 0; j++) 4442 ; 4443 int extraInt = (j == a.length ? 1 : 0); 4444 int result[] = new int[a.length - keep + extraInt]; 4445 4446 /* Copy one's complement of input into output, leaving extra 4447 * int (if it exists) == 0x00 */ 4448 for (int i = keep; i < a.length; i++) 4449 result[i - keep + extraInt] = ~a[i]; 4450 4451 // Add one to one's complement to generate two's complement 4452 for (int i=result.length-1; ++result[i] == 0; i--) 4453 ; 4454 4455 return result; 4456 } 4457 4458 /* 4459 * The following two arrays are used for fast String conversions. Both 4460 * are indexed by radix. The first is the number of digits of the given 4461 * radix that can fit in a Java long without "going negative", i.e., the 4462 * highest integer n such that radix**n < 2**63. The second is the 4463 * "long radix" that tears each number into "long digits", each of which 4464 * consists of the number of digits in the corresponding element in 4465 * digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have 4466 * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not 4467 * used. 4468 */ 4469 private static int digitsPerLong[] = {0, 0, 4470 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14, 4471 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12}; 4472 4473 private static BigInteger longRadix[] = {null, null, 4474 valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL), 4475 valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL), 4476 valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L), 4477 valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L), 4478 valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L), 4479 valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL), 4480 valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L), 4481 valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L), 4482 valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L), 4483 valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L), 4484 valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L), 4485 valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L), 4486 valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL), 4487 valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L), 4488 valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L), 4489 valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L), 4490 valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L), 4491 valueOf(0x41c21cb8e1000000L)}; 4492 4493 /* 4494 * These two arrays are the integer analogue of above. 4495 */ 4496 private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11, 4497 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 4498 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5}; 4499 4500 private static int intRadix[] = {0, 0, 4501 0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800, 4502 0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61, 4503 0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000, 4504 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d, 4505 0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40, 4506 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41, 4507 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400 4508 }; 4509 4510 /** 4511 * These routines provide access to the two's complement representation 4512 * of BigIntegers. 4513 */ 4514 4515 /** 4516 * Returns the length of the two's complement representation in ints, 4517 * including space for at least one sign bit. 4518 */ 4519 private int intLength() { 4520 return (bitLength() >>> 5) + 1; 4521 } 4522 4523 /* Returns sign bit */ 4524 private int signBit() { 4525 return signum < 0 ? 1 : 0; 4526 } 4527 4528 /* Returns an int of sign bits */ 4529 private int signInt() { 4530 return signum < 0 ? -1 : 0; 4531 } 4532 4533 /** 4534 * Returns the specified int of the little-endian two's complement 4535 * representation (int 0 is the least significant). The int number can 4536 * be arbitrarily high (values are logically preceded by infinitely many 4537 * sign ints). 4538 */ 4539 private int getInt(int n) { 4540 if (n < 0) 4541 return 0; 4542 if (n >= mag.length) 4543 return signInt(); 4544 4545 int magInt = mag[mag.length-n-1]; 4546 4547 return (signum >= 0 ? magInt : 4548 (n <= firstNonzeroIntNum() ? -magInt : ~magInt)); 4549 } 4550 4551 /** 4552 * Returns the index of the int that contains the first nonzero int in the 4553 * little-endian binary representation of the magnitude (int 0 is the 4554 * least significant). If the magnitude is zero, return value is undefined. 4555 */ 4556 private int firstNonzeroIntNum() { 4557 int fn = firstNonzeroIntNum - 2; 4558 if (fn == -2) { // firstNonzeroIntNum not initialized yet 4559 fn = 0; 4560 4561 // Search for the first nonzero int 4562 int i; 4563 int mlen = mag.length; 4564 for (i = mlen - 1; i >= 0 && mag[i] == 0; i--) 4565 ; 4566 fn = mlen - i - 1; 4567 firstNonzeroIntNum = fn + 2; // offset by two to initialize 4568 } 4569 return fn; 4570 } 4571 4572 /** use serialVersionUID from JDK 1.1. for interoperability */ 4573 private static final long serialVersionUID = -8287574255936472291L; 4574 4575 /** 4576 * Serializable fields for BigInteger. 4577 * 4578 * @serialField signum int 4579 * signum of this BigInteger. 4580 * @serialField magnitude int[] 4581 * magnitude array of this BigInteger. 4582 * @serialField bitCount int 4583 * number of bits in this BigInteger 4584 * @serialField bitLength int 4585 * the number of bits in the minimal two's-complement 4586 * representation of this BigInteger 4587 * @serialField lowestSetBit int 4588 * lowest set bit in the twos complement representation 4589 */ 4590 private static final ObjectStreamField[] serialPersistentFields = { 4591 new ObjectStreamField("signum", Integer.TYPE), 4592 new ObjectStreamField("magnitude", byte[].class), 4593 new ObjectStreamField("bitCount", Integer.TYPE), 4594 new ObjectStreamField("bitLength", Integer.TYPE), 4595 new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE), 4596 new ObjectStreamField("lowestSetBit", Integer.TYPE) 4597 }; 4598 4599 /** 4600 * Reconstitute the {@code BigInteger} instance from a stream (that is, 4601 * deserialize it). The magnitude is read in as an array of bytes 4602 * for historical reasons, but it is converted to an array of ints 4603 * and the byte array is discarded. 4604 * Note: 4605 * The current convention is to initialize the cache fields, bitCount, 4606 * bitLength and lowestSetBit, to 0 rather than some other marker value. 4607 * Therefore, no explicit action to set these fields needs to be taken in 4608 * readObject because those fields already have a 0 value be default since 4609 * defaultReadObject is not being used. 4610 */ 4611 private void readObject(java.io.ObjectInputStream s) 4612 throws java.io.IOException, ClassNotFoundException { 4613 /* 4614 * In order to maintain compatibility with previous serialized forms, 4615 * the magnitude of a BigInteger is serialized as an array of bytes. 4616 * The magnitude field is used as a temporary store for the byte array 4617 * that is deserialized. The cached computation fields should be 4618 * transient but are serialized for compatibility reasons. 4619 */ 4620 4621 // prepare to read the alternate persistent fields 4622 ObjectInputStream.GetField fields = s.readFields(); 4623 4624 // Read the alternate persistent fields that we care about 4625 int sign = fields.get("signum", -2); 4626 byte[] magnitude = (byte[])fields.get("magnitude", null); 4627 4628 // Validate signum 4629 if (sign < -1 || sign > 1) { 4630 String message = "BigInteger: Invalid signum value"; 4631 if (fields.defaulted("signum")) 4632 message = "BigInteger: Signum not present in stream"; 4633 throw new java.io.StreamCorruptedException(message); 4634 } 4635 int[] mag = stripLeadingZeroBytes(magnitude); 4636 if ((mag.length == 0) != (sign == 0)) { 4637 String message = "BigInteger: signum-magnitude mismatch"; 4638 if (fields.defaulted("magnitude")) 4639 message = "BigInteger: Magnitude not present in stream"; 4640 throw new java.io.StreamCorruptedException(message); 4641 } 4642 4643 // Commit final fields via Unsafe 4644 UnsafeHolder.putSign(this, sign); 4645 4646 // Calculate mag field from magnitude and discard magnitude 4647 UnsafeHolder.putMag(this, mag); 4648 if (mag.length >= MAX_MAG_LENGTH) { 4649 try { 4650 checkRange(); 4651 } catch (ArithmeticException e) { 4652 throw new java.io.StreamCorruptedException("BigInteger: Out of the supported range"); 4653 } 4654 } 4655 } 4656 4657 // Support for resetting final fields while deserializing 4658 private static class UnsafeHolder { 4659 private static final sun.misc.Unsafe unsafe; 4660 private static final long signumOffset; 4661 private static final long magOffset; 4662 static { 4663 try { 4664 unsafe = sun.misc.Unsafe.getUnsafe(); 4665 signumOffset = unsafe.objectFieldOffset 4666 (BigInteger.class.getDeclaredField("signum")); 4667 magOffset = unsafe.objectFieldOffset 4668 (BigInteger.class.getDeclaredField("mag")); 4669 } catch (Exception ex) { 4670 throw new ExceptionInInitializerError(ex); 4671 } 4672 } 4673 4674 static void putSign(BigInteger bi, int sign) { 4675 unsafe.putIntVolatile(bi, signumOffset, sign); 4676 } 4677 4678 static void putMag(BigInteger bi, int[] magnitude) { 4679 unsafe.putObjectVolatile(bi, magOffset, magnitude); 4680 } 4681 } 4682 4683 /** 4684 * Save the {@code BigInteger} instance to a stream. 4685 * The magnitude of a BigInteger is serialized as a byte array for 4686 * historical reasons. 4687 * 4688 * @serialData two necessary fields are written as well as obsolete 4689 * fields for compatibility with older versions. 4690 */ 4691 private void writeObject(ObjectOutputStream s) throws IOException { 4692 // set the values of the Serializable fields 4693 ObjectOutputStream.PutField fields = s.putFields(); 4694 fields.put("signum", signum); 4695 fields.put("magnitude", magSerializedForm()); 4696 // The values written for cached fields are compatible with older 4697 // versions, but are ignored in readObject so don't otherwise matter. 4698 // BEGIN Android-changed: Don't include the following fields. 4699 // fields.put("bitCount", -1); 4700 // fields.put("bitLength", -1); 4701 // fields.put("lowestSetBit", -2); 4702 // fields.put("firstNonzeroByteNum", -2); 4703 // END Android-changed 4704 4705 // save them 4706 s.writeFields(); 4707 } 4708 4709 /** 4710 * Returns the mag array as an array of bytes. 4711 */ 4712 private byte[] magSerializedForm() { 4713 int len = mag.length; 4714 4715 int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0])); 4716 int byteLen = (bitLen + 7) >>> 3; 4717 byte[] result = new byte[byteLen]; 4718 4719 for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0; 4720 i >= 0; i--) { 4721 if (bytesCopied == 4) { 4722 nextInt = mag[intIndex--]; 4723 bytesCopied = 1; 4724 } else { 4725 nextInt >>>= 8; 4726 bytesCopied++; 4727 } 4728 result[i] = (byte)nextInt; 4729 } 4730 return result; 4731 } 4732 4733 /** 4734 * Converts this {@code BigInteger} to a {@code long}, checking 4735 * for lost information. If the value of this {@code BigInteger} 4736 * is out of the range of the {@code long} type, then an 4737 * {@code ArithmeticException} is thrown. 4738 * 4739 * @return this {@code BigInteger} converted to a {@code long}. 4740 * @throws ArithmeticException if the value of {@code this} will 4741 * not exactly fit in a {@code long}. 4742 * @see BigInteger#longValue 4743 * @since 1.8 4744 */ 4745 public long longValueExact() { 4746 if (mag.length <= 2 && bitLength() <= 63) 4747 return longValue(); 4748 else 4749 throw new ArithmeticException("BigInteger out of long range"); 4750 } 4751 4752 /** 4753 * Converts this {@code BigInteger} to an {@code int}, checking 4754 * for lost information. If the value of this {@code BigInteger} 4755 * is out of the range of the {@code int} type, then an 4756 * {@code ArithmeticException} is thrown. 4757 * 4758 * @return this {@code BigInteger} converted to an {@code int}. 4759 * @throws ArithmeticException if the value of {@code this} will 4760 * not exactly fit in a {@code int}. 4761 * @see BigInteger#intValue 4762 * @since 1.8 4763 */ 4764 public int intValueExact() { 4765 if (mag.length <= 1 && bitLength() <= 31) 4766 return intValue(); 4767 else 4768 throw new ArithmeticException("BigInteger out of int range"); 4769 } 4770 4771 /** 4772 * Converts this {@code BigInteger} to a {@code short}, checking 4773 * for lost information. If the value of this {@code BigInteger} 4774 * is out of the range of the {@code short} type, then an 4775 * {@code ArithmeticException} is thrown. 4776 * 4777 * @return this {@code BigInteger} converted to a {@code short}. 4778 * @throws ArithmeticException if the value of {@code this} will 4779 * not exactly fit in a {@code short}. 4780 * @see BigInteger#shortValue 4781 * @since 1.8 4782 */ 4783 public short shortValueExact() { 4784 if (mag.length <= 1 && bitLength() <= 31) { 4785 int value = intValue(); 4786 if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) 4787 return shortValue(); 4788 } 4789 throw new ArithmeticException("BigInteger out of short range"); 4790 } 4791 4792 /** 4793 * Converts this {@code BigInteger} to a {@code byte}, checking 4794 * for lost information. If the value of this {@code BigInteger} 4795 * is out of the range of the {@code byte} type, then an 4796 * {@code ArithmeticException} is thrown. 4797 * 4798 * @return this {@code BigInteger} converted to a {@code byte}. 4799 * @throws ArithmeticException if the value of {@code this} will 4800 * not exactly fit in a {@code byte}. 4801 * @see BigInteger#byteValue 4802 * @since 1.8 4803 */ 4804 public byte byteValueExact() { 4805 if (mag.length <= 1 && bitLength() <= 31) { 4806 int value = intValue(); 4807 if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) 4808 return byteValue(); 4809 } 4810 throw new ArithmeticException("BigInteger out of byte range"); 4811 } 4812 } 4813