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