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