1 /* 2 * Hunt - A refined core library for D programming language. 3 * 4 * Copyright (C) 2018-2019 HuntLabs 5 * 6 * Website: https://www.huntlabs.net/ 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module hunt.math.BigInteger; 13 14 import hunt.Double; 15 import hunt.Float; 16 import hunt.Integer; 17 import hunt.Long; 18 import hunt.Number; 19 20 import hunt.Char; 21 import hunt.text.CharacterData; 22 import hunt.Exceptions; 23 import hunt.text; 24 25 import std.algorithm; 26 import std.conv; 27 import std.math; 28 import std.random; 29 import std.string; 30 31 /** 32 * Immutable arbitrary-precision integers. All operations behave as if 33 * BigIntegers were represented in two's-complement notation (like Java's 34 * primitive integer types). BigInteger provides analogues to all of Java's 35 * primitive integer operators, and all relevant methods from java.lang.std.math. 36 * Additionally, BigInteger provides operations for modular arithmetic, GCD 37 * calculation, primality testing, prime generation, bit manipulation, 38 * and a few other miscellaneous operations. 39 * 40 * <p>Semantics of arithmetic operations exactly mimic those of Java's integer 41 * arithmetic operators, as defined in <i>The Java Language Specification</i>. 42 * For example, division by zero throws an {@code ArithmeticException}, and 43 * division of a negative by a positive yields a negative (or zero) remainder. 44 * All of the details in the Spec concerning overflow are ignored, as 45 * BigIntegers are made as large as necessary to accommodate the results of an 46 * operation. 47 * 48 * <p>Semantics of shift operations extend those of Java's shift operators 49 * to allow for negative shift distances. A right-shift with a negative 50 * shift distance results in a left shift, and vice-versa. The unsigned 51 * right shift operator ({@code >>>}) is omitted, as this operation makes 52 * little sense in combination with the "infinite word size" abstraction 53 * provided by this class. 54 * 55 * <p>Semantics of bitwise logical operations exactly mimic those of Java's 56 * bitwise integer operators. The binary operators ({@code and}, 57 * {@code or}, {@code xor}) implicitly perform sign extension on the shorter 58 * of the two operands prior to performing the operation. 59 * 60 * <p>Comparison operations perform signed integer comparisons, analogous to 61 * those performed by Java's relational and equality operators. 62 * 63 * <p>Modular arithmetic operations are provided to compute residues, perform 64 * exponentiation, and compute multiplicative inverses. These methods always 65 * return a non-negative result, between {@code 0} and {@code (modulus - 1)}, 66 * inclusive. 67 * 68 * <p>Bit operations operate on a single bit of the two's-complement 69 * representation of their operand. If necessary, the operand is sign- 70 * extended so that it contains the designated bit. None of the single-bit 71 * operations can produce a BigInteger with a different sign from the 72 * BigInteger being operated on, as they affect only a single bit, and the 73 * "infinite word size" abstraction provided by this class ensures that there 74 * are infinitely many "virtual sign bits" preceding each BigInteger. 75 * 76 * <p>For the sake of brevity and clarity, pseudo-code is used throughout the 77 * descriptions of BigInteger methods. The pseudo-code expression 78 * {@code (i + j)} is shorthand for "a BigInteger whose value is 79 * that of the BigInteger {@code i} plus that of the BigInteger {@code j}." 80 * The pseudo-code expression {@code (i == j)} is shorthand for 81 * "{@code true} if and only if the BigInteger {@code i} represents the same 82 * value as the BigInteger {@code j}." Other pseudo-code expressions are 83 * interpreted similarly. 84 * 85 * <p>All methods and constructors in this class throw 86 * {@code NullPointerException} when passed 87 * a null object reference for any input parameter. 88 * 89 * BigInteger must support values in the range 90 * -2<sup>{@code int.max}</sup> (exclusive) to 91 * +2<sup>{@code int.max}</sup> (exclusive) 92 * and may support values outside of that range. 93 * 94 * The range of probable prime values is limited and may be less than 95 * the full supported positive range of {@code BigInteger}. 96 * The range must be at least 1 to 2<sup>500000000</sup>. 97 * 98 * @implNote 99 * BigInteger constructors and operations throw {@code ArithmeticException} when 100 * the result is out of the supported range of 101 * -2<sup>{@code int.max}</sup> (exclusive) to 102 * +2<sup>{@code int.max}</sup> (exclusive). 103 * 104 * @see BigDecimal 105 * @jls 4.2.2 Integer Operations 106 * @author Josh Bloch 107 * @author Michael McCloskey 108 * @author Alan Eliasen 109 * @author Timothy Buktu 110 * @since 1.1 111 */ 112 113 class BigInteger : Number { 114 /** 115 * The signum of this BigInteger: -1 for negative, 0 for zero, or 116 * 1 for positive. Note that the BigInteger zero <em>must</em> have 117 * a signum of 0. This is necessary to ensures that there is exactly one 118 * representation for each BigInteger value. 119 */ 120 private int _signum; 121 122 /** 123 * The magnitude of this BigInteger, in <i>big-endian</i> order: the 124 * zeroth element of this array is the most-significant int of the 125 * magnitude. The magnitude must be "minimal" in that the most-significant 126 * int ({@code mag[0]}) must be non-zero. This is necessary to 127 * ensure that there is exactly one representation for each BigInteger 128 * value. Note that this implies that the BigInteger zero has a 129 * zero-length mag array. 130 */ 131 private int[] mag; 132 133 // The following fields are stable variables. A stable variable's value 134 // changes at most once from the default zero value to a non-zero stable 135 // value. A stable value is calculated lazily on demand. 136 137 /** 138 * One plus the bitCount of this BigInteger. This is a stable variable. 139 * 140 * @see #bitCount 141 */ 142 private int bitCountPlusOne; 143 144 /** 145 * One plus the bitLength of this BigInteger. This is a stable variable. 146 * (either value is acceptable). 147 * 148 * @see #bitLength() 149 */ 150 private int bitLengthPlusOne; 151 152 /** 153 * Two plus the lowest set bit of this BigInteger. This is a stable variable. 154 * 155 * @see #getLowestSetBit 156 */ 157 private int lowestSetBitPlusTwo; 158 159 /** 160 * Two plus the index of the lowest-order int in the magnitude of this 161 * BigInteger that contains a nonzero int. This is a stable variable. The 162 * least significant int has int-number 0, the next int in order of 163 * increasing significance has int-number 1, and so forth. 164 * 165 * <p>Note: never used for a BigInteger with a magnitude of zero. 166 * 167 * @see #firstNonzeroIntNum() 168 */ 169 private int firstNonzeroIntNumPlusTwo; 170 171 /** 172 * This mask is used to obtain the value of an int as if it were unsigned. 173 */ 174 enum long LONG_MASK = 0xffffffffL; 175 176 /** 177 * This constant limits {@code mag.length} of BigIntegers to the supported 178 * range. 179 */ 180 private enum int MAX_MAG_LENGTH = int.max / int.sizeof + 1; // (1 << 26) 181 182 /** 183 * Bit lengths larger than this constant can cause overflow in searchLen 184 * calculation and in BitSieve.singleSearch method. 185 */ 186 private enum int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000; 187 188 /** 189 * The threshold value for using Karatsuba multiplication. If the number 190 * of ints in both mag arrays are greater than this number, then 191 * Karatsuba multiplication will be used. This value is found 192 * experimentally to work well. 193 */ 194 private enum int KARATSUBA_THRESHOLD = 80; 195 196 /** 197 * The threshold value for using 3-way Toom-Cook multiplication. 198 * If the number of ints in each mag array is greater than the 199 * Karatsuba threshold, and the number of ints in at least one of 200 * the mag arrays is greater than this threshold, then Toom-Cook 201 * multiplication will be used. 202 */ 203 private enum int TOOM_COOK_THRESHOLD = 240; 204 205 /** 206 * The threshold value for using Karatsuba squaring. If the number 207 * of ints in the number are larger than this value, 208 * Karatsuba squaring will be used. This value is found 209 * experimentally to work well. 210 */ 211 private enum int KARATSUBA_SQUARE_THRESHOLD = 128; 212 213 /** 214 * The threshold value for using Toom-Cook squaring. If the number 215 * of ints in the number are larger than this value, 216 * Toom-Cook squaring will be used. This value is found 217 * experimentally to work well. 218 */ 219 private enum int TOOM_COOK_SQUARE_THRESHOLD = 216; 220 221 /** 222 * The threshold value for using Burnikel-Ziegler division. If the number 223 * of ints in the divisor are larger than this value, Burnikel-Ziegler 224 * division may be used. This value is found experimentally to work well. 225 */ 226 enum int BURNIKEL_ZIEGLER_THRESHOLD = 80; 227 228 /** 229 * The offset value for using Burnikel-Ziegler division. If the number 230 * of ints in the divisor exceeds the Burnikel-Ziegler threshold, and the 231 * number of ints in the dividend is greater than the number of ints in the 232 * divisor plus this value, Burnikel-Ziegler division will be used. This 233 * value is found experimentally to work well. 234 */ 235 enum int BURNIKEL_ZIEGLER_OFFSET = 40; 236 237 /** 238 * The threshold value for using Schoenhage recursive base conversion. If 239 * the number of ints in the number are larger than this value, 240 * the Schoenhage algorithm will be used. In practice, it appears that the 241 * Schoenhage routine is faster for any threshold down to 2, and is 242 * relatively flat for thresholds between 2-25, so this choice may be 243 * varied within this range for very small effect. 244 */ 245 private enum int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20; 246 247 /** 248 * The threshold value for using squaring code to perform multiplication 249 * of a {@code BigInteger} instance by itself. If the number of ints in 250 * the number are larger than this value, {@code multiply(this)} will 251 * return {@code square()}. 252 */ 253 private enum int MULTIPLY_SQUARE_THRESHOLD = 20; 254 255 /** 256 * The threshold for using an intrinsic version of 257 * implMontgomeryXXX to perform Montgomery multiplication. If the 258 * number of ints in the number is more than this value we do not 259 * use the intrinsic. 260 */ 261 private enum int MONTGOMERY_INTRINSIC_THRESHOLD = 512; 262 263 264 // Constructors 265 266 /** 267 * Translates a byte sub-array containing the two's-complement binary 268 * representation of a BigInteger into a BigInteger. The sub-array is 269 * specified via an offset into the array and a length. The sub-array is 270 * assumed to be in <i>big-endian</i> byte-order: the most significant 271 * byte is the element at index {@code off}. The {@code val} array is 272 * assumed to be unchanged for the duration of the constructor call. 273 * 274 * An {@code IndexOutOfBoundsException} is thrown if the length of the array 275 * {@code val} is non-zero and either {@code off} is negative, {@code len} 276 * is negative, or {@code off+len} is greater than the length of 277 * {@code val}. 278 * 279 * @param val byte array containing a sub-array which is the big-endian 280 * two's-complement binary representation of a BigInteger. 281 * @param off the start offset of the binary representation. 282 * @param len the number of bytes to use. 283 * @throws NumberFormatException {@code val} is zero bytes long. 284 * @throws IndexOutOfBoundsException if the provided array offset and 285 * length would cause an index into the byte array to be 286 * negative or greater than or equal to the array length. 287 * @since 9 288 */ 289 this(byte[] val, int off, int len) { 290 if (val.length == 0) { 291 throw new NumberFormatException("Zero length BigInteger"); 292 } else if ((off < 0) || (off >= cast(int)val.length) || (len < 0) || 293 (len > val.length - off)) { // 0 <= off < val.length 294 throw new IndexOutOfBoundsException(); 295 } 296 297 if (val[off] < 0) { 298 mag = makePositive(val, off, len); 299 _signum = -1; 300 } else { 301 mag = stripLeadingZeroBytes(val, off, len); 302 _signum = (mag.length == 0 ? 0 : 1); 303 } 304 if (mag.length >= MAX_MAG_LENGTH) { 305 checkRange(); 306 } 307 } 308 309 /** 310 * Translates a byte array containing the two's-complement binary 311 * representation of a BigInteger into a BigInteger. The input array is 312 * assumed to be in <i>big-endian</i> byte-order: the most significant 313 * byte is in the zeroth element. The {@code val} array is assumed to be 314 * unchanged for the duration of the constructor call. 315 * 316 * @param val big-endian two's-complement binary representation of a 317 * BigInteger. 318 * @throws NumberFormatException {@code val} is zero bytes long. 319 */ 320 this(byte[] val) { 321 this(val, 0, cast(int)val.length); 322 } 323 324 /** 325 * This private constructor translates an int array containing the 326 * two's-complement binary representation of a BigInteger into a 327 * BigInteger. The input array is assumed to be in <i>big-endian</i> 328 * int-order: the most significant int is in the zeroth element. The 329 * {@code val} array is assumed to be unchanged for the duration of 330 * the constructor call. 331 */ 332 private this(int[] val) { 333 if (val.length == 0) 334 throw new NumberFormatException("Zero length BigInteger"); 335 336 if (val[0] < 0) { 337 mag = makePositive(val); 338 _signum = -1; 339 } else { 340 mag = trustedStripLeadingZeroInts(val); 341 _signum = (mag.length == 0 ? 0 : 1); 342 } 343 if (mag.length >= MAX_MAG_LENGTH) { 344 checkRange(); 345 } 346 } 347 348 /** 349 * Translates the sign-magnitude representation of a BigInteger into a 350 * BigInteger. The sign is represented as an integer signum value: -1 for 351 * negative, 0 for zero, or 1 for positive. The magnitude is a sub-array of 352 * a byte array in <i>big-endian</i> byte-order: the most significant byte 353 * is the element at index {@code off}. A zero value of the length 354 * {@code len} is permissible, and will result in a BigInteger value of 0, 355 * whether signum is -1, 0 or 1. The {@code magnitude} array is assumed to 356 * be unchanged for the duration of the constructor call. 357 * 358 * An {@code IndexOutOfBoundsException} is thrown if the length of the array 359 * {@code magnitude} is non-zero and either {@code off} is negative, 360 * {@code len} is negative, or {@code off+len} is greater than the length of 361 * {@code magnitude}. 362 * 363 * @param signum signum of the number (-1 for negative, 0 for zero, 1 364 * for positive). 365 * @param magnitude big-endian binary representation of the magnitude of 366 * the number. 367 * @param off the start offset of the binary representation. 368 * @param len the number of bytes to use. 369 * @throws NumberFormatException {@code signum} is not one of the three 370 * legal values (-1, 0, and 1), or {@code signum} is 0 and 371 * {@code magnitude} contains one or more non-zero bytes. 372 * @throws IndexOutOfBoundsException if the provided array offset and 373 * length would cause an index into the byte array to be 374 * negative or greater than or equal to the array length. 375 * @since 9 376 */ 377 this(int signum, byte[] magnitude, int off, int len) { 378 if (signum < -1 || signum > 1) { 379 throw(new NumberFormatException("Invalid signum value")); 380 } else if ((off < 0) || (len < 0) || 381 (len > 0 && 382 ((off >= magnitude.length) || 383 (len > magnitude.length - off)))) { // 0 <= off < magnitude.length 384 throw new IndexOutOfBoundsException(); 385 } 386 387 // stripLeadingZeroBytes() returns a zero length array if len == 0 388 this.mag = stripLeadingZeroBytes(magnitude, off, len); 389 390 if (this.mag.length == 0) { 391 this._signum = 0; 392 } else { 393 if (signum == 0) 394 throw(new NumberFormatException("signum-magnitude mismatch")); 395 this._signum = signum; 396 } 397 if (mag.length >= MAX_MAG_LENGTH) { 398 checkRange(); 399 } 400 } 401 402 /** 403 * Translates the sign-magnitude representation of a BigInteger into a 404 * BigInteger. The sign is represented as an integer signum value: -1 for 405 * negative, 0 for zero, or 1 for positive. The magnitude is a byte array 406 * in <i>big-endian</i> byte-order: the most significant byte is the 407 * zeroth element. A zero-length magnitude array is permissible, and will 408 * result in a BigInteger value of 0, whether signum is -1, 0 or 1. The 409 * {@code magnitude} array is assumed to be unchanged for the duration of 410 * the constructor call. 411 * 412 * @param signum signum of the number (-1 for negative, 0 for zero, 1 413 * for positive). 414 * @param magnitude big-endian binary representation of the magnitude of 415 * the number. 416 * @throws NumberFormatException {@code signum} is not one of the three 417 * legal values (-1, 0, and 1), or {@code signum} is 0 and 418 * {@code magnitude} contains one or more non-zero bytes. 419 */ 420 this(int signum, byte[] magnitude) { 421 this(signum, magnitude, 0, cast(int)magnitude.length); 422 } 423 424 /** 425 * A constructor for internal use that translates the sign-magnitude 426 * representation of a BigInteger into a BigInteger. It checks the 427 * arguments and copies the magnitude so this constructor would be 428 * safe for external use. The {@code magnitude} array is assumed to be 429 * unchanged for the duration of the constructor call. 430 */ 431 private this(int signum, int[] magnitude) { 432 this.mag = stripLeadingZeroInts(magnitude); 433 434 if (signum < -1 || signum > 1) 435 throw(new NumberFormatException("Invalid signum value")); 436 437 if (this.mag.length == 0) { 438 this._signum = 0; 439 } else { 440 if (signum == 0) 441 throw(new NumberFormatException("signum-magnitude mismatch")); 442 this._signum = signum; 443 } 444 if (mag.length >= MAX_MAG_LENGTH) { 445 checkRange(); 446 } 447 } 448 449 /** 450 * Translates the string representation of a BigInteger in the 451 * specified radix into a BigInteger. The string representation 452 * consists of an optional minus or plus sign followed by a 453 * sequence of one or more digits in the specified radix. The 454 * character-to-digit mapping is provided by {@code 455 * CharacterHelper.digit}. The string may not contain any extraneous 456 * characters (whitespace, for example). 457 * 458 * @param val string representation of BigInteger. 459 * @param radix radix to be used in interpreting {@code val}. 460 * @throws NumberFormatException {@code val} is not a valid representation 461 * of a BigInteger in the specified radix, or {@code radix} is 462 * outside the range from {@link Character#MIN_RADIX} to 463 * {@link Character#MAX_RADIX}, inclusive. 464 * @see Character#digit 465 */ 466 this(string val, int radix) { 467 int cursor = 0, numDigits; 468 int len = cast(int)val.length; 469 470 if (radix < Char.MIN_RADIX || radix > Char.MAX_RADIX) 471 throw new NumberFormatException("Radix out of range"); 472 if (len == 0) 473 throw new NumberFormatException("Zero length BigInteger"); 474 475 // Check for at most one leading sign 476 int sign = 1; 477 ptrdiff_t index1 = val.lastIndexOf('-'); 478 ptrdiff_t index2 = val.lastIndexOf('+'); 479 if (index1 >= 0) { 480 if (index1 != 0 || index2 >= 0) { 481 throw new NumberFormatException("Illegal embedded sign character"); 482 } 483 sign = -1; 484 cursor = 1; 485 } else if (index2 >= 0) { 486 if (index2 != 0) { 487 throw new NumberFormatException("Illegal embedded sign character"); 488 } 489 cursor = 1; 490 } 491 if (cursor == len) 492 throw new NumberFormatException("Zero length BigInteger"); 493 494 // Skip leading zeros and compute number of digits in magnitude 495 while (cursor < len && 496 CharacterHelper.digit(val[cursor], radix) == 0) { 497 cursor++; 498 } 499 500 if (cursor == len) { 501 _signum = 0; 502 mag = ZERO.mag; 503 return; 504 } 505 506 numDigits = len - cursor; 507 _signum = sign; 508 509 // Pre-allocate array of expected size. May be too large but can 510 // never be too small. Typically exact. 511 long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1; 512 if (numBits + 31 >= (1L << 32)) { 513 reportOverflow(); 514 } 515 int numWords = cast(int) (numBits + 31) >>> 5; 516 int[] magnitude = new int[numWords]; 517 518 // Process first (potentially short) digit group 519 int firstGroupLen = numDigits % digitsPerInt[radix]; 520 if (firstGroupLen == 0) 521 firstGroupLen = digitsPerInt[radix]; 522 string group = val.substring(cursor, cursor += firstGroupLen); 523 magnitude[numWords - 1] = to!int(group, radix); 524 if (magnitude[numWords - 1] < 0) 525 throw new NumberFormatException("Illegal digit"); 526 527 // Process remaining digit groups 528 int superRadix = intRadix[radix]; 529 int groupVal = 0; 530 while (cursor < len) { 531 group = val.substring(cursor, cursor += digitsPerInt[radix]); 532 groupVal = to!int(group, radix); 533 if (groupVal < 0) 534 throw new NumberFormatException("Illegal digit"); 535 destructiveMulAdd(magnitude, superRadix, groupVal); 536 } 537 // Required for cases where the array was overallocated. 538 mag = trustedStripLeadingZeroInts(magnitude); 539 if (mag.length >= MAX_MAG_LENGTH) { 540 checkRange(); 541 } 542 } 543 544 /* 545 * Constructs a new BigInteger using a char array with radix=10. 546 * Sign is precalculated outside and not allowed in the val. The {@code val} 547 * array is assumed to be unchanged for the duration of the constructor 548 * call. 549 */ 550 this(char[] val, int sign, int len) { 551 int cursor = 0, numDigits; 552 553 // Skip leading zeros and compute number of digits in magnitude 554 while (cursor < len && CharacterHelper.digit(val[cursor], 10) == 0) { 555 cursor++; 556 } 557 if (cursor == len) { 558 _signum = 0; 559 mag = ZERO.mag; 560 return; 561 } 562 563 numDigits = len - cursor; 564 _signum = sign; 565 // Pre-allocate array of expected size 566 int numWords; 567 if (len < 10) { 568 numWords = 1; 569 } else { 570 long numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1; 571 if (numBits + 31 >= (1L << 32)) { 572 reportOverflow(); 573 } 574 numWords = cast(int) (numBits + 31) >>> 5; 575 } 576 int[] magnitude = new int[numWords]; 577 578 // Process first (potentially short) digit group 579 int firstGroupLen = numDigits % digitsPerInt[10]; 580 if (firstGroupLen == 0) 581 firstGroupLen = digitsPerInt[10]; 582 magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen); 583 584 // Process remaining digit groups 585 while (cursor < len) { 586 int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]); 587 destructiveMulAdd(magnitude, intRadix[10], groupVal); 588 } 589 mag = trustedStripLeadingZeroInts(magnitude); 590 if (mag.length >= MAX_MAG_LENGTH) { 591 checkRange(); 592 } 593 } 594 595 // Create an integer with the digits between the two indexes 596 // Assumes start < end. The result may be negative, but it 597 // is to be treated as an unsigned value. 598 private int parseInt(char[] source, int start, int end) { 599 int result = CharacterHelper.digit(source[start++], 10); 600 if (result == -1) 601 throw new NumberFormatException(cast(string)(source)); 602 603 for (int index = start; index < end; index++) { 604 int nextVal = CharacterHelper.digit(source[index], 10); 605 if (nextVal == -1) 606 throw new NumberFormatException(cast(string)(source)); 607 result = 10*result + nextVal; 608 } 609 610 return result; 611 } 612 613 // bitsPerDigit in the given radix times 1024 614 // Rounded up to avoid underallocation. 615 private enum long[] bitsPerDigit = [ 0, 0, 616 1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672, 617 3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633, 618 4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210, 619 5253, 5295]; 620 621 // Multiply x array times word y in place, and add word z 622 private static void destructiveMulAdd(int[] x, int y, int z) { 623 // Perform the multiplication word by word 624 long ylong = y & LONG_MASK; 625 long zlong = z & LONG_MASK; 626 int len = cast(int)x.length; 627 628 long product = 0; 629 long carry = 0; 630 for (int i = len-1; i >= 0; i--) { 631 product = ylong * (x[i] & LONG_MASK) + carry; 632 x[i] = cast(int)product; 633 carry = product >>> 32; 634 } 635 636 // Perform the addition 637 long sum = (x[len-1] & LONG_MASK) + zlong; 638 x[len-1] = cast(int)sum; 639 carry = sum >>> 32; 640 for (int i = len-2; i >= 0; i--) { 641 sum = (x[i] & LONG_MASK) + carry; 642 x[i] = cast(int)sum; 643 carry = sum >>> 32; 644 } 645 } 646 647 /** 648 * Translates the decimal string representation of a BigInteger into a 649 * BigInteger. The string representation consists of an optional minus 650 * sign followed by a sequence of one or more decimal digits. The 651 * character-to-digit mapping is provided by {@code CharacterHelper.digit}. 652 * The string may not contain any extraneous characters (whitespace, for 653 * example). 654 * 655 * @param val decimal string representation of BigInteger. 656 * @throws NumberFormatException {@code val} is not a valid representation 657 * of a BigInteger. 658 * @see Character#digit 659 */ 660 this(string val) { 661 this(val, 10); 662 } 663 664 /** 665 * Constructs a randomly generated BigInteger, uniformly distributed over 666 * the range 0 to (2<sup>{@code numBits}</sup> - 1), inclusive. 667 * The uniformity of the distribution assumes that a fair source of random 668 * bits is provided in {@code rnd}. Note that this constructor always 669 * constructs a non-negative BigInteger. 670 * 671 * @param numBits maximum bitLength of the new BigInteger. 672 * @param rnd source of randomness to be used in computing the new 673 * BigInteger. 674 * @throws IllegalArgumentException {@code numBits} is negative. 675 * @see #bitLength() 676 */ 677 this(int numBits, Random* rnd) { 678 this(1, randomBits(numBits, rnd)); 679 } 680 681 private static byte[] randomBits(int numBits, Random* rnd) { 682 if (numBits < 0) 683 throw new IllegalArgumentException("numBits must be non-negative"); 684 int numBytes = cast(int)((cast(long)numBits+7)/8); // avoid overflow 685 byte[] buffer = new byte[numBytes]; 686 687 // Generate random bytes and mask out any excess bits 688 if (numBytes > 0) { 689 for(int i=0; i<numBytes; i++) { 690 buffer[i] = uniform(byte.min, byte.max, rnd); 691 } 692 int excessBits = 8*numBytes - numBits; 693 buffer[0] &= (1 << (8-excessBits)) - 1; 694 } 695 return buffer; 696 } 697 698 /** 699 * Constructs a randomly generated positive BigInteger that is probably 700 * prime, with the specified bitLength. 701 * 702 * @apiNote It is recommended that the {@link #probablePrime probablePrime} 703 * method be used in preference to this constructor unless there 704 * is a compelling need to specify a certainty. 705 * 706 * @param bitLength bitLength of the returned BigInteger. 707 * @param certainty a measure of the uncertainty that the caller is 708 * willing to tolerate. The probability that the new BigInteger 709 * represents a prime number will exceed 710 * (1 - 1/2<sup>{@code certainty}</sup>). The execution time of 711 * this constructor is proportional to the value of this parameter. 712 * @param rnd source of random bits used to select candidates to be 713 * tested for primality. 714 * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large. 715 * @see #bitLength() 716 */ 717 this(int bitLength, int certainty, Random* rnd) { 718 BigInteger prime; 719 720 if (bitLength < 2) 721 throw new ArithmeticException("bitLength < 2"); 722 prime = (bitLength < SMALL_PRIME_THRESHOLD 723 ? smallPrime(bitLength, certainty, rnd) 724 : largePrime(bitLength, certainty, rnd)); 725 _signum = 1; 726 mag = prime.mag; 727 } 728 729 // Minimum size in bits that the requested prime number has 730 // before we use the large prime number generating algorithms. 731 // The cutoff of 95 was chosen empirically for best performance. 732 private enum int SMALL_PRIME_THRESHOLD = 95; 733 734 // Certainty required to meet the spec of probablePrime 735 private enum int DEFAULT_PRIME_CERTAINTY = 100; 736 737 /** 738 * Returns a positive BigInteger that is probably prime, with the 739 * specified bitLength. The probability that a BigInteger returned 740 * by this method is composite does not exceed 2<sup>-100</sup>. 741 * 742 * @param bitLength bitLength of the returned BigInteger. 743 * @param rnd source of random bits used to select candidates to be 744 * tested for primality. 745 * @return a BigInteger of {@code bitLength} bits that is probably prime 746 * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large. 747 * @see #bitLength() 748 * @since 1.4 749 */ 750 // static BigInteger probablePrime(int bitLength, Random* rnd) { 751 // if (bitLength < 2) 752 // throw new ArithmeticException("bitLength < 2"); 753 754 // return (bitLength < SMALL_PRIME_THRESHOLD ? 755 // smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) : 756 // largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd)); 757 // } 758 759 /** 760 * Find a random number of the specified bitLength that is probably prime. 761 * This method is used for smaller primes, its performance degrades on 762 * larger bitlengths. 763 * 764 * This method assumes bitLength > 1. 765 */ 766 private static BigInteger smallPrime(int bitLength, int certainty, Random* rnd) { 767 int magLen = (bitLength + 31) >>> 5; 768 int[] temp = new int[magLen]; 769 int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int 770 int highMask = (highBit << 1) - 1; // Bits to keep in high int 771 772 while (true) { 773 // Construct a candidate 774 for (int i=0; i < magLen; i++) 775 temp[i] = uniform(int.min, int.max, rnd); 776 temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length 777 if (bitLength > 2) 778 temp[magLen-1] |= 1; // Make odd if bitlen > 2 779 780 BigInteger p = new BigInteger(temp, 1); 781 782 // Do cheap "pre-test" if applicable 783 if (bitLength > 6) { 784 long r = p.remainder(SMALL_PRIME_PRODUCT).longValue(); 785 if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) || 786 (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) || 787 (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) 788 continue; // Candidate is composite; try another 789 } 790 791 // All candidates of bitLength 2 and 3 are prime by this point 792 if (bitLength < 4) 793 return p; 794 795 // Do expensive test if we survive pre-test (or it's inapplicable) 796 if (p.primeToCertainty(certainty, rnd)) 797 return p; 798 } 799 } 800 801 private __gshared BigInteger SMALL_PRIME_PRODUCT; 802 803 shared static this() { 804 SMALL_PRIME_PRODUCT = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41); 805 } 806 807 /** 808 * Find a random number of the specified bitLength that is probably prime. 809 * This method is more appropriate for larger bitlengths since it uses 810 * a sieve to eliminate most composites before using a more expensive 811 * test. 812 */ 813 private static BigInteger largePrime(int bitLength, int certainty, Random* rnd) { 814 BigInteger p; 815 p = new BigInteger(bitLength, rnd).setBit(bitLength-1); 816 p.mag[$-1] &= 0xfffffffe; 817 818 // Use a sieve length likely to contain the next prime number 819 int searchLen = getPrimeSearchLen(bitLength); 820 BitSieve searchSieve = new BitSieve(p, searchLen); 821 BigInteger candidate = searchSieve.retrieve(p, certainty, rnd); 822 823 while ((candidate is null) || (candidate.bitLength() != bitLength)) { 824 p = p.add(BigInteger.valueOf(2*searchLen)); 825 if (p.bitLength() != bitLength) 826 p = new BigInteger(bitLength, rnd).setBit(bitLength-1); 827 p.mag[$-1] &= 0xfffffffe; 828 searchSieve = new BitSieve(p, searchLen); 829 candidate = searchSieve.retrieve(p, certainty, rnd); 830 } 831 return candidate; 832 } 833 834 /** 835 * Returns the first integer greater than this {@code BigInteger} that 836 * is probably prime. The probability that the number returned by this 837 * method is composite does not exceed 2<sup>-100</sup>. This method will 838 * never skip over a prime when searching: if it returns {@code p}, there 839 * is no prime {@code q} such that {@code this < q < p}. 840 * 841 * @return the first integer greater than this {@code BigInteger} that 842 * is probably prime. 843 * @throws ArithmeticException {@code this < 0} or {@code this} is too large. 844 * @since 1.5 845 */ 846 BigInteger nextProbablePrime() { 847 if (this._signum < 0) 848 throw new ArithmeticException("start < 0: " ~ this.toString()); 849 850 // Handle trivial cases 851 if ((this._signum == 0) || this.equals(ONE)) 852 return TWO; 853 854 BigInteger result = this.add(ONE); 855 856 // Fastpath for small numbers 857 if (result.bitLength() < SMALL_PRIME_THRESHOLD) { 858 859 // Ensure an odd number 860 if (!result.testBit(0)) 861 result = result.add(ONE); 862 863 while (true) { 864 // Do cheap "pre-test" if applicable 865 if (result.bitLength() > 6) { 866 long r = result.remainder(SMALL_PRIME_PRODUCT).longValue(); 867 if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) || 868 (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) || 869 (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) { 870 result = result.add(TWO); 871 continue; // Candidate is composite; try another 872 } 873 } 874 875 // All candidates of bitLength 2 and 3 are prime by this point 876 if (result.bitLength() < 4) 877 return result; 878 879 // The expensive test 880 if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null)) 881 return result; 882 883 result = result.add(TWO); 884 } 885 } 886 887 // Start at previous even number 888 if (result.testBit(0)) 889 result = result.subtract(ONE); 890 891 // Looking for the next large prime 892 int searchLen = getPrimeSearchLen(result.bitLength()); 893 894 while (true) { 895 BitSieve searchSieve = new BitSieve(result, searchLen); 896 BigInteger candidate = searchSieve.retrieve(result, 897 DEFAULT_PRIME_CERTAINTY, null); 898 if (candidate !is null) 899 return candidate; 900 result = result.add(BigInteger.valueOf(2 * searchLen)); 901 } 902 } 903 904 private static int getPrimeSearchLen(int bitLength) { 905 if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) { 906 throw new ArithmeticException("Prime search implementation restriction on bitLength"); 907 } 908 return bitLength / 20 * 64; 909 } 910 911 /** 912 * Returns {@code true} if this BigInteger is probably prime, 913 * {@code false} if it's definitely composite. 914 * 915 * This method assumes bitLength > 2. 916 * 917 * @param certainty a measure of the uncertainty that the caller is 918 * willing to tolerate: if the call returns {@code true} 919 * the probability that this BigInteger is prime exceeds 920 * {@code (1 - 1/2<sup>certainty</sup>)}. The execution time of 921 * this method is proportional to the value of this parameter. 922 * @return {@code true} if this BigInteger is probably prime, 923 * {@code false} if it's definitely composite. 924 */ 925 bool primeToCertainty(int certainty, Random* random) { 926 int rounds = 0; 927 int n = (std.algorithm.min(certainty, int.max-1)+1)/2; 928 929 // The relationship between the certainty and the number of rounds 930 // we perform is given in the draft standard ANSI X9.80, "PRIME 931 // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES". 932 int sizeInBits = this.bitLength(); 933 if (sizeInBits < 100) { 934 rounds = 50; 935 rounds = n < rounds ? n : rounds; 936 return passesMillerRabin(rounds, random); 937 } 938 939 if (sizeInBits < 256) { 940 rounds = 27; 941 } else if (sizeInBits < 512) { 942 rounds = 15; 943 } else if (sizeInBits < 768) { 944 rounds = 8; 945 } else if (sizeInBits < 1024) { 946 rounds = 4; 947 } else { 948 rounds = 2; 949 } 950 rounds = n < rounds ? n : rounds; 951 952 return passesMillerRabin(rounds, random) && passesLucasLehmer(); 953 } 954 955 /** 956 * Returns true iff this BigInteger is a Lucas-Lehmer probable prime. 957 * 958 * The following assumptions are made: 959 * This BigInteger is a positive, odd number. 960 */ 961 private bool passesLucasLehmer() { 962 BigInteger thisPlusOne = this.add(ONE); 963 964 // Step 1 965 int d = 5; 966 while (jacobiSymbol(d, this) != -1) { 967 // 5, -7, 9, -11, ... 968 d = (d < 0) ? std.math.abs(d)+2 : -(d+2); 969 } 970 971 // Step 2 972 BigInteger u = lucasLehmerSequence(d, thisPlusOne, this); 973 974 // Step 3 975 return u.mod(this).equals(ZERO); 976 } 977 978 /** 979 * Computes Jacobi(p,n). 980 * Assumes n positive, odd, n>=3. 981 */ 982 private static int jacobiSymbol(int p, BigInteger n) { 983 if (p == 0) 984 return 0; 985 986 // Algorithm and comments adapted from Colin Plumb's C library. 987 int j = 1; 988 int u = n.mag[$-1]; 989 990 // Make p positive 991 if (p < 0) { 992 p = -p; 993 int n8 = u & 7; 994 if ((n8 == 3) || (n8 == 7)) 995 j = -j; // 3 (011) or 7 (111) mod 8 996 } 997 998 // Get rid of factors of 2 in p 999 while ((p & 3) == 0) 1000 p >>= 2; 1001 if ((p & 1) == 0) { 1002 p >>= 1; 1003 if (((u ^ (u>>1)) & 2) != 0) 1004 j = -j; // 3 (011) or 5 (101) mod 8 1005 } 1006 if (p == 1) 1007 return j; 1008 // Then, apply quadratic reciprocity 1009 if ((p & u & 2) != 0) // p = u = 3 (mod 4)? 1010 j = -j; 1011 // And reduce u mod p 1012 u = n.mod(BigInteger.valueOf(p)).intValue(); 1013 1014 // Now compute Jacobi(u,p), u < p 1015 while (u != 0) { 1016 while ((u & 3) == 0) 1017 u >>= 2; 1018 if ((u & 1) == 0) { 1019 u >>= 1; 1020 if (((p ^ (p>>1)) & 2) != 0) 1021 j = -j; // 3 (011) or 5 (101) mod 8 1022 } 1023 if (u == 1) 1024 return j; 1025 // Now both u and p are odd, so use quadratic reciprocity 1026 assert (u < p); 1027 int t = u; u = p; p = t; 1028 if ((u & p & 2) != 0) // u = p = 3 (mod 4)? 1029 j = -j; 1030 // Now u >= p, so it can be reduced 1031 u %= p; 1032 } 1033 return 0; 1034 } 1035 1036 private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) { 1037 BigInteger d = BigInteger.valueOf(z); 1038 BigInteger u = ONE; BigInteger u2; 1039 BigInteger v = ONE; BigInteger v2; 1040 1041 for (int i=k.bitLength()-2; i >= 0; i--) { 1042 u2 = u.multiply(v).mod(n); 1043 1044 v2 = v.square().add(d.multiply(u.square())).mod(n); 1045 if (v2.testBit(0)) 1046 v2 = v2.subtract(n); 1047 1048 v2 = v2.shiftRight(1); 1049 1050 u = u2; v = v2; 1051 if (k.testBit(i)) { 1052 u2 = u.add(v).mod(n); 1053 if (u2.testBit(0)) 1054 u2 = u2.subtract(n); 1055 1056 u2 = u2.shiftRight(1); 1057 v2 = v.add(d.multiply(u)).mod(n); 1058 if (v2.testBit(0)) 1059 v2 = v2.subtract(n); 1060 v2 = v2.shiftRight(1); 1061 1062 u = u2; v = v2; 1063 } 1064 } 1065 return u; 1066 } 1067 1068 /** 1069 * Returns true iff this BigInteger passes the specified number of 1070 * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS 1071 * 186-2). 1072 * 1073 * The following assumptions are made: 1074 * This BigInteger is a positive, odd number greater than 2. 1075 * iterations<=50. 1076 */ 1077 private bool passesMillerRabin(int iterations, Random* rnd) { 1078 // Find a and m such that m is odd and this == 1 + 2**a * m 1079 BigInteger thisMinusOne = this.subtract(ONE); 1080 BigInteger m = thisMinusOne; 1081 int a = m.getLowestSetBit(); 1082 m = m.shiftRight(a); 1083 1084 // Do the tests 1085 // if (rnd is null) { 1086 // rnd = ThreadLocalRandom.current(); 1087 // } 1088 for (int i=0; i < iterations; i++) { 1089 // Generate a uniform random on (1, this) 1090 BigInteger b; 1091 do { 1092 b = new BigInteger(this.bitLength(), rnd); 1093 } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0); 1094 1095 int j = 0; 1096 BigInteger z = b.modPow(m, this); 1097 while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) { 1098 if (j > 0 && z.equals(ONE) || ++j == a) 1099 return false; 1100 z = z.modPow(TWO, this); 1101 } 1102 } 1103 return true; 1104 } 1105 1106 /** 1107 * This internal constructor differs from its cousin 1108 * with the arguments reversed in two ways: it assumes that its 1109 * arguments are correct, and it doesn't copy the magnitude array. 1110 */ 1111 this(int[] magnitude, int signum) { 1112 this._signum = (magnitude.length == 0 ? 0 : signum); 1113 this.mag = magnitude; 1114 if (mag.length >= MAX_MAG_LENGTH) { 1115 checkRange(); 1116 } 1117 } 1118 1119 /** 1120 * This private constructor is for internal use and assumes that its 1121 * arguments are correct. The {@code magnitude} array is assumed to be 1122 * unchanged for the duration of the constructor call. 1123 */ 1124 private this(byte[] magnitude, int signum) { 1125 this._signum = (magnitude.length == 0 ? 0 : signum); 1126 this.mag = stripLeadingZeroBytes(magnitude, 0, cast(int)magnitude.length); 1127 if (mag.length >= MAX_MAG_LENGTH) { 1128 checkRange(); 1129 } 1130 } 1131 1132 /** 1133 * Throws an {@code ArithmeticException} if the {@code BigInteger} would be 1134 * out of the supported range. 1135 * 1136 * @throws ArithmeticException if {@code this} exceeds the supported range. 1137 */ 1138 private void checkRange() { 1139 if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) { 1140 reportOverflow(); 1141 } 1142 } 1143 1144 private static void reportOverflow() { 1145 throw new ArithmeticException("BigInteger would overflow supported range"); 1146 } 1147 1148 //Static Factory Methods 1149 1150 /** 1151 * Returns a BigInteger whose value is equal to that of the 1152 * specified {@code long}. 1153 * 1154 * @apiNote This static factory method is provided in preference 1155 * to a ({@code long}) constructor because it allows for reuse of 1156 * frequently used BigIntegers. 1157 * 1158 * @param val value of the BigInteger to return. 1159 * @return a BigInteger with the specified value. 1160 */ 1161 static BigInteger valueOf(long val) { 1162 // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant 1163 if (val == 0) 1164 return ZERO; 1165 if (val > 0 && val <= MAX_CONSTANT) 1166 return posConst[cast(int) val]; 1167 else if (val < 0 && val >= -MAX_CONSTANT) 1168 return negConst[cast(int) -val]; 1169 1170 return new BigInteger(val); 1171 } 1172 1173 /** 1174 * Constructs a BigInteger with the specified value, which may not be zero. 1175 */ 1176 private this(long val) { 1177 if (val < 0) { 1178 val = -val; 1179 _signum = -1; 1180 } else { 1181 _signum = 1; 1182 } 1183 1184 int highWord = cast(int)(val >>> 32); 1185 if (highWord == 0) { 1186 mag = new int[1]; 1187 mag[0] = cast(int)val; 1188 } else { 1189 mag = new int[2]; 1190 mag[0] = highWord; 1191 mag[1] = cast(int)val; 1192 } 1193 } 1194 1195 /** 1196 * Returns a BigInteger with the given two's complement representation. 1197 * Assumes that the input array will not be modified (the returned 1198 * BigInteger will reference the input array if feasible). 1199 */ 1200 private static BigInteger valueOf(int[] val) { 1201 return (val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val)); 1202 } 1203 1204 // Constants 1205 1206 /** 1207 * Initialize static constant array when class is loaded. 1208 */ 1209 private enum int MAX_CONSTANT = 16; 1210 private __gshared BigInteger[] posConst; 1211 private __gshared BigInteger[] negConst; 1212 1213 /** 1214 * The cache of powers of each radix. This allows us to not have to 1215 * recalculate powers of radix^(2^n) more than once. This speeds 1216 * Schoenhage recursive base conversion significantly. 1217 */ 1218 private __gshared BigInteger[][] powerCache; 1219 1220 /** The cache of logarithms of radices for base conversion. */ 1221 private __gshared double[] logCache; 1222 1223 /** The natural log of 2. This is used in computing cache indices. */ 1224 private __gshared immutable double LOG_TWO; 1225 1226 shared static this() { 1227 LOG_TWO = std.math.log(2.0); 1228 posConst = new BigInteger[MAX_CONSTANT+1]; 1229 negConst = new BigInteger[MAX_CONSTANT+1]; 1230 1231 for (int i = 1; i <= MAX_CONSTANT; i++) { 1232 int[] magnitude = [i]; 1233 posConst[i] = new BigInteger(magnitude, 1); 1234 negConst[i] = new BigInteger(magnitude, -1); 1235 } 1236 1237 /* 1238 * Initialize the cache of radix^(2^x) values used for base conversion 1239 * with just the very first value. Additional values will be created 1240 * on demand. 1241 */ 1242 powerCache = new BigInteger[][Char.MAX_RADIX+1]; 1243 logCache = new double[Char.MAX_RADIX+1]; 1244 1245 for (int i=Char.MIN_RADIX; i <= Char.MAX_RADIX; i++) { 1246 powerCache[i] = [BigInteger.valueOf(i)]; 1247 logCache[i] = std.math.log(i); 1248 } 1249 } 1250 1251 /** 1252 * The BigInteger constant zero. 1253 * 1254 * @since 1.2 1255 */ 1256 __gshared static BigInteger ZERO; 1257 1258 /** 1259 * The BigInteger constant one. 1260 * 1261 * @since 1.2 1262 */ 1263 __gshared static BigInteger ONE; 1264 1265 /** 1266 * The BigInteger constant two. 1267 * 1268 * @since 9 1269 */ 1270 __gshared static BigInteger TWO; 1271 1272 /** 1273 * The BigInteger constant -1. (Not exported.) 1274 */ 1275 private __gshared static BigInteger NEGATIVE_ONE; 1276 1277 /** 1278 * The BigInteger constant ten. 1279 * 1280 * @since 1.5 1281 */ 1282 __gshared static BigInteger TEN; 1283 1284 shared static this() { 1285 ZERO = new BigInteger(cast(byte[])[], 0); 1286 ONE = valueOf(1); 1287 TWO = valueOf(2); 1288 NEGATIVE_ONE = valueOf(-1); 1289 TEN = valueOf(10); 1290 } 1291 1292 // Arithmetic Operations 1293 1294 /** 1295 * Returns a BigInteger whose value is {@code (this + val)}. 1296 * 1297 * @param val value to be added to this BigInteger. 1298 * @return {@code this + val} 1299 */ 1300 BigInteger add(BigInteger val) { 1301 if (val._signum == 0) 1302 return this; 1303 if (_signum == 0) 1304 return val; 1305 if (val._signum == signum) 1306 return new BigInteger(add(mag, val.mag), signum); 1307 1308 int cmp = compareMagnitude(val); 1309 if (cmp == 0) 1310 return ZERO; 1311 int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) 1312 : subtract(val.mag, mag)); 1313 resultMag = trustedStripLeadingZeroInts(resultMag); 1314 1315 return new BigInteger(resultMag, cmp == signum ? 1 : -1); 1316 } 1317 1318 /** 1319 * Package private methods used by BigDecimal code to add a BigInteger 1320 * with a long. Assumes val is not equal to INFLATED. 1321 */ 1322 BigInteger add(long val) { 1323 if (val == 0) 1324 return this; 1325 if (_signum == 0) 1326 return valueOf(val); 1327 if (Long.signum(val) == signum) 1328 return new BigInteger(add(mag, std.math.abs(val)), signum); 1329 int cmp = compareMagnitude(val); 1330 if (cmp == 0) 1331 return ZERO; 1332 int[] resultMag = (cmp > 0 ? subtract(mag, std.math.abs(val)) : subtract(std.math.abs(val), mag)); 1333 resultMag = trustedStripLeadingZeroInts(resultMag); 1334 return new BigInteger(resultMag, cmp == signum ? 1 : -1); 1335 } 1336 1337 /** 1338 * Adds the contents of the int array x and long value val. This 1339 * method allocates a new int array to hold the answer and returns 1340 * a reference to that array. Assumes x.length > 0 and val is 1341 * non-negative 1342 */ 1343 private static int[] add(int[] x, long val) { 1344 int[] y; 1345 long sum = 0; 1346 int xIndex = cast(int)x.length; 1347 int[] result; 1348 int highWord = cast(int)(val >>> 32); 1349 if (highWord == 0) { 1350 result = new int[xIndex]; 1351 sum = (x[--xIndex] & LONG_MASK) + val; 1352 result[xIndex] = cast(int)sum; 1353 } else { 1354 if (xIndex == 1) { 1355 result = new int[2]; 1356 sum = val + (x[0] & LONG_MASK); 1357 result[1] = cast(int)sum; 1358 result[0] = cast(int)(sum >>> 32); 1359 return result; 1360 } else { 1361 result = new int[xIndex]; 1362 sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK); 1363 result[xIndex] = cast(int)sum; 1364 sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32); 1365 result[xIndex] = cast(int)sum; 1366 } 1367 } 1368 // Copy remainder of longer number while carry propagation is required 1369 bool carry = (sum >>> 32 != 0); 1370 while (xIndex > 0 && carry) 1371 carry = ((result[--xIndex] = x[xIndex] + 1) == 0); 1372 // Copy remainder of longer number 1373 while (xIndex > 0) 1374 result[--xIndex] = x[xIndex]; 1375 // Grow result if necessary 1376 if (carry) { 1377 size_t len = cast(int)result.length; 1378 int[] bigger = new int[len + 1]; 1379 // System.arraycopy(result, 0, bigger, 1, result.length); 1380 bigger[1 .. len+1] = result[0..$]; 1381 bigger[0] = 0x01; 1382 return bigger; 1383 } 1384 return result; 1385 } 1386 1387 /** 1388 * Adds the contents of the int arrays x and y. This method allocates 1389 * a new int array to hold the answer and returns a reference to that 1390 * array. 1391 */ 1392 private static int[] add(int[] x, int[] y) { 1393 // If x is shorter, swap the two arrays 1394 if (x.length < y.length) { 1395 int[] tmp = x; 1396 x = y; 1397 y = tmp; 1398 } 1399 1400 int xIndex = cast(int)x.length; 1401 int yIndex = cast(int)y.length; 1402 int[] result = new int[xIndex]; 1403 long sum = 0; 1404 if (yIndex == 1) { 1405 sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ; 1406 result[xIndex] = cast(int)sum; 1407 } else { 1408 // Add common parts of both numbers 1409 while (yIndex > 0) { 1410 sum = (x[--xIndex] & LONG_MASK) + 1411 (y[--yIndex] & LONG_MASK) + (sum >>> 32); 1412 result[xIndex] = cast(int)sum; 1413 } 1414 } 1415 // Copy remainder of longer number while carry propagation is required 1416 bool carry = (sum >>> 32 != 0); 1417 while (xIndex > 0 && carry) 1418 carry = ((result[--xIndex] = x[xIndex] + 1) == 0); 1419 1420 // Copy remainder of longer number 1421 while (xIndex > 0) 1422 result[--xIndex] = x[xIndex]; 1423 1424 // Grow result if necessary 1425 if (carry) { 1426 size_t len = cast(int)result.length; 1427 int[] bigger = new int[len + 1]; 1428 // System.arraycopy(result, 0, bigger, 1, result.length); 1429 bigger[1 .. 1+len] = result[0 .. $]; 1430 bigger[0] = 0x01; 1431 return bigger; 1432 } 1433 return result; 1434 } 1435 1436 private static int[] subtract(long val, int[] little) { 1437 int highWord = cast(int)(val >>> 32); 1438 if (highWord == 0) { 1439 int[] result = new int[1]; 1440 result[0] = cast(int)(val - (little[0] & LONG_MASK)); 1441 return result; 1442 } else { 1443 int[] result = new int[2]; 1444 if (little.length == 1) { 1445 long difference = (cast(int)val & LONG_MASK) - (little[0] & LONG_MASK); 1446 result[1] = cast(int)difference; 1447 // Subtract remainder of longer number while borrow propagates 1448 bool borrow = (difference >> 32 != 0); 1449 if (borrow) { 1450 result[0] = highWord - 1; 1451 } else { // Copy remainder of longer number 1452 result[0] = highWord; 1453 } 1454 return result; 1455 } else { // little.length == 2 1456 long difference = (cast(int)val & LONG_MASK) - (little[1] & LONG_MASK); 1457 result[1] = cast(int)difference; 1458 difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32); 1459 result[0] = cast(int)difference; 1460 return result; 1461 } 1462 } 1463 } 1464 1465 /** 1466 * Subtracts the contents of the second argument (val) from the 1467 * first (big). The first int array (big) must represent a larger number 1468 * than the second. This method allocates the space necessary to hold the 1469 * answer. 1470 * assumes val >= 0 1471 */ 1472 private static int[] subtract(int[] big, long val) { 1473 int highWord = cast(int)(val >>> 32); 1474 int bigIndex = cast(int)big.length; 1475 int[] result = new int[bigIndex]; 1476 long difference = 0; 1477 1478 if (highWord == 0) { 1479 difference = (big[--bigIndex] & LONG_MASK) - val; 1480 result[bigIndex] = cast(int)difference; 1481 } else { 1482 difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK); 1483 result[bigIndex] = cast(int)difference; 1484 difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32); 1485 result[bigIndex] = cast(int)difference; 1486 } 1487 1488 // Subtract remainder of longer number while borrow propagates 1489 bool borrow = (difference >> 32 != 0); 1490 while (bigIndex > 0 && borrow) 1491 borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1); 1492 1493 // Copy remainder of longer number 1494 while (bigIndex > 0) 1495 result[--bigIndex] = big[bigIndex]; 1496 1497 return result; 1498 } 1499 1500 /** 1501 * Returns a BigInteger whose value is {@code (this - val)}. 1502 * 1503 * @param val value to be subtracted from this BigInteger. 1504 * @return {@code this - val} 1505 */ 1506 BigInteger subtract(BigInteger val) { 1507 if (val._signum == 0) 1508 return this; 1509 if (_signum == 0) 1510 return val.negate(); 1511 if (val.signum != signum) 1512 return new BigInteger(add(mag, val.mag), signum); 1513 1514 int cmp = compareMagnitude(val); 1515 if (cmp == 0) 1516 return ZERO; 1517 int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) 1518 : subtract(val.mag, mag)); 1519 resultMag = trustedStripLeadingZeroInts(resultMag); 1520 return new BigInteger(resultMag, cmp == signum ? 1 : -1); 1521 } 1522 1523 /** 1524 * Subtracts the contents of the second int arrays (little) from the 1525 * first (big). The first int array (big) must represent a larger number 1526 * than the second. This method allocates the space necessary to hold the 1527 * answer. 1528 */ 1529 private static int[] subtract(int[] big, int[] little) { 1530 int bigIndex = cast(int)big.length; 1531 int[] result = new int[bigIndex]; 1532 int littleIndex = cast(int)little.length; 1533 long difference = 0; 1534 1535 // Subtract common parts of both numbers 1536 while (littleIndex > 0) { 1537 difference = (big[--bigIndex] & LONG_MASK) - 1538 (little[--littleIndex] & LONG_MASK) + 1539 (difference >> 32); 1540 result[bigIndex] = cast(int)difference; 1541 } 1542 1543 // Subtract remainder of longer number while borrow propagates 1544 bool borrow = (difference >> 32 != 0); 1545 while (bigIndex > 0 && borrow) 1546 borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1); 1547 1548 // Copy remainder of longer number 1549 while (bigIndex > 0) 1550 result[--bigIndex] = big[bigIndex]; 1551 1552 return result; 1553 } 1554 1555 /** 1556 * Returns a BigInteger whose value is {@code (this * val)}. 1557 * 1558 * @implNote An implementation may offer better algorithmic 1559 * performance when {@code val == this}. 1560 * 1561 * @param val value to be multiplied by this BigInteger. 1562 * @return {@code this * val} 1563 */ 1564 BigInteger multiply(BigInteger val) { 1565 if (val._signum == 0 || _signum == 0) 1566 return ZERO; 1567 1568 int xlen = cast(int)mag.length; 1569 1570 if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD) { 1571 return square(); 1572 } 1573 1574 int ylen = cast(int)val.mag.length; 1575 1576 if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD)) { 1577 int resultSign = _signum == val.signum ? 1 : -1; 1578 if (val.mag.length == 1) { 1579 return multiplyByInt(mag,val.mag[0], resultSign); 1580 } 1581 if (mag.length == 1) { 1582 return multiplyByInt(val.mag,mag[0], resultSign); 1583 } 1584 int[] result = multiplyToLen(mag, xlen, 1585 val.mag, ylen, null); 1586 result = trustedStripLeadingZeroInts(result); 1587 return new BigInteger(result, resultSign); 1588 } else { 1589 if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) { 1590 return multiplyKaratsuba(this, val); 1591 } else { 1592 return multiplyToomCook3(this, val); 1593 } 1594 } 1595 } 1596 1597 private static BigInteger multiplyByInt(int[] x, int y, int sign) { 1598 if (Integer.bitCount(y) == 1) { 1599 return new BigInteger(shiftLeft(x, Integer.numberOfTrailingZeros(y)), sign); 1600 } 1601 int xlen = cast(int)x.length; 1602 int[] rmag = new int[xlen + 1]; 1603 long carry = 0; 1604 long yl = y & LONG_MASK; 1605 int rstart = cast(int)rmag.length - 1; 1606 for (int i = xlen - 1; i >= 0; i--) { 1607 long product = (x[i] & LONG_MASK) * yl + carry; 1608 rmag[rstart--] = cast(int)product; 1609 carry = product >>> 32; 1610 } 1611 if (carry == 0L) { 1612 rmag = rmag[1 .. $]; // java.util.Arrays.copyOfRange(rmag, 1, rmag.length); 1613 } else { 1614 rmag[rstart] = cast(int)carry; 1615 } 1616 return new BigInteger(rmag, sign); 1617 } 1618 1619 /** 1620 * Package private methods used by BigDecimal code to multiply a BigInteger 1621 * with a long. Assumes v is not equal to INFLATED. 1622 */ 1623 BigInteger multiply(long v) { 1624 if (v == 0 || _signum == 0) 1625 return ZERO; 1626 if (v == long.min) 1627 return multiply(BigInteger.valueOf(v)); 1628 int rsign = (v > 0 ? signum : -signum); 1629 if (v < 0) 1630 v = -v; 1631 long dh = v >>> 32; // higher order bits 1632 long dl = v & LONG_MASK; // lower order bits 1633 1634 int xlen = cast(int)mag.length; 1635 int[] value = mag; 1636 int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]); 1637 long carry = 0; 1638 int rstart = cast(int)rmag.length - 1; 1639 for (int i = xlen - 1; i >= 0; i--) { 1640 long product = (value[i] & LONG_MASK) * dl + carry; 1641 rmag[rstart--] = cast(int)product; 1642 carry = product >>> 32; 1643 } 1644 rmag[rstart] = cast(int)carry; 1645 if (dh != 0L) { 1646 carry = 0; 1647 rstart = cast(int)rmag.length - 2; 1648 for (int i = xlen - 1; i >= 0; i--) { 1649 long product = (value[i] & LONG_MASK) * dh + 1650 (rmag[rstart] & LONG_MASK) + carry; 1651 rmag[rstart--] = cast(int)product; 1652 carry = product >>> 32; 1653 } 1654 rmag[0] = cast(int)carry; 1655 } 1656 if (carry == 0L) 1657 rmag = rmag[1 .. $]; //java.util.Arrays.copyOfRange(rmag, 1, rmag.length); 1658 return new BigInteger(rmag, rsign); 1659 } 1660 1661 /** 1662 * Multiplies int arrays x and y to the specified lengths and places 1663 * the result into z. There will be no leading zeros in the resultant array. 1664 */ 1665 private static int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) { 1666 multiplyToLenCheck(x, xlen); 1667 multiplyToLenCheck(y, ylen); 1668 return implMultiplyToLen(x, xlen, y, ylen, z); 1669 } 1670 1671 1672 private static int[] implMultiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) { 1673 int xstart = xlen - 1; 1674 int ystart = ylen - 1; 1675 1676 if (z is null || z.length < (xlen+ ylen)) 1677 z = new int[xlen+ylen]; 1678 1679 long carry = 0; 1680 for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) { 1681 long product = (y[j] & LONG_MASK) * 1682 (x[xstart] & LONG_MASK) + carry; 1683 z[k] = cast(int)product; 1684 carry = product >>> 32; 1685 } 1686 z[xstart] = cast(int)carry; 1687 1688 for (int i = xstart-1; i >= 0; i--) { 1689 carry = 0; 1690 for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) { 1691 long product = (y[j] & LONG_MASK) * 1692 (x[i] & LONG_MASK) + 1693 (z[k] & LONG_MASK) + carry; 1694 z[k] = cast(int)product; 1695 carry = product >>> 32; 1696 } 1697 z[i] = cast(int)carry; 1698 } 1699 return z; 1700 } 1701 1702 private static void multiplyToLenCheck(int[] array, int length) { 1703 if (length <= 0) { 1704 return; // not an error because multiplyToLen won't execute if len <= 0 1705 } 1706 1707 assert(array !is null); 1708 1709 if (length > array.length) { 1710 throw new ArrayIndexOutOfBoundsException(length - 1); 1711 } 1712 } 1713 1714 /** 1715 * Multiplies two BigIntegers using the Karatsuba multiplication 1716 * algorithm. This is a recursive divide-and-conquer algorithm which is 1717 * more efficient for large numbers than what is commonly called the 1718 * "grade-school" algorithm used in multiplyToLen. If the numbers to be 1719 * multiplied have length n, the "grade-school" algorithm has an 1720 * asymptotic complexity of O(n^2). In contrast, the Karatsuba algorithm 1721 * has complexity of O(n^(log2(3))), or O(n^1.585). It achieves this 1722 * increased performance by doing 3 multiplies instead of 4 when 1723 * evaluating the product. As it has some overhead, should be used when 1724 * both numbers are larger than a certain threshold (found 1725 * experimentally). 1726 * 1727 * See: http://en.wikipedia.org/wiki/Karatsuba_algorithm 1728 */ 1729 private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) { 1730 int xlen = cast(int)x.mag.length; 1731 int ylen = cast(int)y.mag.length; 1732 1733 // The number of ints in each half of the number. 1734 int half = (std.algorithm.max(xlen, ylen)+1) / 2; 1735 1736 // xl and yl are the lower halves of x and y respectively, 1737 // xh and yh are the upper halves. 1738 BigInteger xl = x.getLower(half); 1739 BigInteger xh = x.getUpper(half); 1740 BigInteger yl = y.getLower(half); 1741 BigInteger yh = y.getUpper(half); 1742 1743 BigInteger p1 = xh.multiply(yh); // p1 = xh*yh 1744 BigInteger p2 = xl.multiply(yl); // p2 = xl*yl 1745 1746 // p3=(xh+xl)*(yh+yl) 1747 BigInteger p3 = xh.add(xl).multiply(yh.add(yl)); 1748 1749 // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2 1750 BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2); 1751 1752 if (x.signum != y.signum) { 1753 return result.negate(); 1754 } else { 1755 return result; 1756 } 1757 } 1758 1759 /** 1760 * Multiplies two BigIntegers using a 3-way Toom-Cook multiplication 1761 * algorithm. This is a recursive divide-and-conquer algorithm which is 1762 * more efficient for large numbers than what is commonly called the 1763 * "grade-school" algorithm used in multiplyToLen. If the numbers to be 1764 * multiplied have length n, the "grade-school" algorithm has an 1765 * asymptotic complexity of O(n^2). In contrast, 3-way Toom-Cook has a 1766 * complexity of about O(n^1.465). It achieves this increased asymptotic 1767 * performance by breaking each number into three parts and by doing 5 1768 * multiplies instead of 9 when evaluating the product. Due to overhead 1769 * (additions, shifts, and one division) in the Toom-Cook algorithm, it 1770 * should only be used when both numbers are larger than a certain 1771 * threshold (found experimentally). This threshold is generally larger 1772 * than that for Karatsuba multiplication, so this algorithm is generally 1773 * only used when numbers become significantly larger. 1774 * 1775 * The algorithm used is the "optimal" 3-way Toom-Cook algorithm outlined 1776 * by Marco Bodrato. 1777 * 1778 * See: http://bodrato.it/toom-cook/ 1779 * http://bodrato.it/papers/#WAIFI2007 1780 * 1781 * "Towards Optimal Toom-Cook Multiplication for Univariate and 1782 * Multivariate Polynomials in Characteristic 2 and 0." by Marco BODRATO; 1783 * In C.Carlet and B.Sunar, Eds., "WAIFI'07 proceedings", p. 116-133, 1784 * LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007. 1785 * 1786 */ 1787 private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) { 1788 int alen = cast(int)a.mag.length; 1789 int blen = cast(int)b.mag.length; 1790 1791 int largest = std.algorithm.max(alen, blen); 1792 1793 // k is the size (in ints) of the lower-order slices. 1794 int k = (largest+2)/3; // Equal to ceil(largest/3) 1795 1796 // r is the size (in ints) of the highest-order slice. 1797 int r = largest - 2*k; 1798 1799 // Obtain slices of the numbers. a2 and b2 are the most significant 1800 // bits of the numbers a and b, and a0 and b0 the least significant. 1801 BigInteger a0, a1, a2, b0, b1, b2; 1802 a2 = a.getToomSlice(k, r, 0, largest); 1803 a1 = a.getToomSlice(k, r, 1, largest); 1804 a0 = a.getToomSlice(k, r, 2, largest); 1805 b2 = b.getToomSlice(k, r, 0, largest); 1806 b1 = b.getToomSlice(k, r, 1, largest); 1807 b0 = b.getToomSlice(k, r, 2, largest); 1808 1809 BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1; 1810 1811 v0 = a0.multiply(b0); 1812 da1 = a2.add(a0); 1813 db1 = b2.add(b0); 1814 vm1 = da1.subtract(a1).multiply(db1.subtract(b1)); 1815 da1 = da1.add(a1); 1816 db1 = db1.add(b1); 1817 v1 = da1.multiply(db1); 1818 v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply( 1819 db1.add(b2).shiftLeft(1).subtract(b0)); 1820 vinf = a2.multiply(b2); 1821 1822 // The algorithm requires two divisions by 2 and one by 3. 1823 // All divisions are known to be exact, that is, they do not produce 1824 // remainders, and all results are positive. The divisions by 2 are 1825 // implemented as right shifts which are relatively efficient, leaving 1826 // only an exact division by 3, which is done by a specialized 1827 // linear-time algorithm. 1828 t2 = v2.subtract(vm1).exactDivideBy3(); 1829 tm1 = v1.subtract(vm1).shiftRight(1); 1830 t1 = v1.subtract(v0); 1831 t2 = t2.subtract(t1).shiftRight(1); 1832 t1 = t1.subtract(tm1).subtract(vinf); 1833 t2 = t2.subtract(vinf.shiftLeft(1)); 1834 tm1 = tm1.subtract(t2); 1835 1836 // Number of bits to shift left. 1837 int ss = k*32; 1838 1839 BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0); 1840 1841 if (a.signum != b.signum) { 1842 return result.negate(); 1843 } else { 1844 return result; 1845 } 1846 } 1847 1848 1849 /** 1850 * Returns a slice of a BigInteger for use in Toom-Cook multiplication. 1851 * 1852 * @param lowerSize The size of the lower-order bit slices. 1853 * @param upperSize The size of the higher-order bit slices. 1854 * @param slice The index of which slice is requested, which must be a 1855 * number from 0 to size-1. Slice 0 is the highest-order bits, and slice 1856 * size-1 are the lowest-order bits. Slice 0 may be of different size than 1857 * the other slices. 1858 * @param fullsize The size of the larger integer array, used to align 1859 * slices to the appropriate position when multiplying different-sized 1860 * numbers. 1861 */ 1862 private BigInteger getToomSlice(int lowerSize, int upperSize, int slice, 1863 int fullsize) { 1864 int start, end, sliceSize, len, offset; 1865 1866 len = cast(int)mag.length; 1867 offset = fullsize - len; 1868 1869 if (slice == 0) { 1870 start = 0 - offset; 1871 end = upperSize - 1 - offset; 1872 } else { 1873 start = upperSize + (slice-1)*lowerSize - offset; 1874 end = start + lowerSize - 1; 1875 } 1876 1877 if (start < 0) { 1878 start = 0; 1879 } 1880 if (end < 0) { 1881 return ZERO; 1882 } 1883 1884 sliceSize = (end-start) + 1; 1885 1886 if (sliceSize <= 0) { 1887 return ZERO; 1888 } 1889 1890 // While performing Toom-Cook, all slices are positive and 1891 // the sign is adjusted when the final number is composed. 1892 if (start == 0 && sliceSize >= len) { 1893 return this.abs(); 1894 } 1895 1896 int[] intSlice = mag[start .. start + sliceSize]; 1897 // int[] intSlice = new int[sliceSize]; 1898 //System.arraycopy(mag, start, intSlice, 0, sliceSize); 1899 1900 return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1); 1901 } 1902 1903 /** 1904 * Does an exact division (that is, the remainder is known to be zero) 1905 * of the specified number by 3. This is used in Toom-Cook 1906 * multiplication. This is an efficient algorithm that runs in linear 1907 * time. If the argument is not exactly divisible by 3, results are 1908 * undefined. Note that this is expected to be called with positive 1909 * arguments only. 1910 */ 1911 private BigInteger exactDivideBy3() { 1912 int len = cast(int)mag.length; 1913 int[] result = new int[len]; 1914 long x, w, q, borrow; 1915 borrow = 0L; 1916 for (int i=len-1; i >= 0; i--) { 1917 x = (mag[i] & LONG_MASK); 1918 w = x - borrow; 1919 if (borrow > x) { // Did we make the number go negative? 1920 borrow = 1L; 1921 } else { 1922 borrow = 0L; 1923 } 1924 1925 // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32). Thus, 1926 // the effect of this is to divide by 3 (mod 2^32). 1927 // This is much faster than division on most architectures. 1928 q = (w * 0xAAAAAAABL) & LONG_MASK; 1929 result[i] = cast(int) q; 1930 1931 // Now check the borrow. The second check can of course be 1932 // eliminated if the first fails. 1933 if (q >= 0x55555556L) { 1934 borrow++; 1935 if (q >= 0xAAAAAAABL) 1936 borrow++; 1937 } 1938 } 1939 result = trustedStripLeadingZeroInts(result); 1940 return new BigInteger(result, signum); 1941 } 1942 1943 /** 1944 * Returns a new BigInteger representing n lower ints of the number. 1945 * This is used by Karatsuba multiplication and Karatsuba squaring. 1946 */ 1947 private BigInteger getLower(int n) { 1948 int len = cast(int)mag.length; 1949 1950 if (len <= n) { 1951 return abs(); 1952 } 1953 1954 int[] lowerInts = mag[len-n .. len]; 1955 // int[] lowerInts = new int[n]; 1956 // System.arraycopy(mag, len-n, lowerInts, 0, n); 1957 1958 return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1); 1959 } 1960 1961 /** 1962 * Returns a new BigInteger representing mag.length-n upper 1963 * ints of the number. This is used by Karatsuba multiplication and 1964 * Karatsuba squaring. 1965 */ 1966 private BigInteger getUpper(int n) { 1967 int len = cast(int)mag.length; 1968 1969 if (len <= n) { 1970 return ZERO; 1971 } 1972 1973 int upperLen = len - n; 1974 int[] upperInts = mag[0 .. upperLen]; 1975 // int[] upperInts = new int[upperLen]; 1976 // System.arraycopy(mag, 0, upperInts, 0, upperLen); 1977 1978 return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1); 1979 } 1980 1981 // Squaring 1982 1983 /** 1984 * Returns a BigInteger whose value is {@code (this<sup>2</sup>)}. 1985 * 1986 * @return {@code this<sup>2</sup>} 1987 */ 1988 private BigInteger square() { 1989 if (_signum == 0) { 1990 return ZERO; 1991 } 1992 int len = cast(int)mag.length; 1993 1994 if (len < KARATSUBA_SQUARE_THRESHOLD) { 1995 int[] z = squareToLen(mag, len, null); 1996 return new BigInteger(trustedStripLeadingZeroInts(z), 1); 1997 } else { 1998 if (len < TOOM_COOK_SQUARE_THRESHOLD) { 1999 return squareKaratsuba(); 2000 } else { 2001 return squareToomCook3(); 2002 } 2003 } 2004 } 2005 2006 /** 2007 * Squares the contents of the int array x. The result is placed into the 2008 * int array z. The contents of x are not changed. 2009 */ 2010 private static int[] squareToLen(int[] x, int len, int[] z) { 2011 int zlen = len << 1; 2012 if (z is null || z.length < zlen) 2013 z = new int[zlen]; 2014 2015 // Execute checks before calling intrinsified method. 2016 implSquareToLenChecks(x, len, z, zlen); 2017 return implSquareToLen(x, len, z, zlen); 2018 } 2019 2020 /** 2021 * Parameters validation. 2022 */ 2023 private static void implSquareToLenChecks(int[] x, int len, int[] z, int zlen) { 2024 if (len < 1) { 2025 throw new IllegalArgumentException("invalid input length: " ~ len.to!string().to!string()); 2026 } 2027 if (len > x.length) { 2028 throw new IllegalArgumentException("input length out of bound: " ~ 2029 len.to!string() ~ " > " ~ x.length.to!string()); 2030 } 2031 if (len * 2 > z.length) { 2032 throw new IllegalArgumentException("input length out of bound: " ~ 2033 (len * 2).to!string() ~ " > " ~ z.length.to!string()); 2034 } 2035 if (zlen < 1) { 2036 throw new IllegalArgumentException("invalid input length: " ~ zlen.to!string()); 2037 } 2038 if (zlen > z.length) { 2039 throw new IllegalArgumentException("input length out of bound: " ~ 2040 len.to!string() ~ " > " ~ z.length.to!string()); 2041 } 2042 } 2043 2044 /** 2045 * Java Runtime may use intrinsic for this method. 2046 */ 2047 2048 private static final int[] implSquareToLen(int[] x, int len, int[] z, int zlen) { 2049 /* 2050 * The algorithm used here is adapted from Colin Plumb's C library. 2051 * Technique: Consider the partial products in the multiplication 2052 * of "abcde" by itself: 2053 * 2054 * a b c d e 2055 * * a b c d e 2056 * ================== 2057 * ae be ce de ee 2058 * ad bd cd dd de 2059 * ac bc cc cd ce 2060 * ab bb bc bd be 2061 * aa ab ac ad ae 2062 * 2063 * Note that everything above the main diagonal: 2064 * ae be ce de = (abcd) * e 2065 * ad bd cd = (abc) * d 2066 * ac bc = (ab) * c 2067 * ab = (a) * b 2068 * 2069 * is a copy of everything below the main diagonal: 2070 * de 2071 * cd ce 2072 * bc bd be 2073 * ab ac ad ae 2074 * 2075 * Thus, the sum is 2 * (off the diagonal) + diagonal. 2076 * 2077 * This is accumulated beginning with the diagonal (which 2078 * consist of the squares of the digits of the input), which is then 2079 * divided by two, the off-diagonal added, and multiplied by two 2080 * again. The low bit is simply a copy of the low bit of the 2081 * input, so it doesn't need special care. 2082 */ 2083 2084 // Store the squares, right shifted one bit (i.e., divided by 2) 2085 int lastProductLowWord = 0; 2086 for (int j=0, i=0; j < len; j++) { 2087 long piece = (x[j] & LONG_MASK); 2088 long product = piece * piece; 2089 z[i++] = (lastProductLowWord << 31) | cast(int)(product >>> 33); 2090 z[i++] = cast(int)(product >>> 1); 2091 lastProductLowWord = cast(int)product; 2092 } 2093 2094 // Add in off-diagonal sums 2095 for (int i=len, offset=1; i > 0; i--, offset+=2) { 2096 int t = x[i-1]; 2097 t = mulAdd(z, x, offset, i-1, t); 2098 addOne(z, offset-1, i, t); 2099 } 2100 2101 // Shift back up and set low bit 2102 primitiveLeftShift(z, zlen, 1); 2103 z[zlen-1] |= x[len-1] & 1; 2104 2105 return z; 2106 } 2107 2108 /** 2109 * Squares a BigInteger using the Karatsuba squaring algorithm. It should 2110 * be used when both numbers are larger than a certain threshold (found 2111 * experimentally). It is a recursive divide-and-conquer algorithm that 2112 * has better asymptotic performance than the algorithm used in 2113 * squareToLen. 2114 */ 2115 private BigInteger squareKaratsuba() { 2116 int half = cast(int)(mag.length+1) / 2; 2117 2118 BigInteger xl = getLower(half); 2119 BigInteger xh = getUpper(half); 2120 2121 BigInteger xhs = xh.square(); // xhs = xh^2 2122 BigInteger xls = xl.square(); // xls = xl^2 2123 2124 // xh^2 << 64 + (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2 2125 return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls); 2126 } 2127 2128 /** 2129 * Squares a BigInteger using the 3-way Toom-Cook squaring algorithm. It 2130 * should be used when both numbers are larger than a certain threshold 2131 * (found experimentally). It is a recursive divide-and-conquer algorithm 2132 * that has better asymptotic performance than the algorithm used in 2133 * squareToLen or squareKaratsuba. 2134 */ 2135 private BigInteger squareToomCook3() { 2136 int len = cast(int)mag.length; 2137 2138 // k is the size (in ints) of the lower-order slices. 2139 int k = (len+2)/3; // Equal to ceil(largest/3) 2140 2141 // r is the size (in ints) of the highest-order slice. 2142 int r = len - 2*k; 2143 2144 // Obtain slices of the numbers. a2 is the most significant 2145 // bits of the number, and a0 the least significant. 2146 BigInteger a0, a1, a2; 2147 a2 = getToomSlice(k, r, 0, len); 2148 a1 = getToomSlice(k, r, 1, len); 2149 a0 = getToomSlice(k, r, 2, len); 2150 BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1; 2151 2152 v0 = a0.square(); 2153 da1 = a2.add(a0); 2154 vm1 = da1.subtract(a1).square(); 2155 da1 = da1.add(a1); 2156 v1 = da1.square(); 2157 vinf = a2.square(); 2158 v2 = da1.add(a2).shiftLeft(1).subtract(a0).square(); 2159 2160 // The algorithm requires two divisions by 2 and one by 3. 2161 // All divisions are known to be exact, that is, they do not produce 2162 // remainders, and all results are positive. The divisions by 2 are 2163 // implemented as right shifts which are relatively efficient, leaving 2164 // only a division by 3. 2165 // The division by 3 is done by an optimized algorithm for this case. 2166 t2 = v2.subtract(vm1).exactDivideBy3(); 2167 tm1 = v1.subtract(vm1).shiftRight(1); 2168 t1 = v1.subtract(v0); 2169 t2 = t2.subtract(t1).shiftRight(1); 2170 t1 = t1.subtract(tm1).subtract(vinf); 2171 t2 = t2.subtract(vinf.shiftLeft(1)); 2172 tm1 = tm1.subtract(t2); 2173 2174 // Number of bits to shift left. 2175 int ss = k*32; 2176 2177 return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0); 2178 } 2179 2180 // Division 2181 2182 /** 2183 * Returns a BigInteger whose value is {@code (this / val)}. 2184 * 2185 * @param val value by which this BigInteger is to be divided. 2186 * @return {@code this / val} 2187 * @throws ArithmeticException if {@code val} is zero. 2188 */ 2189 BigInteger divide(BigInteger val) { 2190 // if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || 2191 // mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) { 2192 // return divideKnuth(val); 2193 // } else { 2194 // return divideBurnikelZiegler(val); 2195 // } 2196 return null; 2197 } 2198 2199 /** 2200 * Returns a BigInteger whose value is {@code (this / val)} using an O(n^2) algorithm from Knuth. 2201 * 2202 * @param val value by which this BigInteger is to be divided. 2203 * @return {@code this / val} 2204 * @throws ArithmeticException if {@code val} is zero. 2205 * @see MutableBigInteger#divideKnuth(MutableBigInteger, MutableBigInteger, bool) 2206 */ 2207 // private BigInteger divideKnuth(BigInteger val) { 2208 // MutableBigInteger q = new MutableBigInteger(), 2209 // a = new MutableBigInteger(this.mag), 2210 // b = new MutableBigInteger(val.mag); 2211 2212 // a.divideKnuth(b, q, false); 2213 // return q.toBigInteger(this._signum * val.signum); 2214 // } 2215 2216 /** 2217 * Returns an array of two BigIntegers containing {@code (this / val)} 2218 * followed by {@code (this % val)}. 2219 * 2220 * @param val value by which this BigInteger is to be divided, and the 2221 * remainder computed. 2222 * @return an array of two BigIntegers: the quotient {@code (this / val)} 2223 * is the initial element, and the remainder {@code (this % val)} 2224 * is the final element. 2225 * @throws ArithmeticException if {@code val} is zero. 2226 */ 2227 BigInteger[] divideAndRemainder(BigInteger val) { 2228 if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || 2229 mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) { 2230 return divideAndRemainderKnuth(val); 2231 } else { 2232 return divideAndRemainderBurnikelZiegler(val); 2233 } 2234 } 2235 2236 /** Long division */ 2237 private BigInteger[] divideAndRemainderKnuth(BigInteger val) { 2238 BigInteger[] result = new BigInteger[2]; 2239 MutableBigInteger q = new MutableBigInteger(), 2240 a = new MutableBigInteger(this.mag), 2241 b = new MutableBigInteger(val.mag); 2242 MutableBigInteger r = a.divideKnuth(b, q); 2243 result[0] = q.toBigInteger(this._signum == val.signum ? 1 : -1); 2244 result[1] = r.toBigInteger(this._signum); 2245 return result; 2246 } 2247 2248 /** 2249 * Returns a BigInteger whose value is {@code (this % val)}. 2250 * 2251 * @param val value by which this BigInteger is to be divided, and the 2252 * remainder computed. 2253 * @return {@code this % val} 2254 * @throws ArithmeticException if {@code val} is zero. 2255 */ 2256 BigInteger remainder(BigInteger val) { 2257 if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || 2258 mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) { 2259 return remainderKnuth(val); 2260 } else { 2261 return remainderBurnikelZiegler(val); 2262 } 2263 } 2264 2265 /** Long division */ 2266 private BigInteger remainderKnuth(BigInteger val) { 2267 MutableBigInteger q = new MutableBigInteger(), 2268 a = new MutableBigInteger(this.mag), 2269 b = new MutableBigInteger(val.mag); 2270 2271 return a.divideKnuth(b, q).toBigInteger(this._signum); 2272 } 2273 2274 /** 2275 * Calculates {@code this / val} using the Burnikel-Ziegler algorithm. 2276 * @param val the divisor 2277 * @return {@code this / val} 2278 */ 2279 private BigInteger divideBurnikelZiegler(BigInteger val) { 2280 return divideAndRemainderBurnikelZiegler(val)[0]; 2281 } 2282 2283 /** 2284 * Calculates {@code this % val} using the Burnikel-Ziegler algorithm. 2285 * @param val the divisor 2286 * @return {@code this % val} 2287 */ 2288 private BigInteger remainderBurnikelZiegler(BigInteger val) { 2289 return divideAndRemainderBurnikelZiegler(val)[1]; 2290 } 2291 2292 /** 2293 * Computes {@code this / val} and {@code this % val} using the 2294 * Burnikel-Ziegler algorithm. 2295 * @param val the divisor 2296 * @return an array containing the quotient and remainder 2297 */ 2298 private BigInteger[] divideAndRemainderBurnikelZiegler(BigInteger val) { 2299 MutableBigInteger q = new MutableBigInteger(); 2300 MutableBigInteger r = new MutableBigInteger(this).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q); 2301 BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum); 2302 BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum); 2303 return [qBigInt, rBigInt]; 2304 } 2305 2306 /** 2307 * Returns a BigInteger whose value is <code>(this<sup>exponent</sup>)</code>. 2308 * Note that {@code exponent} is an integer rather than a BigInteger. 2309 * 2310 * @param exponent exponent to which this BigInteger is to be raised. 2311 * @return <code>this<sup>exponent</sup></code> 2312 * @throws ArithmeticException {@code exponent} is negative. (This would 2313 * cause the operation to yield a non-integer value.) 2314 */ 2315 BigInteger pow(int exponent) { 2316 if (exponent < 0) { 2317 throw new ArithmeticException("Negative exponent"); 2318 } 2319 if (_signum == 0) { 2320 return (exponent == 0 ? ONE : this); 2321 } 2322 2323 BigInteger partToSquare = this.abs(); 2324 2325 // Factor out powers of two from the base, as the exponentiation of 2326 // these can be done by left shifts only. 2327 // The remaining part can then be exponentiated faster. The 2328 // powers of two will be multiplied back at the end. 2329 int powersOfTwo = partToSquare.getLowestSetBit(); 2330 long bitsToShift = cast(long)powersOfTwo * exponent; 2331 if (bitsToShift > int.max) { 2332 reportOverflow(); 2333 } 2334 2335 int remainingBits; 2336 2337 // Factor the powers of two out quickly by shifting right, if needed. 2338 if (powersOfTwo > 0) { 2339 partToSquare = partToSquare.shiftRight(powersOfTwo); 2340 remainingBits = partToSquare.bitLength(); 2341 if (remainingBits == 1) { // Nothing left but +/- 1? 2342 if (signum < 0 && (exponent&1) == 1) { 2343 return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent); 2344 } else { 2345 return ONE.shiftLeft(powersOfTwo*exponent); 2346 } 2347 } 2348 } else { 2349 remainingBits = partToSquare.bitLength(); 2350 if (remainingBits == 1) { // Nothing left but +/- 1? 2351 if (signum < 0 && (exponent&1) == 1) { 2352 return NEGATIVE_ONE; 2353 } else { 2354 return ONE; 2355 } 2356 } 2357 } 2358 2359 // This is a quick way to approximate the size of the result, 2360 // similar to doing log2[n] * exponent. This will give an upper bound 2361 // of how big the result can be, and which algorithm to use. 2362 long scaleFactor = cast(long)remainingBits * exponent; 2363 2364 // Use slightly different algorithms for small and large operands. 2365 // See if the result will safely fit into a long. (Largest 2^63-1) 2366 if (partToSquare.mag.length == 1 && scaleFactor <= 62) { 2367 // Small number algorithm. Everything fits into a long. 2368 int newSign = (signum <0 && (exponent&1) == 1 ? -1 : 1); 2369 long result = 1; 2370 long baseToPow2 = partToSquare.mag[0] & LONG_MASK; 2371 2372 int workingExponent = exponent; 2373 2374 // Perform exponentiation using repeated squaring trick 2375 while (workingExponent != 0) { 2376 if ((workingExponent & 1) == 1) { 2377 result = result * baseToPow2; 2378 } 2379 2380 if ((workingExponent >>>= 1) != 0) { 2381 baseToPow2 = baseToPow2 * baseToPow2; 2382 } 2383 } 2384 2385 // Multiply back the powers of two (quickly, by shifting left) 2386 if (powersOfTwo > 0) { 2387 if (bitsToShift + scaleFactor <= 62) { // Fits in long? 2388 return valueOf((result << bitsToShift) * newSign); 2389 } else { 2390 return valueOf(result*newSign).shiftLeft(cast(int) bitsToShift); 2391 } 2392 } 2393 else { 2394 return valueOf(result*newSign); 2395 } 2396 } else { 2397 // Large number algorithm. This is basically identical to 2398 // the algorithm above, but calls multiply() and square() 2399 // which may use more efficient algorithms for large numbers. 2400 BigInteger answer = ONE; 2401 2402 int workingExponent = exponent; 2403 // Perform exponentiation using repeated squaring trick 2404 while (workingExponent != 0) { 2405 if ((workingExponent & 1) == 1) { 2406 answer = answer.multiply(partToSquare); 2407 } 2408 2409 if ((workingExponent >>>= 1) != 0) { 2410 partToSquare = partToSquare.square(); 2411 } 2412 } 2413 // Multiply back the (exponentiated) powers of two (quickly, 2414 // by shifting left) 2415 if (powersOfTwo > 0) { 2416 answer = answer.shiftLeft(powersOfTwo*exponent); 2417 } 2418 2419 if (signum < 0 && (exponent&1) == 1) { 2420 return answer.negate(); 2421 } else { 2422 return answer; 2423 } 2424 } 2425 } 2426 2427 /** 2428 * Returns the integer square root of this BigInteger. The integer square 2429 * root of the corresponding mathematical integer {@code n} is the largest 2430 * mathematical integer {@code s} such that {@code s*s <= n}. It is equal 2431 * to the value of {@code floor(sqrt(n))}, where {@code sqrt(n)} denotes the 2432 * real square root of {@code n} treated as a real. Note that the integer 2433 * square root will be less than the real square root if the latter is not 2434 * representable as an integral value. 2435 * 2436 * @return the integer square root of {@code this} 2437 * @throws ArithmeticException if {@code this} is negative. (The square 2438 * root of a negative integer {@code val} is 2439 * {@code (i * sqrt(-val))} where <i>i</i> is the 2440 * <i>imaginary unit</i> and is equal to 2441 * {@code sqrt(-1)}.) 2442 * @since 9 2443 */ 2444 BigInteger sqrt() { 2445 if (this._signum < 0) { 2446 throw new ArithmeticException("Negative BigInteger"); 2447 } 2448 2449 return new MutableBigInteger(this.mag).sqrt().toBigInteger(); 2450 } 2451 2452 /** 2453 * Returns an array of two BigIntegers containing the integer square root 2454 * {@code s} of {@code this} and its remainder {@code this - s*s}, 2455 * respectively. 2456 * 2457 * @return an array of two BigIntegers with the integer square root at 2458 * offset 0 and the remainder at offset 1 2459 * @throws ArithmeticException if {@code this} is negative. (The square 2460 * root of a negative integer {@code val} is 2461 * {@code (i * sqrt(-val))} where <i>i</i> is the 2462 * <i>imaginary unit</i> and is equal to 2463 * {@code sqrt(-1)}.) 2464 * @see #sqrt() 2465 * @since 9 2466 */ 2467 BigInteger[] sqrtAndRemainder() { 2468 BigInteger s = sqrt(); 2469 BigInteger r = this.subtract(s.square()); 2470 assert(r.compareTo(BigInteger.ZERO) >= 0); 2471 return [s, r]; 2472 } 2473 2474 /** 2475 * Returns a BigInteger whose value is the greatest common divisor of 2476 * {@code abs(this)} and {@code abs(val)}. Returns 0 if 2477 * {@code this == 0 && val == 0}. 2478 * 2479 * @param val value with which the GCD is to be computed. 2480 * @return {@code GCD(abs(this), abs(val))} 2481 */ 2482 BigInteger gcd(BigInteger val) { 2483 if (val._signum == 0) 2484 return this.abs(); 2485 else if (this._signum == 0) 2486 return val.abs(); 2487 2488 MutableBigInteger a = new MutableBigInteger(this); 2489 MutableBigInteger b = new MutableBigInteger(val); 2490 2491 MutableBigInteger result = a.hybridGCD(b); 2492 2493 return result.toBigInteger(1); 2494 } 2495 2496 /** 2497 * Package private method to return bit length for an integer. 2498 */ 2499 static int bitLengthForInt(int n) { 2500 return 32 - Integer.numberOfLeadingZeros(n); 2501 } 2502 2503 /** 2504 * Left shift int array a up to len by n bits. Returns the array that 2505 * results from the shift since space may have to be reallocated. 2506 */ 2507 private static int[] leftShift(int[] a, int len, int n) { 2508 int nInts = n >>> 5; 2509 int nBits = n&0x1F; 2510 int bitsInHighWord = bitLengthForInt(a[0]); 2511 2512 // If shift can be done without recopy, do so 2513 if (n <= (32-bitsInHighWord)) { 2514 primitiveLeftShift(a, len, nBits); 2515 return a; 2516 } else { // Array must be resized 2517 if (nBits <= (32-bitsInHighWord)) { 2518 int[] result = new int[nInts+len]; 2519 // System.arraycopy(a, 0, result, 0, len); 2520 result[0..len] = a[0..len]; 2521 primitiveLeftShift(result, cast(int)result.length, nBits); 2522 return result; 2523 } else { 2524 int[] result = new int[nInts+len+1]; 2525 // System.arraycopy(a, 0, result, 0, len); 2526 result[0..len] = a[0..len]; 2527 primitiveRightShift(result, cast(int)result.length, 32 - nBits); 2528 return result; 2529 } 2530 } 2531 } 2532 2533 // shifts a up to len right n bits assumes no leading zeros, 0<n<32 2534 static void primitiveRightShift(int[] a, int len, int n) { 2535 int n2 = 32 - n; 2536 for (int i=len-1, c=a[i]; i > 0; i--) { 2537 int b = c; 2538 c = a[i-1]; 2539 a[i] = (c << n2) | (b >>> n); 2540 } 2541 a[0] >>>= n; 2542 } 2543 2544 // shifts a up to len left n bits assumes no leading zeros, 0<=n<32 2545 static void primitiveLeftShift(int[] a, int len, int n) { 2546 if (len == 0 || n == 0) 2547 return; 2548 2549 int n2 = 32 - n; 2550 for (int i=0, c=a[i], m=i+len-1; i < m; i++) { 2551 int b = c; 2552 c = a[i+1]; 2553 a[i] = (b << n) | (c >>> n2); 2554 } 2555 a[len-1] <<= n; 2556 } 2557 2558 /** 2559 * Calculate bitlength of contents of the first len elements an int array, 2560 * assuming there are no leading zero ints. 2561 */ 2562 private static int bitLength(int[] val, int len) { 2563 if (len == 0) 2564 return 0; 2565 return ((len - 1) << 5) + bitLengthForInt(val[0]); 2566 } 2567 2568 /** 2569 * Returns a BigInteger whose value is the absolute value of this 2570 * BigInteger. 2571 * 2572 * @return {@code abs(this)} 2573 */ 2574 BigInteger abs() { 2575 return (signum >= 0 ? this : this.negate()); 2576 } 2577 2578 /** 2579 * Returns a BigInteger whose value is {@code (-this)}. 2580 * 2581 * @return {@code -this} 2582 */ 2583 BigInteger negate() { 2584 return new BigInteger(this.mag, -this._signum); 2585 } 2586 2587 /** 2588 * Returns the signum function of this BigInteger. 2589 * 2590 * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or 2591 * positive. 2592 */ 2593 int signum() { 2594 return this._signum; 2595 } 2596 2597 // Modular Arithmetic Operations 2598 2599 /** 2600 * Returns a BigInteger whose value is {@code (this mod m}). This method 2601 * differs from {@code remainder} in that it always returns a 2602 * <i>non-negative</i> BigInteger. 2603 * 2604 * @param m the modulus. 2605 * @return {@code this mod m} 2606 * @throws ArithmeticException {@code m} ≤ 0 2607 * @see #remainder 2608 */ 2609 BigInteger mod(BigInteger m) { 2610 if (m.signum <= 0) 2611 throw new ArithmeticException("BigInteger: modulus not positive"); 2612 2613 BigInteger result = this.remainder(m); 2614 return (result.signum >= 0 ? result : result.add(m)); 2615 } 2616 2617 /** 2618 * Returns a BigInteger whose value is 2619 * <code>(this<sup>exponent</sup> mod m)</code>. (Unlike {@code pow}, this 2620 * method permits negative exponents.) 2621 * 2622 * @param exponent the exponent. 2623 * @param m the modulus. 2624 * @return <code>this<sup>exponent</sup> mod m</code> 2625 * @throws ArithmeticException {@code m} ≤ 0 or the exponent is 2626 * negative and this BigInteger is not <i>relatively 2627 * prime</i> to {@code m}. 2628 * @see #modInverse 2629 */ 2630 BigInteger modPow(BigInteger exponent, BigInteger m) { 2631 if (m.signum <= 0) 2632 throw new ArithmeticException("BigInteger: modulus not positive"); 2633 2634 // Trivial cases 2635 if (exponent._signum == 0) 2636 return (m.equals(ONE) ? ZERO : ONE); 2637 2638 if (this.equals(ONE)) 2639 return (m.equals(ONE) ? ZERO : ONE); 2640 2641 if (this.equals(ZERO) && exponent.signum >= 0) 2642 return ZERO; 2643 2644 if (this.equals(negConst[1]) && (!exponent.testBit(0))) 2645 return (m.equals(ONE) ? ZERO : ONE); 2646 2647 bool invertResult; 2648 invertResult = (exponent.signum < 0); 2649 if (invertResult) 2650 exponent = exponent.negate(); 2651 2652 BigInteger base = (this._signum < 0 || this.compareTo(m) >= 0 2653 ? this.mod(m) : this); 2654 BigInteger result; 2655 if (m.testBit(0)) { // odd modulus 2656 result = base.oddModPow(exponent, m); 2657 } else { 2658 /* 2659 * Even modulus. Tear it into an "odd part" (m1) and power of two 2660 * (m2), exponentiate mod m1, manually exponentiate mod m2, and 2661 * use Chinese Remainder Theorem to combine results. 2662 */ 2663 2664 // Tear m apart into odd part (m1) and power of 2 (m2) 2665 int p = m.getLowestSetBit(); // Max pow of 2 that divides m 2666 2667 BigInteger m1 = m.shiftRight(p); // m/2**p 2668 BigInteger m2 = ONE.shiftLeft(p); // 2**p 2669 2670 // Calculate new base from m1 2671 BigInteger base2 = (this._signum < 0 || this.compareTo(m1) >= 0 2672 ? this.mod(m1) : this); 2673 2674 // Caculate (base ** exponent) mod m1. 2675 BigInteger a1 = (m1.equals(ONE) ? ZERO : 2676 base2.oddModPow(exponent, m1)); 2677 2678 // Calculate (this ** exponent) mod m2 2679 BigInteger a2 = base.modPow2(exponent, p); 2680 2681 // Combine results using Chinese Remainder Theorem 2682 BigInteger y1 = m2.modInverse(m1); 2683 BigInteger y2 = m1.modInverse(m2); 2684 2685 if (m.mag.length < MAX_MAG_LENGTH / 2) { 2686 result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m); 2687 } else { 2688 MutableBigInteger t1 = new MutableBigInteger(); 2689 new MutableBigInteger(a1.multiply(m2)).multiply(new MutableBigInteger(y1), t1); 2690 MutableBigInteger t2 = new MutableBigInteger(); 2691 new MutableBigInteger(a2.multiply(m1)).multiply(new MutableBigInteger(y2), t2); 2692 t1.add(t2); 2693 MutableBigInteger q = new MutableBigInteger(); 2694 result = t1.divide(new MutableBigInteger(m), q).toBigInteger(); 2695 } 2696 } 2697 2698 return (invertResult ? result.modInverse(m) : result); 2699 } 2700 2701 // Montgomery multiplication. These are wrappers for 2702 // implMontgomeryXX routines which are expected to be replaced by 2703 // virtual machine intrinsics. We don't use the intrinsics for 2704 // very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be 2705 // larger than any reasonable crypto key. 2706 private static int[] montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv, 2707 int[] product) { 2708 implMontgomeryMultiplyChecks(a, b, n, len, product); 2709 if (len > MONTGOMERY_INTRINSIC_THRESHOLD) { 2710 // Very long argument: do not use an intrinsic 2711 product = multiplyToLen(a, len, b, len, product); 2712 return montReduce(product, n, len, cast(int)inv); 2713 } else { 2714 return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len)); 2715 } 2716 } 2717 private static int[] montgomerySquare(int[] a, int[] n, int len, long inv, 2718 int[] product) { 2719 implMontgomeryMultiplyChecks(a, a, n, len, product); 2720 if (len > MONTGOMERY_INTRINSIC_THRESHOLD) { 2721 // Very long argument: do not use an intrinsic 2722 product = squareToLen(a, len, product); 2723 return montReduce(product, n, len, cast(int)inv); 2724 } else { 2725 return implMontgomerySquare(a, n, len, inv, materialize(product, len)); 2726 } 2727 } 2728 2729 // Range-check everything. 2730 private static void implMontgomeryMultiplyChecks 2731 (int[] a, int[] b, int[] n, int len, int[] product) { 2732 if (len % 2 != 0) { 2733 throw new IllegalArgumentException("input array length must be even: " ~ len.to!string()); 2734 } 2735 2736 if (len < 1) { 2737 throw new IllegalArgumentException("invalid input length: " ~ len.to!string()); 2738 } 2739 2740 if (len > a.length || 2741 len > b.length || 2742 len > n.length || 2743 (product !is null && len > product.length)) { 2744 throw new IllegalArgumentException("input array length out of bound: " ~ len.to!string()); 2745 } 2746 } 2747 2748 // Make sure that the int array z (which is expected to contain 2749 // the result of a Montgomery multiplication) is present and 2750 // sufficiently large. 2751 private static int[] materialize(int[] z, int len) { 2752 if (z is null || z.length < len) 2753 z = new int[len]; 2754 return z; 2755 } 2756 2757 // These methods are intended to be replaced by virtual machine 2758 // intrinsics. 2759 2760 private static int[] implMontgomeryMultiply(int[] a, int[] b, int[] n, int len, 2761 long inv, int[] product) { 2762 product = multiplyToLen(a, len, b, len, product); 2763 return montReduce(product, n, len, cast(int)inv); 2764 } 2765 2766 private static int[] implMontgomerySquare(int[] a, int[] n, int len, 2767 long inv, int[] product) { 2768 product = squareToLen(a, len, product); 2769 return montReduce(product, n, len, cast(int)inv); 2770 } 2771 2772 enum int[] bnExpModThreshTable = [7, 25, 81, 241, 673, 1793, 2773 int.max]; // Sentinel 2774 2775 /** 2776 * Returns a BigInteger whose value is x to the power of y mod z. 2777 * Assumes: z is odd && x < z. 2778 */ 2779 private BigInteger oddModPow(BigInteger y, BigInteger z) { 2780 /* 2781 * The algorithm is adapted from Colin Plumb's C library. 2782 * 2783 * The window algorithm: 2784 * The idea is to keep a running product of b1 = n^(high-order bits of exp) 2785 * and then keep appending exponent bits to it. The following patterns 2786 * apply to a 3-bit window (k = 3): 2787 * To append 0: square 2788 * To append 1: square, multiply by n^1 2789 * To append 10: square, multiply by n^1, square 2790 * To append 11: square, square, multiply by n^3 2791 * To append 100: square, multiply by n^1, square, square 2792 * To append 101: square, square, square, multiply by n^5 2793 * To append 110: square, square, multiply by n^3, square 2794 * To append 111: square, square, square, multiply by n^7 2795 * 2796 * Since each pattern involves only one multiply, the longer the pattern 2797 * the better, except that a 0 (no multiplies) can be appended directly. 2798 * We precompute a table of odd powers of n, up to 2^k, and can then 2799 * multiply k bits of exponent at a time. Actually, assuming random 2800 * exponents, there is on average one zero bit between needs to 2801 * multiply (1/2 of the time there's none, 1/4 of the time there's 1, 2802 * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so 2803 * you have to do one multiply per k+1 bits of exponent. 2804 * 2805 * The loop walks down the exponent, squaring the result buffer as 2806 * it goes. There is a wbits+1 bit lookahead buffer, buf, that is 2807 * filled with the upcoming exponent bits. (What is read after the 2808 * end of the exponent is unimportant, but it is filled with zero here.) 2809 * When the most-significant bit of this buffer becomes set, i.e. 2810 * (buf & tblmask) != 0, we have to decide what pattern to multiply 2811 * by, and when to do it. We decide, remember to do it in future 2812 * after a suitable number of squarings have passed (e.g. a pattern 2813 * of "100" in the buffer requires that we multiply by n^1 immediately; 2814 * a pattern of "110" calls for multiplying by n^3 after one more 2815 * squaring), clear the buffer, and continue. 2816 * 2817 * When we start, there is one more optimization: the result buffer 2818 * is implcitly one, so squaring it or multiplying by it can be 2819 * optimized away. Further, if we start with a pattern like "100" 2820 * in the lookahead window, rather than placing n into the buffer 2821 * and then starting to square it, we have already computed n^2 2822 * to compute the odd-powers table, so we can place that into 2823 * the buffer and save a squaring. 2824 * 2825 * This means that if you have a k-bit window, to compute n^z, 2826 * where z is the high k bits of the exponent, 1/2 of the time 2827 * it requires no squarings. 1/4 of the time, it requires 1 2828 * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings. 2829 * And the remaining 1/2^(k-1) of the time, the top k bits are a 2830 * 1 followed by k-1 0 bits, so it again only requires k-2 2831 * squarings, not k-1. The average of these is 1. Add that 2832 * to the one squaring we have to do to compute the table, 2833 * and you'll see that a k-bit window saves k-2 squarings 2834 * as well as reducing the multiplies. (It actually doesn't 2835 * hurt in the case k = 1, either.) 2836 */ 2837 // Special case for exponent of one 2838 if (y.equals(ONE)) 2839 return this; 2840 2841 // Special case for base of zero 2842 if (_signum == 0) 2843 return ZERO; 2844 2845 int[] base = mag.dup; 2846 int[] exp = y.mag; 2847 int[] mod = z.mag; 2848 int modLen = cast(int)mod.length; 2849 2850 // Make modLen even. It is conventional to use a cryptographic 2851 // modulus that is 512, 768, 1024, or 2048 bits, so this code 2852 // will not normally be executed. However, it is necessary for 2853 // the correct functioning of the HotSpot intrinsics. 2854 if ((modLen & 1) != 0) { 2855 int[] x = new int[modLen + 1]; 2856 // System.arraycopy(mod, 0, x, 1, modLen); 2857 x[1 .. modLen+1] = mod[0 .. modLen]; 2858 mod = x; 2859 modLen++; 2860 } 2861 2862 // Select an appropriate window size 2863 int wbits = 0; 2864 int ebits = bitLength(exp, cast(int)exp.length); 2865 // if exponent is 65537 (0x10001), use minimum window size 2866 if ((ebits != 17) || (exp[0] != 65537)) { 2867 while (ebits > bnExpModThreshTable[wbits]) { 2868 wbits++; 2869 } 2870 } 2871 2872 // Calculate appropriate table size 2873 int tblmask = 1 << wbits; 2874 2875 // Allocate table for precomputed odd powers of base in Montgomery form 2876 int[][] table = new int[][tblmask]; 2877 for (int i=0; i < tblmask; i++) 2878 table[i] = new int[modLen]; 2879 2880 // Compute the modular inverse of the least significant 64-bit 2881 // digit of the modulus 2882 long n0 = (mod[modLen-1] & LONG_MASK) + ((mod[modLen-2] & LONG_MASK) << 32); 2883 long inv = -MutableBigInteger.inverseMod64(n0); 2884 2885 // Convert base to Montgomery form 2886 int[] a = leftShift(base, cast(int)base.length, modLen << 5); 2887 2888 MutableBigInteger q = new MutableBigInteger(), 2889 a2 = new MutableBigInteger(a), 2890 b2 = new MutableBigInteger(mod); 2891 b2.normalize(); // MutableBigInteger.divide() assumes that its 2892 // divisor is in normal form. 2893 2894 MutableBigInteger r= a2.divide(b2, q); 2895 table[0] = r.toIntArray(); 2896 2897 // Pad table[0] with leading zeros so its length is at least modLen 2898 if (table[0].length < modLen) { 2899 size_t len = table[0].length; 2900 size_t offset = modLen - len; 2901 int[] t2 = new int[modLen]; 2902 t2[offset .. offset+len] = table[0][0 .. $]; 2903 // System.arraycopy(table[0], 0, t2, offset, table[0].length); 2904 2905 table[0] = t2; 2906 } 2907 2908 // Set b to the square of the base 2909 int[] b = montgomerySquare(table[0], mod, modLen, inv, null); 2910 2911 // Set t to high half of b 2912 int[] t = b[0..modLen].dup; // Arrays.copyOf(b, modLen); 2913 2914 // Fill in the table with odd powers of the base 2915 for (int i=1; i < tblmask; i++) { 2916 table[i] = montgomeryMultiply(t, table[i-1], mod, modLen, inv, null); 2917 } 2918 2919 // Pre load the window that slides over the exponent 2920 int bitpos = 1 << ((ebits-1) & (32-1)); 2921 2922 int buf = 0; 2923 int elen = cast(int)exp.length; 2924 int eIndex = 0; 2925 for (int i = 0; i <= wbits; i++) { 2926 buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0); 2927 bitpos >>>= 1; 2928 if (bitpos == 0) { 2929 eIndex++; 2930 bitpos = 1 << (32-1); 2931 elen--; 2932 } 2933 } 2934 2935 int multpos = ebits; 2936 2937 // The first iteration, which is hoisted out of the main loop 2938 ebits--; 2939 bool isone = true; 2940 2941 multpos = ebits - wbits; 2942 while ((buf & 1) == 0) { 2943 buf >>>= 1; 2944 multpos++; 2945 } 2946 2947 int[] mult = table[buf >>> 1]; 2948 2949 buf = 0; 2950 if (multpos == ebits) 2951 isone = false; 2952 2953 // The main loop 2954 while (true) { 2955 ebits--; 2956 // Advance the window 2957 buf <<= 1; 2958 2959 if (elen != 0) { 2960 buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0; 2961 bitpos >>>= 1; 2962 if (bitpos == 0) { 2963 eIndex++; 2964 bitpos = 1 << (32-1); 2965 elen--; 2966 } 2967 } 2968 2969 // Examine the window for pending multiplies 2970 if ((buf & tblmask) != 0) { 2971 multpos = ebits - wbits; 2972 while ((buf & 1) == 0) { 2973 buf >>>= 1; 2974 multpos++; 2975 } 2976 mult = table[buf >>> 1]; 2977 buf = 0; 2978 } 2979 2980 // Perform multiply 2981 if (ebits == multpos) { 2982 if (isone) { 2983 b = mult.dup; 2984 isone = false; 2985 } else { 2986 t = b; 2987 a = montgomeryMultiply(t, mult, mod, modLen, inv, a); 2988 t = a; a = b; b = t; 2989 } 2990 } 2991 2992 // Check if done 2993 if (ebits == 0) 2994 break; 2995 2996 // Square the input 2997 if (!isone) { 2998 t = b; 2999 a = montgomerySquare(t, mod, modLen, inv, a); 3000 t = a; a = b; b = t; 3001 } 3002 } 3003 3004 // Convert result out of Montgomery form and return 3005 int[] t2 = new int[2*modLen]; 3006 // System.arraycopy(b, 0, t2, modLen, modLen); 3007 t2[modLen .. modLen+modLen] = b[0 .. modLen]; 3008 b = montReduce(t2, mod, modLen, cast(int)inv); 3009 // t2 = Arrays.copyOf(b, modLen); 3010 t2 = b[0 .. modLen].dup; 3011 3012 return new BigInteger(1, t2); 3013 } 3014 3015 /** 3016 * Montgomery reduce n, modulo mod. This reduces modulo mod and divides 3017 * by 2^(32*mlen). Adapted from Colin Plumb's C library. 3018 */ 3019 private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) { 3020 int c=0; 3021 int len = mlen; 3022 int offset=0; 3023 3024 do { 3025 int nEnd = n[n.length-1-offset]; 3026 int carry = mulAdd(n, mod, offset, mlen, inv * nEnd); 3027 c += addOne(n, offset, mlen, carry); 3028 offset++; 3029 } while (--len > 0); 3030 3031 while (c > 0) 3032 c += subN(n, mod, mlen); 3033 3034 while (intArrayCmpToLen(n, mod, mlen) >= 0) 3035 subN(n, mod, mlen); 3036 3037 return n; 3038 } 3039 3040 3041 /* 3042 * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than, 3043 * equal to, or greater than arg2 up to length len. 3044 */ 3045 private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) { 3046 for (int i=0; i < len; i++) { 3047 long b1 = arg1[i] & LONG_MASK; 3048 long b2 = arg2[i] & LONG_MASK; 3049 if (b1 < b2) 3050 return -1; 3051 if (b1 > b2) 3052 return 1; 3053 } 3054 return 0; 3055 } 3056 3057 /** 3058 * Subtracts two numbers of same length, returning borrow. 3059 */ 3060 private static int subN(int[] a, int[] b, int len) { 3061 long sum = 0; 3062 3063 while (--len >= 0) { 3064 sum = (a[len] & LONG_MASK) - 3065 (b[len] & LONG_MASK) + (sum >> 32); 3066 a[len] = cast(int)sum; 3067 } 3068 3069 return cast(int)(sum >> 32); 3070 } 3071 3072 /** 3073 * Multiply an array by one word k and add to result, return the carry 3074 */ 3075 static int mulAdd(int[] ot, int[] input, int offset, int len, int k) { 3076 implMulAddCheck(ot, input, offset, len, k); 3077 return implMulAdd(ot, input, offset, len, k); 3078 } 3079 3080 /** 3081 * Parameters validation. 3082 */ 3083 private static void implMulAddCheck(int[] ot, int[] input, int offset, int len, int k) { 3084 if (len > input.length) { 3085 throw new IllegalArgumentException("input length is out of bound: " ~ len.to!string() ~ " > " ~ to!string(input.length)); 3086 } 3087 if (offset < 0) { 3088 throw new IllegalArgumentException("input offset is invalid: " ~ offset.to!string()); 3089 } 3090 if (offset > (ot.length - 1)) { 3091 throw new IllegalArgumentException("input offset is out of bound: " ~ offset.to!string() ~ " > " ~ to!string(ot.length - 1)); 3092 } 3093 if (len > (ot.length - offset)) { 3094 throw new IllegalArgumentException("input len is out of bound: " ~ len.to!string() ~ " > " ~ to!string(ot.length - offset)); 3095 } 3096 } 3097 3098 /** 3099 * Java Runtime may use intrinsic for this method. 3100 */ 3101 3102 private static int implMulAdd(int[] output, int[] input, int offset, int len, int k) { 3103 long kLong = k & LONG_MASK; 3104 long carry = 0; 3105 3106 offset = cast(int)output.length-offset - 1; 3107 for (int j=len-1; j >= 0; j--) { 3108 long product = (input[j] & LONG_MASK) * kLong + 3109 (output[offset] & LONG_MASK) + carry; 3110 output[offset--] = cast(int)product; 3111 carry = product >>> 32; 3112 } 3113 return cast(int)carry; 3114 } 3115 3116 /** 3117 * Add one word to the number a mlen words into a. Return the resulting 3118 * carry. 3119 */ 3120 static int addOne(int[] a, int offset, int mlen, int carry) { 3121 offset = cast(int)a.length-1-mlen-offset; 3122 long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK); 3123 3124 a[offset] = cast(int)t; 3125 if ((t >>> 32) == 0) 3126 return 0; 3127 while (--mlen >= 0) { 3128 if (--offset < 0) { // Carry out of number 3129 return 1; 3130 } else { 3131 a[offset]++; 3132 if (a[offset] != 0) 3133 return 0; 3134 } 3135 } 3136 return 1; 3137 } 3138 3139 /** 3140 * Returns a BigInteger whose value is (this ** exponent) mod (2**p) 3141 */ 3142 private BigInteger modPow2(BigInteger exponent, int p) { 3143 /* 3144 * Perform exponentiation using repeated squaring trick, chopping off 3145 * high order bits as indicated by modulus. 3146 */ 3147 BigInteger result = ONE; 3148 BigInteger baseToPow2 = this.mod2(p); 3149 int expOffset = 0; 3150 3151 int limit = exponent.bitLength(); 3152 3153 if (this.testBit(0)) 3154 limit = (p-1) < limit ? (p-1) : limit; 3155 3156 while (expOffset < limit) { 3157 if (exponent.testBit(expOffset)) 3158 result = result.multiply(baseToPow2).mod2(p); 3159 expOffset++; 3160 if (expOffset < limit) 3161 baseToPow2 = baseToPow2.square().mod2(p); 3162 } 3163 3164 return result; 3165 } 3166 3167 /** 3168 * Returns a BigInteger whose value is this mod(2**p). 3169 * Assumes that this {@code BigInteger >= 0} and {@code p > 0}. 3170 */ 3171 private BigInteger mod2(int p) { 3172 if (bitLength() <= p) 3173 return this; 3174 3175 // Copy remaining ints of mag 3176 int numInts = (p + 31) >>> 5; 3177 int[] mag = new int[numInts]; 3178 // System.arraycopy(this.mag, (this.mag.length - numInts), mag, 0, numInts); 3179 mag[0..numInts] = this.mag[$-numInts .. $].dup; 3180 3181 // Mask out any excess bits 3182 int excessBits = (numInts << 5) - p; 3183 mag[0] &= (1L << (32-excessBits)) - 1; 3184 3185 return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1)); 3186 } 3187 3188 /** 3189 * Returns a BigInteger whose value is {@code (this}<sup>-1</sup> {@code mod m)}. 3190 * 3191 * @param m the modulus. 3192 * @return {@code this}<sup>-1</sup> {@code mod m}. 3193 * @throws ArithmeticException {@code m} ≤ 0, or this BigInteger 3194 * has no multiplicative inverse mod m (that is, this BigInteger 3195 * is not <i>relatively prime</i> to m). 3196 */ 3197 BigInteger modInverse(BigInteger m) { 3198 if (m.signum != 1) 3199 throw new ArithmeticException("BigInteger: modulus not positive"); 3200 3201 if (m.equals(ONE)) 3202 return ZERO; 3203 3204 // Calculate (this mod m) 3205 BigInteger modVal = this; 3206 if (signum < 0 || (this.compareMagnitude(m) >= 0)) 3207 modVal = this.mod(m); 3208 3209 if (modVal.equals(ONE)) 3210 return ONE; 3211 3212 MutableBigInteger a = new MutableBigInteger(modVal); 3213 MutableBigInteger b = new MutableBigInteger(m); 3214 3215 MutableBigInteger result = a.mutableModInverse(b); 3216 return result.toBigInteger(1); 3217 } 3218 3219 // Shift Operations 3220 3221 /** 3222 * Returns a BigInteger whose value is {@code (this << n)}. 3223 * The shift distance, {@code n}, may be negative, in which case 3224 * this method performs a right shift. 3225 * (Computes <code>floor(this * 2<sup>n</sup>)</code>.) 3226 * 3227 * @param n shift distance, in bits. 3228 * @return {@code this << n} 3229 * @see #shiftRight 3230 */ 3231 BigInteger shiftLeft(int n) { 3232 if (_signum == 0) 3233 return ZERO; 3234 if (n > 0) { 3235 return new BigInteger(shiftLeft(mag, n), signum); 3236 } else if (n == 0) { 3237 return this; 3238 } else { 3239 // Possible int overflow in (-n) is not a trouble, 3240 // because shiftRightImpl considers its argument unsigned 3241 return shiftRightImpl(-n); 3242 } 3243 } 3244 3245 /** 3246 * Returns a magnitude array whose value is {@code (mag << n)}. 3247 * The shift distance, {@code n}, is considered unnsigned. 3248 * (Computes <code>this * 2<sup>n</sup></code>.) 3249 * 3250 * @param mag magnitude, the most-significant int ({@code mag[0]}) must be non-zero. 3251 * @param n unsigned shift distance, in bits. 3252 * @return {@code mag << n} 3253 */ 3254 private static int[] shiftLeft(int[] mag, int n) { 3255 int nInts = n >>> 5; 3256 int nBits = n & 0x1f; 3257 int magLen = cast(int)mag.length; 3258 int[] newMag = null; 3259 3260 if (nBits == 0) { 3261 newMag = new int[magLen + nInts]; 3262 // System.arraycopy(mag, 0, newMag, 0, magLen); 3263 newMag[0..magLen] = mag[0..magLen].dup; 3264 } else { 3265 int i = 0; 3266 int nBits2 = 32 - nBits; 3267 int highBits = mag[0] >>> nBits2; 3268 if (highBits != 0) { 3269 newMag = new int[magLen + nInts + 1]; 3270 newMag[i++] = highBits; 3271 } else { 3272 newMag = new int[magLen + nInts]; 3273 } 3274 int j=0; 3275 while (j < magLen-1) 3276 newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2; 3277 newMag[i] = mag[j] << nBits; 3278 } 3279 return newMag; 3280 } 3281 3282 /** 3283 * Returns a BigInteger whose value is {@code (this >> n)}. Sign 3284 * extension is performed. The shift distance, {@code n}, may be 3285 * negative, in which case this method performs a left shift. 3286 * (Computes <code>floor(this / 2<sup>n</sup>)</code>.) 3287 * 3288 * @param n shift distance, in bits. 3289 * @return {@code this >> n} 3290 * @see #shiftLeft 3291 */ 3292 BigInteger shiftRight(int n) { 3293 if (_signum == 0) 3294 return ZERO; 3295 if (n > 0) { 3296 return shiftRightImpl(n); 3297 } else if (n == 0) { 3298 return this; 3299 } else { 3300 // Possible int overflow in {@code -n} is not a trouble, 3301 // because shiftLeft considers its argument unsigned 3302 return new BigInteger(shiftLeft(mag, -n), signum); 3303 } 3304 } 3305 3306 /** 3307 * Returns a BigInteger whose value is {@code (this >> n)}. The shift 3308 * distance, {@code n}, is considered unsigned. 3309 * (Computes <code>floor(this * 2<sup>-n</sup>)</code>.) 3310 * 3311 * @param n unsigned shift distance, in bits. 3312 * @return {@code this >> n} 3313 */ 3314 private BigInteger shiftRightImpl(int n) { 3315 int nInts = n >>> 5; 3316 int nBits = n & 0x1f; 3317 int magLen = cast(int)mag.length; 3318 int[] newMag = null; 3319 3320 // Special case: entire contents shifted off the end 3321 if (nInts >= magLen) 3322 return (signum >= 0 ? ZERO : negConst[1]); 3323 3324 if (nBits == 0) { 3325 int newMagLen = magLen - nInts; 3326 // newMag = Arrays.copyOf(mag, newMagLen); 3327 newMag = mag[0..newMagLen].dup; 3328 } else { 3329 int i = 0; 3330 int highBits = mag[0] >>> nBits; 3331 if (highBits != 0) { 3332 newMag = new int[magLen - nInts]; 3333 newMag[i++] = highBits; 3334 } else { 3335 newMag = new int[magLen - nInts -1]; 3336 } 3337 3338 int nBits2 = 32 - nBits; 3339 int j=0; 3340 while (j < magLen - nInts - 1) 3341 newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits); 3342 } 3343 3344 if (signum < 0) { 3345 // Find out whether any one-bits were shifted off the end. 3346 bool onesLost = false; 3347 for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--) 3348 onesLost = (mag[i] != 0); 3349 if (!onesLost && nBits != 0) 3350 onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0); 3351 3352 if (onesLost) 3353 newMag = javaIncrement(newMag); 3354 } 3355 3356 return new BigInteger(newMag, signum); 3357 } 3358 3359 int[] javaIncrement(int[] val) { 3360 int lastSum = 0; 3361 for (size_t i=val.length-1; i >= 0 && lastSum == 0; i--) 3362 lastSum = (val[i] += 1); 3363 if (lastSum == 0) { 3364 val = new int[val.length+1]; 3365 val[0] = 1; 3366 } 3367 return val; 3368 } 3369 3370 // Bitwise Operations 3371 3372 /** 3373 * Returns a BigInteger whose value is {@code (this & val)}. (This 3374 * method returns a negative BigInteger if and only if this and val are 3375 * both negative.) 3376 * 3377 * @param val value to be AND'ed with this BigInteger. 3378 * @return {@code this & val} 3379 */ 3380 BigInteger and(BigInteger val) { 3381 int[] result = new int[std.algorithm.max(intLength(), val.intLength())]; 3382 for (int i=0; i < cast(int)result.length; i++) 3383 result[i] = (getInt(cast(int)result.length-i-1) 3384 & val.getInt(cast(int)result.length-i-1)); 3385 3386 return valueOf(result); 3387 } 3388 3389 /** 3390 * Returns a BigInteger whose value is {@code (this | val)}. (This method 3391 * returns a negative BigInteger if and only if either this or val is 3392 * negative.) 3393 * 3394 * @param val value to be OR'ed with this BigInteger. 3395 * @return {@code this | val} 3396 */ 3397 BigInteger or(BigInteger val) { 3398 int[] result = new int[std.algorithm.max(intLength(), val.intLength())]; 3399 for (int i=0; i < cast(int)result.length; i++) 3400 result[i] = (getInt(cast(int)result.length-i-1) 3401 | val.getInt(cast(int)result.length-i-1)); 3402 3403 return valueOf(result); 3404 } 3405 3406 /** 3407 * Returns a BigInteger whose value is {@code (this ^ val)}. (This method 3408 * returns a negative BigInteger if and only if exactly one of this and 3409 * val are negative.) 3410 * 3411 * @param val value to be XOR'ed with this BigInteger. 3412 * @return {@code this ^ val} 3413 */ 3414 BigInteger xor(BigInteger val) { 3415 int[] result = new int[std.algorithm.max(intLength(), val.intLength())]; 3416 for (int i=0; i < cast(int)result.length; i++) 3417 result[i] = (getInt(cast(int)result.length-i-1) 3418 ^ val.getInt(cast(int)result.length-i-1)); 3419 3420 return valueOf(result); 3421 } 3422 3423 /** 3424 * Returns a BigInteger whose value is {@code (~this)}. (This method 3425 * returns a negative value if and only if this BigInteger is 3426 * non-negative.) 3427 * 3428 * @return {@code ~this} 3429 */ 3430 BigInteger not() { 3431 int[] result = new int[intLength()]; 3432 for (int i=0; i < cast(int)result.length; i++) 3433 result[i] = ~getInt(cast(int)result.length-i-1); 3434 3435 return valueOf(result); 3436 } 3437 3438 /** 3439 * Returns a BigInteger whose value is {@code (this & ~val)}. This 3440 * method, which is equivalent to {@code and(val.not())}, is provided as 3441 * a convenience for masking operations. (This method returns a negative 3442 * BigInteger if and only if {@code this} is negative and {@code val} is 3443 * positive.) 3444 * 3445 * @param val value to be complemented and AND'ed with this BigInteger. 3446 * @return {@code this & ~val} 3447 */ 3448 BigInteger andNot(BigInteger val) { 3449 int[] result = new int[std.algorithm.max(intLength(), val.intLength())]; 3450 for (int i=0; i < cast(int)result.length; i++) 3451 result[i] = (getInt(cast(int)result.length-i-1) 3452 & ~val.getInt(cast(int)result.length-i-1)); 3453 3454 return valueOf(result); 3455 } 3456 3457 3458 // Single Bit Operations 3459 3460 /** 3461 * Returns {@code true} if and only if the designated bit is set. 3462 * (Computes {@code ((this & (1<<n)) != 0)}.) 3463 * 3464 * @param n index of bit to test. 3465 * @return {@code true} if and only if the designated bit is set. 3466 * @throws ArithmeticException {@code n} is negative. 3467 */ 3468 bool testBit(int n) { 3469 if (n < 0) 3470 throw new ArithmeticException("Negative bit address"); 3471 3472 return (getInt(n >>> 5) & (1 << (n & 31))) != 0; 3473 } 3474 3475 /** 3476 * Returns a BigInteger whose value is equivalent to this BigInteger 3477 * with the designated bit set. (Computes {@code (this | (1<<n))}.) 3478 * 3479 * @param n index of bit to set. 3480 * @return {@code this | (1<<n)} 3481 * @throws ArithmeticException {@code n} is negative. 3482 */ 3483 BigInteger setBit(int n) { 3484 if (n < 0) 3485 throw new ArithmeticException("Negative bit address"); 3486 3487 int intNum = n >>> 5; 3488 int[] result = new int[std.algorithm.max(intLength(), intNum+2)]; 3489 3490 for (int i=0; i < cast(int)result.length; i++) 3491 result[result.length-i-1] = getInt(i); 3492 3493 result[result.length-intNum-1] |= (1 << (n & 31)); 3494 3495 return valueOf(result); 3496 } 3497 3498 /** 3499 * Returns a BigInteger whose value is equivalent to this BigInteger 3500 * with the designated bit cleared. 3501 * (Computes {@code (this & ~(1<<n))}.) 3502 * 3503 * @param n index of bit to clear. 3504 * @return {@code this & ~(1<<n)} 3505 * @throws ArithmeticException {@code n} is negative. 3506 */ 3507 BigInteger clearBit(int n) { 3508 if (n < 0) 3509 throw new ArithmeticException("Negative bit address"); 3510 3511 int intNum = n >>> 5; 3512 int[] result = new int[std.algorithm.max(intLength(), ((n + 1) >>> 5) + 1)]; 3513 3514 for (int i=0; i < cast(int)result.length; i++) 3515 result[result.length-i-1] = getInt(i); 3516 3517 result[result.length-intNum-1] &= ~(1 << (n & 31)); 3518 3519 return valueOf(result); 3520 } 3521 3522 /** 3523 * Returns a BigInteger whose value is equivalent to this BigInteger 3524 * with the designated bit flipped. 3525 * (Computes {@code (this ^ (1<<n))}.) 3526 * 3527 * @param n index of bit to flip. 3528 * @return {@code this ^ (1<<n)} 3529 * @throws ArithmeticException {@code n} is negative. 3530 */ 3531 BigInteger flipBit(int n) { 3532 if (n < 0) 3533 throw new ArithmeticException("Negative bit address"); 3534 3535 int intNum = n >>> 5; 3536 int[] result = new int[std.algorithm.max(intLength(), intNum+2)]; 3537 3538 for (int i=0; i < cast(int)result.length; i++) 3539 result[result.length-i-1] = getInt(i); 3540 3541 result[result.length-intNum-1] ^= (1 << (n & 31)); 3542 3543 return valueOf(result); 3544 } 3545 3546 /** 3547 * Returns the index of the rightmost (lowest-order) one bit in this 3548 * BigInteger (the number of zero bits to the right of the rightmost 3549 * one bit). Returns -1 if this BigInteger contains no one bits. 3550 * (Computes {@code (this == 0? -1 : log2(this & -this))}.) 3551 * 3552 * @return index of the rightmost one bit in this BigInteger. 3553 */ 3554 int getLowestSetBit() { 3555 int lsb = lowestSetBitPlusTwo - 2; 3556 if (lsb == -2) { // lowestSetBit not initialized yet 3557 lsb = 0; 3558 if (_signum == 0) { 3559 lsb -= 1; 3560 } else { 3561 // Search for lowest order nonzero int 3562 int i,b; 3563 for (i=0; (b = getInt(i)) == 0; i++) {} 3564 lsb += (i << 5) + Integer.numberOfTrailingZeros(b); 3565 } 3566 lowestSetBitPlusTwo = lsb + 2; 3567 } 3568 return lsb; 3569 } 3570 3571 3572 // Miscellaneous Bit Operations 3573 3574 /** 3575 * Returns the number of bits in the minimal two's-complement 3576 * representation of this BigInteger, <em>excluding</em> a sign bit. 3577 * For positive BigIntegers, this is equivalent to the number of bits in 3578 * the ordinary binary representation. (Computes 3579 * {@code (ceil(log2(this < 0 ? -this : this+1)))}.) 3580 * 3581 * @return number of bits in the minimal two's-complement 3582 * representation of this BigInteger, <em>excluding</em> a sign bit. 3583 */ 3584 int bitLength() { 3585 int n = bitLengthPlusOne - 1; 3586 if (n == -1) { // bitLength not initialized yet 3587 int[] m = mag; 3588 int len = cast(int)m.length; 3589 if (len == 0) { 3590 n = 0; // offset by one to initialize 3591 } else { 3592 // Calculate the bit length of the magnitude 3593 int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]); 3594 if (signum < 0) { 3595 // Check if magnitude is a power of two 3596 bool pow2 = (Integer.bitCount(mag[0]) == 1); 3597 for (int i=1; i< len && pow2; i++) 3598 pow2 = (mag[i] == 0); 3599 3600 n = (pow2 ? magBitLength -1 : magBitLength); 3601 } else { 3602 n = magBitLength; 3603 } 3604 } 3605 bitLengthPlusOne = n + 1; 3606 } 3607 return n; 3608 } 3609 3610 /** 3611 * Returns the number of bits in the two's complement representation 3612 * of this BigInteger that differ from its sign bit. This method is 3613 * useful when implementing bit-vector style sets atop BigIntegers. 3614 * 3615 * @return number of bits in the two's complement representation 3616 * of this BigInteger that differ from its sign bit. 3617 */ 3618 int bitCount() { 3619 int bc = bitCountPlusOne - 1; 3620 if (bc == -1) { // bitCount not initialized yet 3621 bc = 0; // offset by one to initialize 3622 // Count the bits in the magnitude 3623 for (int i=0; i < mag.length; i++) 3624 bc += Integer.bitCount(mag[i]); 3625 if (signum < 0) { 3626 // Count the trailing zeros in the magnitude 3627 int magTrailingZeroCount = 0, j; 3628 for (j=cast(int)mag.length-1; mag[j] == 0; j--) 3629 magTrailingZeroCount += 32; 3630 magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]); 3631 bc += magTrailingZeroCount - 1; 3632 } 3633 bitCountPlusOne = bc + 1; 3634 } 3635 return bc; 3636 } 3637 3638 // Primality Testing 3639 3640 /** 3641 * Returns {@code true} if this BigInteger is probably prime, 3642 * {@code false} if it's definitely composite. If 3643 * {@code certainty} is ≤ 0, {@code true} is 3644 * returned. 3645 * 3646 * @param certainty a measure of the uncertainty that the caller is 3647 * willing to tolerate: if the call returns {@code true} 3648 * the probability that this BigInteger is prime exceeds 3649 * (1 - 1/2<sup>{@code certainty}</sup>). The execution time of 3650 * this method is proportional to the value of this parameter. 3651 * @return {@code true} if this BigInteger is probably prime, 3652 * {@code false} if it's definitely composite. 3653 */ 3654 bool isProbablePrime(int certainty) { 3655 if (certainty <= 0) 3656 return true; 3657 BigInteger w = this.abs(); 3658 if (w.equals(TWO)) 3659 return true; 3660 if (!w.testBit(0) || w.equals(ONE)) 3661 return false; 3662 3663 return w.primeToCertainty(certainty, null); 3664 } 3665 3666 // Comparison Operations 3667 3668 /** 3669 * Compares this BigInteger with the specified BigInteger. This 3670 * method is provided in preference to individual methods for each 3671 * of the six bool comparison operators ({@literal <}, ==, 3672 * {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested 3673 * idiom for performing these comparisons is: {@code 3674 * (x.compareTo(y)} <<i>op</i>> {@code 0)}, where 3675 * <<i>op</i>> is one of the six comparison operators. 3676 * 3677 * @param val BigInteger to which this BigInteger is to be compared. 3678 * @return -1, 0 or 1 as this BigInteger is numerically less than, equal 3679 * to, or greater than {@code val}. 3680 */ 3681 int compareTo(BigInteger val) { 3682 if (_signum == val.signum) { 3683 switch (signum) { 3684 case 1: 3685 return compareMagnitude(val); 3686 case -1: 3687 return val.compareMagnitude(this); 3688 default: 3689 return 0; 3690 } 3691 } 3692 return signum > val.signum ? 1 : -1; 3693 } 3694 3695 /** 3696 * Compares the magnitude array of this BigInteger with the specified 3697 * BigInteger's. This is the version of compareTo ignoring sign. 3698 * 3699 * @param val BigInteger whose magnitude array to be compared. 3700 * @return -1, 0 or 1 as this magnitude array is less than, equal to or 3701 * greater than the magnitude aray for the specified BigInteger's. 3702 */ 3703 final int compareMagnitude(BigInteger val) { 3704 int[] m1 = mag; 3705 int len1 = cast(int)m1.length; 3706 int[] m2 = val.mag; 3707 int len2 = cast(int)m2.length; 3708 if (len1 < len2) 3709 return -1; 3710 if (len1 > len2) 3711 return 1; 3712 for (int i = 0; i < len1; i++) { 3713 int a = m1[i]; 3714 int b = m2[i]; 3715 if (a != b) 3716 return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1; 3717 } 3718 return 0; 3719 } 3720 3721 /** 3722 * Version of compareMagnitude that compares magnitude with long value. 3723 * val can't be long.min. 3724 */ 3725 final int compareMagnitude(long val) { 3726 assert(val != long.min); 3727 int[] m1 = mag; 3728 int len = cast(int)m1.length; 3729 if (len > 2) { 3730 return 1; 3731 } 3732 if (val < 0) { 3733 val = -val; 3734 } 3735 int highWord = cast(int)(val >>> 32); 3736 if (highWord == 0) { 3737 if (len < 1) 3738 return -1; 3739 if (len > 1) 3740 return 1; 3741 int a = m1[0]; 3742 int b = cast(int)val; 3743 if (a != b) { 3744 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1; 3745 } 3746 return 0; 3747 } else { 3748 if (len < 2) 3749 return -1; 3750 int a = m1[0]; 3751 int b = highWord; 3752 if (a != b) { 3753 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1; 3754 } 3755 a = m1[1]; 3756 b = cast(int)val; 3757 if (a != b) { 3758 return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1; 3759 } 3760 return 0; 3761 } 3762 } 3763 3764 /** 3765 * Compares this BigInteger with the specified Object for equality. 3766 * 3767 * @param x Object to which this BigInteger is to be compared. 3768 * @return {@code true} if and only if the specified Object is a 3769 * BigInteger whose value is numerically equal to this BigInteger. 3770 */ 3771 bool equals(Object x) { 3772 return opEquals(x); 3773 } 3774 3775 override bool opEquals(Object x) { 3776 // This test is just an optimization, which may or may not help 3777 if (x is this) 3778 return true; 3779 3780 BigInteger xInt = cast(BigInteger) x; 3781 if(xInt is null) 3782 return false; 3783 if (xInt.signum != signum) 3784 return false; 3785 3786 int[] m = mag; 3787 int len = cast(int)m.length; 3788 int[] xm = xInt.mag; 3789 if (len != xm.length) 3790 return false; 3791 3792 for (int i = 0; i < len; i++) 3793 if (xm[i] != m[i]) 3794 return false; 3795 3796 return true; 3797 } 3798 3799 /** 3800 * Returns the minimum of this BigInteger and {@code val}. 3801 * 3802 * @param val value with which the minimum is to be computed. 3803 * @return the BigInteger whose value is the lesser of this BigInteger and 3804 * {@code val}. If they are equal, either may be returned. 3805 */ 3806 BigInteger min(BigInteger val) { 3807 return (compareTo(val) < 0 ? this : val); 3808 } 3809 3810 /** 3811 * Returns the maximum of this BigInteger and {@code val}. 3812 * 3813 * @param val value with which the maximum is to be computed. 3814 * @return the BigInteger whose value is the greater of this and 3815 * {@code val}. If they are equal, either may be returned. 3816 */ 3817 BigInteger max(BigInteger val) { 3818 return (compareTo(val) > 0 ? this : val); 3819 } 3820 3821 3822 // Hash Function 3823 3824 /** 3825 * Returns the hash code for this BigInteger. 3826 * 3827 * @return hash code for this BigInteger. 3828 */ 3829 size_t hashCode() { 3830 return toHash(); 3831 } 3832 3833 override size_t toHash() @trusted nothrow { 3834 size_t hashCode = 0; 3835 3836 for (size_t i=0; i < mag.length; i++) 3837 hashCode = cast(size_t)(31*hashCode + (mag[i] & LONG_MASK)); 3838 3839 return hashCode * _signum; 3840 } 3841 3842 /** 3843 * Returns the string representation of this BigInteger in the 3844 * given radix. If the radix is outside the range from {@link 3845 * Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive, 3846 * it will default to 10 (as is the case for 3847 * {@code Integer.toString}). The digit-to-character mapping 3848 * provided by {@code Char.forDigit} is used, and a minus 3849 * sign is prepended if appropriate. (This representation is 3850 * compatible with the {@link #BigInteger(string, int) (string, 3851 * int)} constructor.) 3852 * 3853 * @param radix radix of the string representation. 3854 * @return string representation of this BigInteger in the given radix. 3855 * @see Integer#toString 3856 * @see Character#forDigit 3857 * @see #BigInteger(java.lang.string, int) 3858 */ 3859 string toString(int radix) { 3860 if (_signum == 0) 3861 return "0"; 3862 if (radix < Char.MIN_RADIX || radix > Char.MAX_RADIX) 3863 radix = 10; 3864 3865 // If it's small enough, use smallToString. 3866 if (mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) 3867 return smallToString(radix); 3868 3869 // Otherwise use recursive toString, which requires positive arguments. 3870 // The results will be concatenated into this StringBuilder 3871 StringBuilder sb = new StringBuilder(); 3872 string r; 3873 if (signum < 0) { 3874 toString(this.negate(), sb, radix, 0); 3875 // sb.insert(0, '-'); 3876 r = "-" ~ sb.toString(); 3877 } 3878 else { 3879 toString(this, sb, radix, 0); 3880 r = sb.toString(); 3881 } 3882 3883 return r; 3884 } 3885 3886 /** This method is used to perform toString when arguments are small. */ 3887 private string smallToString(int radix) { 3888 if (_signum == 0) { 3889 return "0"; 3890 } 3891 3892 // Compute upper bound on number of digit groups and allocate space 3893 int maxNumDigitGroups = cast(int)(4*mag.length + 6)/7; 3894 string[] digitGroup = new string[maxNumDigitGroups]; 3895 3896 // Translate number to string, a digit group at a time 3897 BigInteger tmp = this.abs(); 3898 int numGroups = 0; 3899 while (tmp.signum != 0) { 3900 BigInteger d = longRadix[radix]; 3901 3902 MutableBigInteger q = new MutableBigInteger(), 3903 a = new MutableBigInteger(tmp.mag), 3904 b = new MutableBigInteger(d.mag); 3905 MutableBigInteger r = a.divide(b, q); 3906 BigInteger q2 = q.toBigInteger(tmp.signum * d.signum); 3907 BigInteger r2 = r.toBigInteger(tmp.signum * d.signum); 3908 3909 digitGroup[numGroups++] = to!string(r2.longValue(), radix); 3910 tmp = q2; 3911 } 3912 3913 // Put sign (if any) and first digit group into result buffer 3914 StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1); 3915 if (signum < 0) { 3916 buf.append('-'); 3917 } 3918 buf.append(digitGroup[numGroups-1]); 3919 3920 // Append remaining digit groups padded with leading zeros 3921 for (int i=numGroups-2; i >= 0; i--) { 3922 // Prepend (any) leading zeros for this digit group 3923 int numLeadingZeros = digitsPerLong[radix] - cast(int)digitGroup[i].length; 3924 if (numLeadingZeros != 0) { 3925 buf.append(zeros[numLeadingZeros]); 3926 } 3927 buf.append(digitGroup[i]); 3928 } 3929 return buf.toString(); 3930 } 3931 3932 /** 3933 * Converts the specified BigInteger to a string and appends to 3934 * {@code sb}. This implements the recursive Schoenhage algorithm 3935 * for base conversions. 3936 * <p> 3937 * See Knuth, Donald, _The Art of Computer Programming_, Vol. 2, 3938 * Answers to Exercises (4.4) Question 14. 3939 * 3940 * @param u The number to convert to a string. 3941 * @param sb The StringBuilder that will be appended to in place. 3942 * @param radix The base to convert to. 3943 * @param digits The minimum number of digits to pad to. 3944 */ 3945 private static void toString(BigInteger u, StringBuilder sb, int radix, 3946 int digits) { 3947 // If we're smaller than a certain threshold, use the smallToString 3948 // method, padding with leading zeroes when necessary. 3949 if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) { 3950 string s = u.smallToString(radix); 3951 3952 // Pad with internal zeros if necessary. 3953 // Don't pad if we're at the beginning of the string. 3954 if ((s.length < digits) && (sb.length > 0)) { 3955 for (size_t i=s.length; i < digits; i++) { 3956 sb.append('0'); 3957 } 3958 } 3959 3960 sb.append(s); 3961 return; 3962 } 3963 3964 int b, n; 3965 b = u.bitLength(); 3966 3967 // Calculate a value for n in the equation radix^(2^n) = u 3968 // and subtract 1 from that value. This is used to find the 3969 // cache index that contains the best value to divide u. 3970 n = cast(int) std.math.round(std.math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0); 3971 BigInteger v = getRadixConversionCache(radix, n); 3972 BigInteger[] results; 3973 results = u.divideAndRemainder(v); 3974 3975 int expectedDigits = 1 << n; 3976 3977 // Now recursively build the two halves of each number. 3978 toString(results[0], sb, radix, digits-expectedDigits); 3979 toString(results[1], sb, radix, expectedDigits); 3980 } 3981 3982 /** 3983 * Returns the value radix^(2^exponent) from the cache. 3984 * If this value doesn't already exist in the cache, it is added. 3985 * <p> 3986 * This could be changed to a more complicated caching method using 3987 * {@code Future}. 3988 */ 3989 private static BigInteger getRadixConversionCache(int radix, int exponent) { 3990 BigInteger[] cacheLine = powerCache[radix]; // read 3991 if (exponent < cacheLine.length) { 3992 return cacheLine[exponent]; 3993 } 3994 3995 int oldLength = cast(int)cacheLine.length; 3996 BigInteger[] oldCacheLine = cacheLine; 3997 cacheLine = new BigInteger[exponent + 1]; 3998 cacheLine[0..oldLength] = oldCacheLine[0..$]; 3999 // cacheLine = Arrays.copyOf(cacheLine, exponent + 1); 4000 for (int i = oldLength; i <= exponent; i++) { 4001 cacheLine[i] = cacheLine[i - 1].pow(2); 4002 } 4003 4004 BigInteger[][] pc = powerCache; // read again 4005 if (exponent >= pc[radix].length) { 4006 pc = pc.dup; 4007 pc[radix] = cacheLine; 4008 powerCache = pc; // write, publish 4009 } 4010 return cacheLine[exponent]; 4011 } 4012 4013 /* zero[i] is a string of i consecutive zeros. */ 4014 private __gshared static string[] zeros; 4015 shared static this() { 4016 zeros = new string[64]; 4017 zeros[63] = "000000000000000000000000000000000000000000000000000000000000000"; 4018 for (int i=0; i < 63; i++) 4019 zeros[i] = zeros[63][0 .. i]; 4020 } 4021 4022 /** 4023 * Returns the decimal string representation of this BigInteger. 4024 * The digit-to-character mapping provided by 4025 * {@code Char.forDigit} is used, and a minus sign is 4026 * prepended if appropriate. (This representation is compatible 4027 * with the {@link #BigInteger(string) (string)} constructor, and 4028 * allows for string concatenation with Java's + operator.) 4029 * 4030 * @return decimal string representation of this BigInteger. 4031 * @see Character#forDigit 4032 * @see #BigInteger(java.lang.string) 4033 */ 4034 override string toString() { 4035 return toString(10); 4036 } 4037 4038 /** 4039 * Returns a byte array containing the two's-complement 4040 * representation of this BigInteger. The byte array will be in 4041 * <i>big-endian</i> byte-order: the most significant byte is in 4042 * the zeroth element. The array will contain the minimum number 4043 * of bytes required to represent this BigInteger, including at 4044 * least one sign bit, which is {@code (ceil((this.bitLength() + 4045 * 1)/8))}. (This representation is compatible with the 4046 * {@link #BigInteger(byte[]) (byte[])} constructor.) 4047 * 4048 * @return a byte array containing the two's-complement representation of 4049 * this BigInteger. 4050 * @see #BigInteger(byte[]) 4051 */ 4052 byte[] toByteArray() { 4053 int byteLen = bitLength()/8 + 1; 4054 byte[] byteArray = new byte[byteLen]; 4055 4056 for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) { 4057 if (bytesCopied == 4) { 4058 nextInt = getInt(intIndex++); 4059 bytesCopied = 1; 4060 } else { 4061 nextInt >>>= 8; 4062 bytesCopied++; 4063 } 4064 byteArray[i] = cast(byte)nextInt; 4065 } 4066 return byteArray; 4067 } 4068 4069 /** 4070 * Converts this BigInteger to an {@code int}. This 4071 * conversion is analogous to a 4072 * <i>narrowing primitive conversion</i> from {@code long} to 4073 * {@code int} as defined in 4074 * <cite>The Java™ Language Specification</cite>: 4075 * if this BigInteger is too big to fit in an 4076 * {@code int}, only the low-order 32 bits are returned. 4077 * Note that this conversion can lose information about the 4078 * overall magnitude of the BigInteger value as well as return a 4079 * result with the opposite sign. 4080 * 4081 * @return this BigInteger converted to an {@code int}. 4082 * @see #intValueExact() 4083 * @jls 5.1.3 Narrowing Primitive Conversion 4084 */ 4085 int intValue() { 4086 int result = 0; 4087 result = getInt(0); 4088 return result; 4089 } 4090 4091 /** 4092 * Converts this BigInteger to a {@code long}. This 4093 * conversion is analogous to a 4094 * <i>narrowing primitive conversion</i> from {@code long} to 4095 * {@code int} as defined in 4096 * <cite>The Java™ Language Specification</cite>: 4097 * if this BigInteger is too big to fit in a 4098 * {@code long}, only the low-order 64 bits are returned. 4099 * Note that this conversion can lose information about the 4100 * overall magnitude of the BigInteger value as well as return a 4101 * result with the opposite sign. 4102 * 4103 * @return this BigInteger converted to a {@code long}. 4104 * @see #longValueExact() 4105 * @jls 5.1.3 Narrowing Primitive Conversion 4106 */ 4107 long longValue() { 4108 long result = 0; 4109 4110 for (int i=1; i >= 0; i--) 4111 result = (result << 32) + (getInt(i) & LONG_MASK); 4112 return result; 4113 } 4114 4115 /** 4116 * Converts this BigInteger to a {@code float}. This 4117 * conversion is similar to the 4118 * <i>narrowing primitive conversion</i> from {@code double} to 4119 * {@code float} as defined in 4120 * <cite>The Java™ Language Specification</cite>: 4121 * if this BigInteger has too great a magnitude 4122 * to represent as a {@code float}, it will be converted to 4123 * {@link Float#NEGATIVE_INFINITY} or {@link 4124 * Float#POSITIVE_INFINITY} as appropriate. Note that even when 4125 * the return value is finite, this conversion can lose 4126 * information about the precision of the BigInteger value. 4127 * 4128 * @return this BigInteger converted to a {@code float}. 4129 * @jls 5.1.3 Narrowing Primitive Conversion 4130 */ 4131 float floatValue() { 4132 if (_signum == 0) { 4133 return 0.0f; 4134 } 4135 4136 int exponent =cast(int)(cast(int)(mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1; 4137 4138 // exponent == floor(log2(abs(this))) 4139 if (exponent < Long.SIZE - 1) { 4140 return longValue(); 4141 } else if (exponent > Float.MAX_EXPONENT) { 4142 return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY; 4143 } 4144 4145 /* 4146 * We need the top SIGNIFICAND_WIDTH bits, including the "implicit" 4147 * one bit. To make rounding easier, we pick out the top 4148 * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or 4149 * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1 4150 * bits, and signifFloor the top SIGNIFICAND_WIDTH. 4151 * 4152 * It helps to consider the real number signif = abs(this) * 4153 * 2^(SIGNIFICAND_WIDTH - 1 - exponent). 4154 */ 4155 int shift = exponent - FloatConsts.SIGNIFICAND_WIDTH; 4156 4157 int twiceSignifFloor; 4158 // twiceSignifFloor will be == abs().shiftRight(shift).intValue() 4159 // We do the shift into an int directly to improve performance. 4160 4161 int nBits = shift & 0x1f; 4162 int nBits2 = 32 - nBits; 4163 4164 if (nBits == 0) { 4165 twiceSignifFloor = mag[0]; 4166 } else { 4167 twiceSignifFloor = mag[0] >>> nBits; 4168 if (twiceSignifFloor == 0) { 4169 twiceSignifFloor = (mag[0] << nBits2) | (mag[1] >>> nBits); 4170 } 4171 } 4172 4173 int signifFloor = twiceSignifFloor >> 1; 4174 signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit 4175 4176 /* 4177 * We round up if either the fractional part of signif is strictly 4178 * greater than 0.5 (which is true if the 0.5 bit is set and any lower 4179 * bit is set), or if the fractional part of signif is >= 0.5 and 4180 * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit 4181 * are set). This is equivalent to the desired HALF_EVEN rounding. 4182 */ 4183 bool increment = (twiceSignifFloor & 1) != 0 4184 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift); 4185 int signifRounded = increment ? signifFloor + 1 : signifFloor; 4186 int bits = ((exponent + FloatConsts.EXP_BIAS)) 4187 << (FloatConsts.SIGNIFICAND_WIDTH - 1); 4188 bits += signifRounded; 4189 /* 4190 * If signifRounded == 2^24, we'd need to set all of the significand 4191 * bits to zero and add 1 to the exponent. This is exactly the behavior 4192 * we get from just adding signifRounded to bits directly. If the 4193 * exponent is Float.MAX_EXPONENT, we round up (correctly) to 4194 * Float.POSITIVE_INFINITY. 4195 */ 4196 bits |= signum & FloatConsts.SIGN_BIT_MASK; 4197 return Float.intBitsToFloat(bits); 4198 } 4199 4200 /** 4201 * Converts this BigInteger to a {@code double}. This 4202 * conversion is similar to the 4203 * <i>narrowing primitive conversion</i> from {@code double} to 4204 * {@code float} as defined in 4205 * <cite>The Java™ Language Specification</cite>: 4206 * if this BigInteger has too great a magnitude 4207 * to represent as a {@code double}, it will be converted to 4208 * {@link Double#NEGATIVE_INFINITY} or {@link 4209 * Double#POSITIVE_INFINITY} as appropriate. Note that even when 4210 * the return value is finite, this conversion can lose 4211 * information about the precision of the BigInteger value. 4212 * 4213 * @return this BigInteger converted to a {@code double}. 4214 * @jls 5.1.3 Narrowing Primitive Conversion 4215 */ 4216 double doubleValue() { 4217 if (_signum == 0) { 4218 return 0.0; 4219 } 4220 4221 int exponent = (cast(int)(mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1; 4222 4223 // exponent == floor(log2(abs(this))Double) 4224 if (exponent < Long.SIZE - 1) { 4225 return longValue(); 4226 } else if (exponent > Double.MAX_EXPONENT) { 4227 return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY; 4228 } 4229 4230 /* 4231 * We need the top SIGNIFICAND_WIDTH bits, including the "implicit" 4232 * one bit. To make rounding easier, we pick out the top 4233 * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or 4234 * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1 4235 * bits, and signifFloor the top SIGNIFICAND_WIDTH. 4236 * 4237 * It helps to consider the real number signif = abs(this) * 4238 * 2^(SIGNIFICAND_WIDTH - 1 - exponent). 4239 */ 4240 int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH; 4241 4242 long twiceSignifFloor; 4243 // twiceSignifFloor will be == abs().shiftRight(shift).longValue() 4244 // We do the shift into a long directly to improve performance. 4245 4246 int nBits = shift & 0x1f; 4247 int nBits2 = 32 - nBits; 4248 4249 int highBits; 4250 int lowBits; 4251 if (nBits == 0) { 4252 highBits = mag[0]; 4253 lowBits = mag[1]; 4254 } else { 4255 highBits = mag[0] >>> nBits; 4256 lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits); 4257 if (highBits == 0) { 4258 highBits = lowBits; 4259 lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits); 4260 } 4261 } 4262 4263 twiceSignifFloor = ((highBits & LONG_MASK) << 32) 4264 | (lowBits & LONG_MASK); 4265 4266 long signifFloor = twiceSignifFloor >> 1; 4267 signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit 4268 4269 /* 4270 * We round up if either the fractional part of signif is strictly 4271 * greater than 0.5 (which is true if the 0.5 bit is set and any lower 4272 * bit is set), or if the fractional part of signif is >= 0.5 and 4273 * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit 4274 * are set). This is equivalent to the desired HALF_EVEN rounding. 4275 */ 4276 bool increment = (twiceSignifFloor & 1) != 0 4277 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift); 4278 long signifRounded = increment ? signifFloor + 1 : signifFloor; 4279 long bits = cast(long) ((exponent + DoubleConsts.EXP_BIAS)) 4280 << (DoubleConsts.SIGNIFICAND_WIDTH - 1); 4281 bits += signifRounded; 4282 /* 4283 * If signifRounded == 2^53, we'd need to set all of the significand 4284 * bits to zero and add 1 to the exponent. This is exactly the behavior 4285 * we get from just adding signifRounded to bits directly. If the 4286 * exponent is Double.MAX_EXPONENT, we round up (correctly) to 4287 * Double.POSITIVE_INFINITY. 4288 */ 4289 bits |= signum & DoubleConsts.SIGN_BIT_MASK; 4290 return Double.longBitsToDouble(bits); 4291 } 4292 4293 4294 byte byteValue() { 4295 return cast(byte) intValue(); 4296 } 4297 4298 short shortValue() { 4299 return cast(short) intValue(); 4300 } 4301 4302 /** 4303 * Returns a copy of the input array stripped of any leading zero bytes. 4304 */ 4305 private static int[] stripLeadingZeroInts(int[] val) { 4306 int vlen = cast(int)val.length; 4307 int keep; 4308 4309 // Find first nonzero byte 4310 for (keep = 0; keep < vlen && val[keep] == 0; keep++){} 4311 return val[keep .. vlen].dup; // java.util.Arrays.copyOfRange(val, keep, vlen); 4312 } 4313 4314 /** 4315 * Returns the input array stripped of any leading zero bytes. 4316 * Since the source is trusted the copying may be skipped. 4317 */ 4318 private static int[] trustedStripLeadingZeroInts(int[] val) { 4319 int vlen = cast(int)val.length; 4320 int keep; 4321 4322 // Find first nonzero byte 4323 for (keep = 0; keep < vlen && val[keep] == 0; keep++){} 4324 return keep == 0 ? val : val[keep .. vlen].dup; // java.util.Arrays.copyOfRange(val, keep, vlen); 4325 } 4326 4327 /** 4328 * Returns a copy of the input array stripped of any leading zero bytes. 4329 */ 4330 private static int[] stripLeadingZeroBytes(byte[] a, int off, int len) { 4331 int indexBound = off + len; 4332 int keep; 4333 4334 // Find first nonzero byte 4335 for (keep = off; keep < indexBound && a[keep] == 0; keep++){} 4336 4337 // Allocate new array and copy relevant part of input array 4338 int intLength = ((indexBound - keep) + 3) >>> 2; 4339 int[] result = new int[intLength]; 4340 int b = indexBound - 1; 4341 for (int i = intLength-1; i >= 0; i--) { 4342 result[i] = a[b--] & 0xff; 4343 int bytesRemaining = b - keep + 1; 4344 int bytesToTransfer = std.algorithm.min(3, bytesRemaining); 4345 for (int j=8; j <= (bytesToTransfer << 3); j += 8) 4346 result[i] |= ((a[b--] & 0xff) << j); 4347 } 4348 return result; 4349 } 4350 4351 /** 4352 * Takes an array a representing a negative 2's-complement number and 4353 * returns the minimal (no leading zero bytes) unsigned whose value is -a. 4354 */ 4355 private static int[] makePositive(byte[] a, int off, int len) { 4356 int keep, k; 4357 int indexBound = off + len; 4358 4359 // Find first non-sign (0xff) byte of input 4360 for (keep=off; keep < indexBound && a[keep] == -1; keep++) {} 4361 4362 4363 /* Allocate output array. If all non-sign bytes are 0x00, we must 4364 * allocate space for one extra output byte. */ 4365 for (k=keep; k < indexBound && a[k] == 0; k++) {} 4366 4367 int extraByte = (k == indexBound) ? 1 : 0; 4368 int intLength = ((indexBound - keep + extraByte) + 3) >>> 2; 4369 int[] result = new int[intLength]; 4370 4371 /* Copy one's complement of input into output, leaving extra 4372 * byte (if it exists) == 0x00 */ 4373 int b = indexBound - 1; 4374 for (int i = intLength-1; i >= 0; i--) { 4375 result[i] = a[b--] & 0xff; 4376 int numBytesToTransfer = std.algorithm.min(3, b-keep+1); 4377 if (numBytesToTransfer < 0) 4378 numBytesToTransfer = 0; 4379 for (int j=8; j <= 8*numBytesToTransfer; j += 8) 4380 result[i] |= ((a[b--] & 0xff) << j); 4381 4382 // Mask indicates which bits must be complemented 4383 int mask = -1 >>> (8*(3-numBytesToTransfer)); 4384 result[i] = ~result[i] & mask; 4385 } 4386 4387 // Add one to one's complement to generate two's complement 4388 for (size_t i=result.length-1; i >= 0; i--) { 4389 result[i] = cast(int)((result[i] & LONG_MASK) + 1); 4390 if (result[i] != 0) 4391 break; 4392 } 4393 4394 return result; 4395 } 4396 4397 /** 4398 * Takes an array a representing a negative 2's-complement number and 4399 * returns the minimal (no leading zero ints) unsigned whose value is -a. 4400 */ 4401 private static int[] makePositive(int[] a) { 4402 int keep, j; 4403 4404 // Find first non-sign (0xffffffff) int of input 4405 for (keep=0; keep < a.length && a[keep] == -1; keep++){} 4406 4407 /* Allocate output array. If all non-sign ints are 0x00, we must 4408 * allocate space for one extra output int. */ 4409 for (j=keep; j < a.length && a[j] == 0; j++){} 4410 int extraInt = (j == a.length ? 1 : 0); 4411 int[] result = new int[a.length - keep + extraInt]; 4412 4413 /* Copy one's complement of input into output, leaving extra 4414 * int (if it exists) == 0x00 */ 4415 for (int i = keep; i < a.length; i++) 4416 result[i - keep + extraInt] = ~a[i]; 4417 4418 // Add one to one's complement to generate two's complement 4419 for (size_t i=result.length-1; ++result[i] == 0; i--){} 4420 4421 return result; 4422 } 4423 4424 /* 4425 * The following two arrays are used for fast string conversions. Both 4426 * are indexed by radix. The first is the number of digits of the given 4427 * radix that can fit in a Java long without "going negative", i.e., the 4428 * highest integer n such that radix**n < 2**63. The second is the 4429 * "long radix" that tears each number into "long digits", each of which 4430 * consists of the number of digits in the corresponding element in 4431 * digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have 4432 * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not 4433 * used. 4434 */ 4435 private static int[] digitsPerLong = [0, 0, 4436 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14, 4437 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12]; 4438 4439 private __gshared static BigInteger[] longRadix; 4440 4441 shared static this() { 4442 longRadix = [null, null, 4443 valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL), 4444 valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL), 4445 valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L), 4446 valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L), 4447 valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L), 4448 valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL), 4449 valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L), 4450 valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L), 4451 valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L), 4452 valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L), 4453 valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L), 4454 valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L), 4455 valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL), 4456 valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L), 4457 valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L), 4458 valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L), 4459 valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L), 4460 valueOf(0x41c21cb8e1000000L)]; 4461 } 4462 4463 /* 4464 * These two arrays are the integer analogue of above. 4465 */ 4466 private enum int[] digitsPerInt = [0, 0, 30, 19, 15, 13, 11, 4467 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 4468 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5]; 4469 4470 private enum int[] intRadix =[0, 0, 4471 0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800, 4472 0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61, 4473 0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000, 4474 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d, 4475 0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40, 4476 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41, 4477 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400 4478 ]; 4479 4480 /** 4481 * These routines provide access to the two's complement representation 4482 * of BigIntegers. 4483 */ 4484 4485 /** 4486 * Returns the length of the two's complement representation in ints, 4487 * including space for at least one sign bit. 4488 */ 4489 private int intLength() { 4490 return (bitLength() >>> 5) + 1; 4491 } 4492 4493 /* Returns sign bit */ 4494 private int signBit() { 4495 return signum < 0 ? 1 : 0; 4496 } 4497 4498 /* Returns an int of sign bits */ 4499 private int signInt() { 4500 return signum < 0 ? -1 : 0; 4501 } 4502 4503 /** 4504 * Returns the specified int of the little-endian two's complement 4505 * representation (int 0 is the least significant). The int number can 4506 * be arbitrarily high (values are logically preceded by infinitely many 4507 * sign ints). 4508 */ 4509 private int getInt(int n) { 4510 if (n < 0) 4511 return 0; 4512 if (n >= cast(int)mag.length) 4513 return signInt(); 4514 4515 int magInt = mag[mag.length-n-1]; 4516 4517 return (signum >= 0 ? magInt : 4518 (n <= firstNonzeroIntNum() ? -magInt : ~magInt)); 4519 } 4520 4521 /** 4522 * Returns the index of the int that contains the first nonzero int in the 4523 * little-endian binary representation of the magnitude (int 0 is the 4524 * least significant). If the magnitude is zero, return value is undefined. 4525 * 4526 * <p>Note: never used for a BigInteger with a magnitude of zero. 4527 * @see #getInt. 4528 */ 4529 private int firstNonzeroIntNum() { 4530 int fn = firstNonzeroIntNumPlusTwo - 2; 4531 if (fn == -2) { // firstNonzeroIntNum not initialized yet 4532 // Search for the first nonzero int 4533 int i; 4534 int mlen = cast(int)mag.length; 4535 for (i = mlen - 1; i >= 0 && mag[i] == 0; i--) {} 4536 fn = mlen - i - 1; 4537 firstNonzeroIntNumPlusTwo = fn + 2; // offset by two to initialize 4538 } 4539 return fn; 4540 } 4541 4542 /** use serialVersionUID from JDK 1.1. for interoperability */ 4543 // private static final long serialVersionUID = -8287574255936472291L; 4544 4545 /** 4546 * Serializable fields for BigInteger. 4547 * 4548 * @serialField signum int 4549 * signum of this BigInteger 4550 * @serialField magnitude byte[] 4551 * magnitude array of this BigInteger 4552 * @serialField bitCount int 4553 * appears in the serialized form for backward compatibility 4554 * @serialField bitLength int 4555 * appears in the serialized form for backward compatibility 4556 * @serialField firstNonzeroByteNum int 4557 * appears in the serialized form for backward compatibility 4558 * @serialField lowestSetBit int 4559 * appears in the serialized form for backward compatibility 4560 */ 4561 // private static final ObjectStreamField[] serialPersistentFields = { 4562 // new ObjectStreamField("signum", Integer.TYPE), 4563 // new ObjectStreamField("magnitude", byte[].class), 4564 // new ObjectStreamField("bitCount", Integer.TYPE), 4565 // new ObjectStreamField("bitLength", Integer.TYPE), 4566 // new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE), 4567 // new ObjectStreamField("lowestSetBit", Integer.TYPE) 4568 // }; 4569 4570 /** 4571 * Reconstitute the {@code BigInteger} instance from a stream (that is, 4572 * deserialize it). The magnitude is read in as an array of bytes 4573 * for historical reasons, but it is converted to an array of ints 4574 * and the byte array is discarded. 4575 * Note: 4576 * The current convention is to initialize the cache fields, bitCountPlusOne, 4577 * bitLengthPlusOne and lowestSetBitPlusTwo, to 0 rather than some other 4578 * marker value. Therefore, no explicit action to set these fields needs to 4579 * be taken in readObject because those fields already have a 0 value by 4580 * default since defaultReadObject is not being used. 4581 */ 4582 // private void readObject(java.io.ObjectInputStream s) 4583 // throws java.io.IOException, ClassNotFoundException { 4584 // // prepare to read the alternate persistent fields 4585 // ObjectInputStream.GetField fields = s.readFields(); 4586 4587 // // Read the alternate persistent fields that we care about 4588 // int sign = fields.get("signum", -2); 4589 // byte[] magnitude = (byte[])fields.get("magnitude", null); 4590 4591 // // Validate signum 4592 // if (sign < -1 || sign > 1) { 4593 // string message = "BigInteger: Invalid signum value"; 4594 // if (fields.defaulted("signum")) 4595 // message = "BigInteger: Signum not present in stream"; 4596 // throw new java.io.StreamCorruptedException(message); 4597 // } 4598 // int[] mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length); 4599 // if (cast(int)(mag.length == 0) != (sign == 0)) { 4600 // string message = "BigInteger: signum-magnitude mismatch"; 4601 // if (fields.defaulted("magnitude")) 4602 // message = "BigInteger: Magnitude not present in stream"; 4603 // throw new java.io.StreamCorruptedException(message); 4604 // } 4605 4606 // // Commit final fields via Unsafe 4607 // UnsafeHolder.putSign(this, sign); 4608 4609 // // Calculate mag field from magnitude and discard magnitude 4610 // UnsafeHolder.putMag(this, mag); 4611 // if (mag.length >= MAX_MAG_LENGTH) { 4612 // try { 4613 // checkRange(); 4614 // } catch (ArithmeticException e) { 4615 // throw new java.io.StreamCorruptedException("BigInteger: Out of the supported range"); 4616 // } 4617 // } 4618 // } 4619 4620 // // Support for resetting final fields while deserializing 4621 // private static class UnsafeHolder { 4622 // private static final jdk.internal.misc.Unsafe unsafe 4623 // = jdk.internal.misc.Unsafe.getUnsafe(); 4624 // private static final long signumOffset 4625 // = unsafe.objectFieldOffset(BigInteger.class, "signum"); 4626 // private static final long magOffset 4627 // = unsafe.objectFieldOffset(BigInteger.class, "mag"); 4628 4629 // static void putSign(BigInteger bi, int sign) { 4630 // unsafe.putInt(bi, signumOffset, sign); 4631 // } 4632 4633 // static void putMag(BigInteger bi, int[] magnitude) { 4634 // unsafe.putObject(bi, magOffset, magnitude); 4635 // } 4636 // } 4637 4638 /** 4639 * Save the {@code BigInteger} instance to a stream. The magnitude of a 4640 * {@code BigInteger} is serialized as a byte array for historical reasons. 4641 * To maintain compatibility with older implementations, the integers 4642 * -1, -1, -2, and -2 are written as the values of the obsolete fields 4643 * {@code bitCount}, {@code bitLength}, {@code lowestSetBit}, and 4644 * {@code firstNonzeroByteNum}, respectively. These values are compatible 4645 * with older implementations, but will be ignored by current 4646 * implementations. 4647 */ 4648 // private void writeObject(ObjectOutputStream s) throws IOException { 4649 // // set the values of the Serializable fields 4650 // ObjectOutputStream.PutField fields = s.putFields(); 4651 // fields.put("signum", signum); 4652 // fields.put("magnitude", magSerializedForm()); 4653 // // The values written for cached fields are compatible with older 4654 // // versions, but are ignored in readObject so don't otherwise matter. 4655 // fields.put("bitCount", -1); 4656 // fields.put("bitLength", -1); 4657 // fields.put("lowestSetBit", -2); 4658 // fields.put("firstNonzeroByteNum", -2); 4659 4660 // // save them 4661 // s.writeFields(); 4662 // } 4663 4664 /** 4665 * Returns the mag array as an array of bytes. 4666 */ 4667 private byte[] magSerializedForm() { 4668 int len = cast(int)mag.length; 4669 4670 int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0])); 4671 int byteLen = (bitLen + 7) >>> 3; 4672 byte[] result = new byte[byteLen]; 4673 4674 for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0; 4675 i >= 0; i--) { 4676 if (bytesCopied == 4) { 4677 nextInt = mag[intIndex--]; 4678 bytesCopied = 1; 4679 } else { 4680 nextInt >>>= 8; 4681 bytesCopied++; 4682 } 4683 result[i] = cast(byte)nextInt; 4684 } 4685 return result; 4686 } 4687 4688 /** 4689 * Converts this {@code BigInteger} to a {@code long}, checking 4690 * for lost information. If the value of this {@code BigInteger} 4691 * is out of the range of the {@code long} type, then an 4692 * {@code ArithmeticException} is thrown. 4693 * 4694 * @return this {@code BigInteger} converted to a {@code long}. 4695 * @throws ArithmeticException if the value of {@code this} will 4696 * not exactly fit in a {@code long}. 4697 * @see BigInteger#longValue 4698 * @since 1.8 4699 */ 4700 long longValueExact() { 4701 if (mag.length <= 2 && bitLength() <= 63) 4702 return longValue(); 4703 else 4704 throw new ArithmeticException("BigInteger out of long range"); 4705 } 4706 4707 /** 4708 * Converts this {@code BigInteger} to an {@code int}, checking 4709 * for lost information. If the value of this {@code BigInteger} 4710 * is out of the range of the {@code int} type, then an 4711 * {@code ArithmeticException} is thrown. 4712 * 4713 * @return this {@code BigInteger} converted to an {@code int}. 4714 * @throws ArithmeticException if the value of {@code this} will 4715 * not exactly fit in an {@code int}. 4716 * @see BigInteger#intValue 4717 * @since 1.8 4718 */ 4719 int intValueExact() { 4720 if (mag.length <= 1 && bitLength() <= 31) 4721 return intValue(); 4722 else 4723 throw new ArithmeticException("BigInteger out of int range"); 4724 } 4725 4726 /** 4727 * Converts this {@code BigInteger} to a {@code short}, checking 4728 * for lost information. If the value of this {@code BigInteger} 4729 * is out of the range of the {@code short} type, then an 4730 * {@code ArithmeticException} is thrown. 4731 * 4732 * @return this {@code BigInteger} converted to a {@code short}. 4733 * @throws ArithmeticException if the value of {@code this} will 4734 * not exactly fit in a {@code short}. 4735 * @see BigInteger#shortValue 4736 * @since 1.8 4737 */ 4738 short shortValueExact() { 4739 if (mag.length <= 1 && bitLength() <= 31) { 4740 int value = intValue(); 4741 if (value >= short.min && value <= short.max) 4742 return shortValue(); 4743 } 4744 throw new ArithmeticException("BigInteger out of short range"); 4745 } 4746 4747 /** 4748 * Converts this {@code BigInteger} to a {@code byte}, checking 4749 * for lost information. If the value of this {@code BigInteger} 4750 * is out of the range of the {@code byte} type, then an 4751 * {@code ArithmeticException} is thrown. 4752 * 4753 * @return this {@code BigInteger} converted to a {@code byte}. 4754 * @throws ArithmeticException if the value of {@code this} will 4755 * not exactly fit in a {@code byte}. 4756 * @see BigInteger#byteValue 4757 * @since 1.8 4758 */ 4759 byte byteValueExact() { 4760 if (mag.length <= 1 && bitLength() <= 31) { 4761 int value = intValue(); 4762 if (value >= byte.min && value <= byte.max) 4763 return byteValue(); 4764 } 4765 throw new ArithmeticException("BigInteger out of byte range"); 4766 } 4767 } 4768 4769 4770 4771 class MutableBigInteger { 4772 /** 4773 * Holds the magnitude of this MutableBigInteger in big endian order. 4774 * The magnitude may start at an offset into the value array, and it may 4775 * end before the length of the value array. 4776 */ 4777 int[] value; 4778 4779 /** 4780 * The number of ints of the value array that are currently used 4781 * to hold the magnitude of this MutableBigInteger. The magnitude starts 4782 * at an offset and offset + intLen may be less than value.length. 4783 */ 4784 int intLen; 4785 4786 /** 4787 * The offset into the value array where the magnitude of this 4788 * MutableBigInteger begins. 4789 */ 4790 int offset = 0; 4791 4792 // Constants 4793 /** 4794 * MutableBigInteger with one element value array with the value 1. Used by 4795 * BigDecimal divideAndRound to increment the quotient. Use this constant 4796 * only when the method is not going to modify this object. 4797 */ 4798 __gshared MutableBigInteger ONE; 4799 4800 /** 4801 * The minimum {@code intLen} for cancelling powers of two before 4802 * dividing. 4803 * If the number of ints is less than this threshold, 4804 * {@code divideKnuth} does not eliminate common powers of two from 4805 * the dividend and divisor. 4806 */ 4807 enum int KNUTH_POW2_THRESH_LEN = 6; 4808 4809 /** 4810 * The minimum number of trailing zero ints for cancelling powers of two 4811 * before dividing. 4812 * If the dividend and divisor don't share at least this many zero ints 4813 * at the end, {@code divideKnuth} does not eliminate common powers 4814 * of two from the dividend and divisor. 4815 */ 4816 enum int KNUTH_POW2_THRESH_ZEROS = 3; 4817 4818 private enum long INFLATED = long.min; 4819 private enum LONG_MASK = BigInteger.LONG_MASK; 4820 4821 shared static this() { 4822 ONE = new MutableBigInteger(1); 4823 } 4824 4825 // Constructors 4826 4827 /** 4828 * The default constructor. An empty MutableBigInteger is created with 4829 * a one word capacity. 4830 */ 4831 this() { 4832 value = new int[1]; 4833 intLen = 0; 4834 } 4835 4836 /** 4837 * Construct a new MutableBigInteger with a magnitude specified by 4838 * the int val. 4839 */ 4840 this(int val) { 4841 value = new int[1]; 4842 intLen = 1; 4843 value[0] = val; 4844 } 4845 4846 /** 4847 * Construct a new MutableBigInteger with the specified value array 4848 * up to the length of the array supplied. 4849 */ 4850 this(int[] val) { 4851 value = val; 4852 intLen = cast(int)val.length; 4853 } 4854 4855 /** 4856 * Construct a new MutableBigInteger with a magnitude equal to the 4857 * specified BigInteger. 4858 */ 4859 this(BigInteger b) { 4860 intLen = cast(int)b.mag.length; 4861 // value = Arrays.copyOf(b.mag, intLen); 4862 value = b.mag.dup; 4863 } 4864 4865 /** 4866 * Construct a new MutableBigInteger with a magnitude equal to the 4867 * specified MutableBigInteger. 4868 */ 4869 this(MutableBigInteger val) { 4870 intLen = val.intLen; 4871 // value = Arrays.copyOfRange(val.value, val.offset, val.offset + intLen); 4872 value = val.cloneValue(); 4873 } 4874 4875 int[] cloneValue() { 4876 return value[offset .. offset + intLen].dup; 4877 } 4878 4879 /** 4880 * Makes this number an {@code n}-int number all of whose bits are ones. 4881 * Used by Burnikel-Ziegler division. 4882 * @param n number of ints in the {@code value} array 4883 * @return a number equal to {@code ((1<<(32*n)))-1} 4884 */ 4885 private void ones(int n) { 4886 if (n > value.length) 4887 value = new int[n]; 4888 // Arrays.fill(value, -1); 4889 value[] = -1; 4890 offset = 0; 4891 intLen = n; 4892 } 4893 4894 /** 4895 * Internal helper method to return the magnitude array. The caller is not 4896 * supposed to modify the returned array. 4897 */ 4898 private int[] getMagnitudeArray() { 4899 if (offset > 0 || value.length != intLen) 4900 // return Arrays.copyOfRange(value, offset, offset + intLen); 4901 return value[offset .. offset + intLen]; 4902 return value; 4903 } 4904 4905 /** 4906 * Convert this MutableBigInteger to a long value. The caller has to make 4907 * sure this MutableBigInteger can be fit into long. 4908 */ 4909 private long toLong() { 4910 assert (intLen <= 2, "this MutableBigInteger exceeds the range of long"); 4911 if (intLen == 0) 4912 return 0; 4913 long d = value[offset] & LONG_MASK; 4914 return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d; 4915 } 4916 4917 /** 4918 * Convert this MutableBigInteger to a BigInteger object. 4919 */ 4920 BigInteger toBigInteger(int sign) { 4921 if (intLen == 0 || sign == 0) 4922 return BigInteger.ZERO; 4923 return new BigInteger(getMagnitudeArray(), sign); 4924 } 4925 4926 /** 4927 * Converts this number to a nonnegative {@code BigInteger}. 4928 */ 4929 BigInteger toBigInteger() { 4930 normalize(); 4931 return toBigInteger(isZero() ? 0 : 1); 4932 } 4933 4934 /** 4935 * Convert this MutableBigInteger to BigDecimal object with the specified sign 4936 * and scale. 4937 */ 4938 // BigDecimal toBigDecimal(int sign, int scale) { 4939 // if (intLen == 0 || sign == 0) 4940 // return BigDecimal.zeroValueOf(scale); 4941 // int[] mag = getMagnitudeArray(); 4942 // int len = cast(int)mag.length; 4943 // int d = mag[0]; 4944 // // If this MutableBigInteger can't be fit into long, we need to 4945 // // make a BigInteger object for the resultant BigDecimal object. 4946 // if (len > 2 || (d < 0 && len == 2)) 4947 // return new BigDecimal(new BigInteger(mag, sign), INFLATED, scale, 0); 4948 // long v = (len == 2) ? 4949 // ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) : 4950 // d & LONG_MASK; 4951 // return BigDecimal.valueOf(sign == -1 ? -v : v, scale); 4952 // } 4953 4954 /** 4955 * This is for internal use in converting from a MutableBigInteger 4956 * object into a long value given a specified sign. 4957 * returns INFLATED if value is not fit into long 4958 */ 4959 long toCompactValue(int sign) { 4960 if (intLen == 0 || sign == 0) 4961 return 0L; 4962 int[] mag = getMagnitudeArray(); 4963 int len = cast(int)mag.length; 4964 int d = mag[0]; 4965 // If this MutableBigInteger can not be fitted into long, we need to 4966 // make a BigInteger object for the resultant BigDecimal object. 4967 if (len > 2 || (d < 0 && len == 2)) 4968 return INFLATED; 4969 long v = (len == 2) ? 4970 ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) : 4971 d & LONG_MASK; 4972 return sign == -1 ? -v : v; 4973 } 4974 4975 /** 4976 * Clear out a MutableBigInteger for reuse. 4977 */ 4978 void clear() { 4979 offset = intLen = 0; 4980 for (int index=0, n=cast(int)value.length; index < n; index++) 4981 value[index] = 0; 4982 } 4983 4984 /** 4985 * Set a MutableBigInteger to zero, removing its offset. 4986 */ 4987 void reset() { 4988 offset = intLen = 0; 4989 } 4990 4991 /** 4992 * Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1 4993 * as this MutableBigInteger is numerically less than, equal to, or 4994 * greater than {@code b}. 4995 */ 4996 final int compare(MutableBigInteger b) { 4997 int blen = b.intLen; 4998 if (intLen < blen) 4999 return -1; 5000 if (intLen > blen) 5001 return 1; 5002 5003 // Add Integer.MIN_VALUE to make the comparison act as unsigned integer 5004 // comparison. 5005 int[] bval = b.value; 5006 for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) { 5007 int b1 = value[i] + 0x80000000; 5008 int b2 = bval[j] + 0x80000000; 5009 if (b1 < b2) 5010 return -1; 5011 if (b1 > b2) 5012 return 1; 5013 } 5014 return 0; 5015 } 5016 5017 /** 5018 * Returns a value equal to what {@code b.leftShift(32*ints); return compare(b);} 5019 * would return, but doesn't change the value of {@code b}. 5020 */ 5021 private int compareShifted(MutableBigInteger b, int ints) { 5022 int blen = b.intLen; 5023 int alen = intLen - ints; 5024 if (alen < blen) 5025 return -1; 5026 if (alen > blen) 5027 return 1; 5028 5029 // Add Integer.MIN_VALUE to make the comparison act as unsigned integer 5030 // comparison. 5031 int[] bval = b.value; 5032 for (int i = offset, j = b.offset; i < alen + offset; i++, j++) { 5033 int b1 = value[i] + 0x80000000; 5034 int b2 = bval[j] + 0x80000000; 5035 if (b1 < b2) 5036 return -1; 5037 if (b1 > b2) 5038 return 1; 5039 } 5040 return 0; 5041 } 5042 5043 /** 5044 * Compare this against half of a MutableBigInteger object (Needed for 5045 * remainder tests). 5046 * Assumes no leading unnecessary zeros, which holds for results 5047 * from divide(). 5048 */ 5049 final int compareHalf(MutableBigInteger b) { 5050 int blen = b.intLen; 5051 int len = intLen; 5052 if (len <= 0) 5053 return blen <= 0 ? 0 : -1; 5054 if (len > blen) 5055 return 1; 5056 if (len < blen - 1) 5057 return -1; 5058 int[] bval = b.value; 5059 int bstart = 0; 5060 int carry = 0; 5061 // Only 2 cases left:len == blen or len == blen - 1 5062 if (len != blen) { // len == blen - 1 5063 if (bval[bstart] == 1) { 5064 ++bstart; 5065 carry = 0x80000000; 5066 } else 5067 return -1; 5068 } 5069 // compare values with right-shifted values of b, 5070 // carrying shifted-out bits across words 5071 int[] val = value; 5072 for (int i = offset, j = bstart; i < len + offset;) { 5073 int bv = bval[j++]; 5074 long hb = ((bv >>> 1) + carry) & LONG_MASK; 5075 long v = val[i++] & LONG_MASK; 5076 if (v != hb) 5077 return v < hb ? -1 : 1; 5078 carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0 5079 } 5080 return carry == 0 ? 0 : -1; 5081 } 5082 5083 /** 5084 * Return the index of the lowest set bit in this MutableBigInteger. If the 5085 * magnitude of this MutableBigInteger is zero, -1 is returned. 5086 */ 5087 private final int getLowestSetBit() { 5088 if (intLen == 0) 5089 return -1; 5090 int j, b; 5091 for (j=intLen-1; (j > 0) && (value[j+offset] == 0); j--) {} 5092 b = value[j+offset]; 5093 if (b == 0) 5094 return -1; 5095 return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b); 5096 } 5097 5098 /** 5099 * Return the int in use in this MutableBigInteger at the specified 5100 * index. This method is not used because it is not inlined on all 5101 * platforms. 5102 */ 5103 private final int getInt(int index) { 5104 return value[offset+index]; 5105 } 5106 5107 /** 5108 * Return a long which is equal to the unsigned value of the int in 5109 * use in this MutableBigInteger at the specified index. This method is 5110 * not used because it is not inlined on all platforms. 5111 */ 5112 private final long getLong(int index) { 5113 return value[offset+index] & LONG_MASK; 5114 } 5115 5116 /** 5117 * Ensure that the MutableBigInteger is in normal form, specifically 5118 * making sure that there are no leading zeros, and that if the 5119 * magnitude is zero, then intLen is zero. 5120 */ 5121 final void normalize() { 5122 if (intLen == 0) { 5123 offset = 0; 5124 return; 5125 } 5126 5127 int index = offset; 5128 if (value[index] != 0) 5129 return; 5130 5131 int indexBound = index+intLen; 5132 do { 5133 index++; 5134 } while(index < indexBound && value[index] == 0); 5135 5136 int numZeros = index - offset; 5137 intLen -= numZeros; 5138 offset = (intLen == 0 ? 0 : offset+numZeros); 5139 } 5140 5141 /** 5142 * If this MutableBigInteger cannot hold len words, increase the size 5143 * of the value array to len words. 5144 */ 5145 private final void ensureCapacity(int len) { 5146 if (value.length < len) { 5147 value = new int[len]; 5148 offset = 0; 5149 intLen = len; 5150 } 5151 } 5152 5153 /** 5154 * Convert this MutableBigInteger into an int array with no leading 5155 * zeros, of a length that is equal to this MutableBigInteger's intLen. 5156 */ 5157 int[] toIntArray() { 5158 int[] result = new int[intLen]; 5159 for(int i=0; i < intLen; i++) 5160 result[i] = value[offset+i]; 5161 return result; 5162 } 5163 5164 /** 5165 * Sets the int at index+offset in this MutableBigInteger to val. 5166 * This does not get inlined on all platforms so it is not used 5167 * as often as originally intended. 5168 */ 5169 void setInt(int index, int val) { 5170 value[offset + index] = val; 5171 } 5172 5173 /** 5174 * Sets this MutableBigInteger's value array to the specified array. 5175 * The intLen is set to the specified length. 5176 */ 5177 void setValue(int[] val, int length) { 5178 value = val; 5179 intLen = length; 5180 offset = 0; 5181 } 5182 5183 /** 5184 * Sets this MutableBigInteger's value array to a copy of the specified 5185 * array. The intLen is set to the length of the new array. 5186 */ 5187 void copyValue(MutableBigInteger src) { 5188 int len = src.intLen; 5189 if (value.length < len) 5190 value = new int[len]; 5191 //System.arraycopy(src.value, src.offset, value, 0, len); 5192 value[0 .. len] = src.cloneValue(); 5193 5194 intLen = len; 5195 offset = 0; 5196 } 5197 5198 /** 5199 * Sets this MutableBigInteger's value array to a copy of the specified 5200 * array. The intLen is set to the length of the specified array. 5201 */ 5202 void copyValue(int[] val) { 5203 int len = cast(int)val.length; 5204 if (value.length < len) 5205 value = new int[len]; 5206 // System.arraycopy(val, 0, value, 0, len); 5207 value[0..len] = val[0 .. len]; 5208 intLen = len; 5209 offset = 0; 5210 } 5211 5212 /** 5213 * Returns true iff this MutableBigInteger has a value of one. 5214 */ 5215 bool isOne() { 5216 return (intLen == 1) && (value[offset] == 1); 5217 } 5218 5219 /** 5220 * Returns true iff this MutableBigInteger has a value of zero. 5221 */ 5222 bool isZero() { 5223 return (intLen == 0); 5224 } 5225 5226 /** 5227 * Returns true iff this MutableBigInteger is even. 5228 */ 5229 bool isEven() { 5230 return (intLen == 0) || ((value[offset + intLen - 1] & 1) == 0); 5231 } 5232 5233 /** 5234 * Returns true iff this MutableBigInteger is odd. 5235 */ 5236 bool isOdd() { 5237 return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1); 5238 } 5239 5240 /** 5241 * Returns true iff this MutableBigInteger is in normal form. A 5242 * MutableBigInteger is in normal form if it has no leading zeros 5243 * after the offset, and intLen + offset <= cast(int)value.length. 5244 */ 5245 bool isNormal() { 5246 if (intLen + offset > value.length) 5247 return false; 5248 if (intLen == 0) 5249 return true; 5250 return (value[offset] != 0); 5251 } 5252 5253 /** 5254 * Returns a string representation of this MutableBigInteger in radix 10. 5255 */ 5256 override string toString() { 5257 BigInteger b = toBigInteger(1); 5258 return b.toString(); 5259 } 5260 5261 /** 5262 * Like {@link #rightShift(int)} but {@code n} can be greater than the length of the number. 5263 */ 5264 void safeRightShift(int n) { 5265 if (n/32 >= intLen) { 5266 reset(); 5267 } else { 5268 rightShift(n); 5269 } 5270 } 5271 5272 /** 5273 * Right shift this MutableBigInteger n bits. The MutableBigInteger is left 5274 * in normal form. 5275 */ 5276 void rightShift(int n) { 5277 if (intLen == 0) 5278 return; 5279 int nInts = n >>> 5; 5280 int nBits = n & 0x1F; 5281 this.intLen -= nInts; 5282 if (nBits == 0) 5283 return; 5284 int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]); 5285 if (nBits >= bitsInHighWord) { 5286 this.primitiveLeftShift(32 - nBits); 5287 this.intLen--; 5288 } else { 5289 primitiveRightShift(nBits); 5290 } 5291 } 5292 5293 /** 5294 * Like {@link #leftShift(int)} but {@code n} can be zero. 5295 */ 5296 void safeLeftShift(int n) { 5297 if (n > 0) { 5298 leftShift(n); 5299 } 5300 } 5301 5302 /** 5303 * Left shift this MutableBigInteger n bits. 5304 */ 5305 void leftShift(int n) { 5306 /* 5307 * If there is enough storage space in this MutableBigInteger already 5308 * the available space will be used. Space to the right of the used 5309 * ints in the value array is faster to utilize, so the extra space 5310 * will be taken from the right if possible. 5311 */ 5312 if (intLen == 0) 5313 return; 5314 int nInts = n >>> 5; 5315 int nBits = n&0x1F; 5316 int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]); 5317 5318 // If shift can be done without moving words, do so 5319 if (n <= (32-bitsInHighWord)) { 5320 primitiveLeftShift(nBits); 5321 return; 5322 } 5323 5324 int newLen = intLen + nInts +1; 5325 if (nBits <= (32-bitsInHighWord)) 5326 newLen--; 5327 if (value.length < newLen) { 5328 // The array must grow 5329 int[] result = new int[newLen]; 5330 for (int i=0; i < intLen; i++) 5331 result[i] = value[offset+i]; 5332 setValue(result, newLen); 5333 } else if (value.length - offset >= newLen) { 5334 // Use space on right 5335 for(int i=0; i < newLen - intLen; i++) 5336 value[offset+intLen+i] = 0; 5337 } else { 5338 // Must use space on left 5339 for (int i=0; i < intLen; i++) 5340 value[i] = value[offset+i]; 5341 for (int i=intLen; i < newLen; i++) 5342 value[i] = 0; 5343 offset = 0; 5344 } 5345 intLen = newLen; 5346 if (nBits == 0) 5347 return; 5348 if (nBits <= (32-bitsInHighWord)) 5349 primitiveLeftShift(nBits); 5350 else 5351 primitiveRightShift(32 -nBits); 5352 } 5353 5354 /** 5355 * A primitive used for division. This method adds in one multiple of the 5356 * divisor a back to the dividend result at a specified offset. It is used 5357 * when qhat was estimated too large, and must be adjusted. 5358 */ 5359 private int divadd(int[] a, int[] result, int offset) { 5360 long carry = 0; 5361 5362 for (int j=cast(int)a.length-1; j >= 0; j--) { 5363 long sum = (a[j] & LONG_MASK) + 5364 (result[j+offset] & LONG_MASK) + carry; 5365 result[j+offset] = cast(int)sum; 5366 carry = sum >>> 32; 5367 } 5368 return cast(int)carry; 5369 } 5370 5371 /** 5372 * This method is used for division. It multiplies an n word input a by one 5373 * word input x, and subtracts the n word product from q. This is needed 5374 * when subtracting qhat*divisor from dividend. 5375 */ 5376 private int mulsub(int[] q, int[] a, int x, int len, int offset) { 5377 long xLong = x & LONG_MASK; 5378 long carry = 0; 5379 offset += len; 5380 5381 for (int j=len-1; j >= 0; j--) { 5382 long product = (a[j] & LONG_MASK) * xLong + carry; 5383 long difference = q[offset] - product; 5384 q[offset--] = cast(int)difference; 5385 carry = (product >>> 32) 5386 + (((difference & LONG_MASK) > 5387 (((~cast(int)product) & LONG_MASK))) ? 1:0); 5388 } 5389 return cast(int)carry; 5390 } 5391 5392 /** 5393 * The method is the same as mulsun, except the fact that q array is not 5394 * updated, the only result of the method is borrow flag. 5395 */ 5396 private int mulsubBorrow(int[] q, int[] a, int x, int len, int offset) { 5397 long xLong = x & LONG_MASK; 5398 long carry = 0; 5399 offset += len; 5400 for (int j=len-1; j >= 0; j--) { 5401 long product = (a[j] & LONG_MASK) * xLong + carry; 5402 long difference = q[offset--] - product; 5403 carry = (product >>> 32) 5404 + (((difference & LONG_MASK) > 5405 (((~cast(int)product) & LONG_MASK))) ? 1:0); 5406 } 5407 return cast(int)carry; 5408 } 5409 5410 /** 5411 * Right shift this MutableBigInteger n bits, where n is 5412 * less than 32. 5413 * Assumes that intLen > 0, n > 0 for speed 5414 */ 5415 private final void primitiveRightShift(int n) { 5416 int[] val = value; 5417 int n2 = 32 - n; 5418 for (int i=offset+intLen-1, c=val[i]; i > offset; i--) { 5419 int b = c; 5420 c = val[i-1]; 5421 val[i] = (c << n2) | (b >>> n); 5422 } 5423 val[offset] >>>= n; 5424 } 5425 5426 /** 5427 * Left shift this MutableBigInteger n bits, where n is 5428 * less than 32. 5429 * Assumes that intLen > 0, n > 0 for speed 5430 */ 5431 private final void primitiveLeftShift(int n) { 5432 int[] val = value; 5433 int n2 = 32 - n; 5434 for (int i=offset, c=val[i], m=i+intLen-1; i < m; i++) { 5435 int b = c; 5436 c = val[i+1]; 5437 val[i] = (b << n) | (c >>> n2); 5438 } 5439 val[offset+intLen-1] <<= n; 5440 } 5441 5442 /** 5443 * Returns a {@code BigInteger} equal to the {@code n} 5444 * low ints of this number. 5445 */ 5446 private BigInteger getLower(int n) { 5447 if (isZero()) { 5448 return BigInteger.ZERO; 5449 } else if (intLen < n) { 5450 return toBigInteger(1); 5451 } else { 5452 // strip zeros 5453 int len = n; 5454 while (len > 0 && value[offset+intLen-len] == 0) 5455 len--; 5456 int sign = len > 0 ? 1 : 0; 5457 // return new BigInteger(Arrays.copyOfRange(value, offset+intLen-len, offset+intLen), sign); 5458 return new BigInteger(value[offset+intLen-len .. offset+intLen], sign); 5459 } 5460 } 5461 5462 /** 5463 * Discards all ints whose index is greater than {@code n}. 5464 */ 5465 private void keepLower(int n) { 5466 if (intLen >= n) { 5467 offset += intLen - n; 5468 intLen = n; 5469 } 5470 } 5471 5472 /** 5473 * Adds the contents of two MutableBigInteger objects.The result 5474 * is placed within this MutableBigInteger. 5475 * The contents of the addend are not changed. 5476 */ 5477 void add(MutableBigInteger addend) { 5478 int x = intLen; 5479 int y = addend.intLen; 5480 int resultLen = (intLen > addend.intLen ? intLen : addend.intLen); 5481 int[] result = (value.length < resultLen ? new int[resultLen] : value); 5482 5483 int rstart = cast(int)result.length-1; 5484 long sum; 5485 long carry = 0; 5486 5487 // Add common parts of both numbers 5488 while(x > 0 && y > 0) { 5489 x--; y--; 5490 sum = (value[x+offset] & LONG_MASK) + 5491 (addend.value[y+addend.offset] & LONG_MASK) + carry; 5492 result[rstart--] = cast(int)sum; 5493 carry = sum >>> 32; 5494 } 5495 5496 // Add remainder of the longer number 5497 while(x > 0) { 5498 x--; 5499 if (carry == 0 && result == value && rstart == (x + offset)) 5500 return; 5501 sum = (value[x+offset] & LONG_MASK) + carry; 5502 result[rstart--] = cast(int)sum; 5503 carry = sum >>> 32; 5504 } 5505 while(y > 0) { 5506 y--; 5507 sum = (addend.value[y+addend.offset] & LONG_MASK) + carry; 5508 result[rstart--] = cast(int)sum; 5509 carry = sum >>> 32; 5510 } 5511 5512 if (carry > 0) { // Result must grow in length 5513 resultLen++; 5514 size_t len = cast(int)result.length; 5515 if (len < resultLen) { 5516 int[] temp = new int[resultLen]; 5517 // Result one word longer from carry-out; copy low-order 5518 // bits into new result. 5519 // System.arraycopy(result, 0, temp, 1, result.length); 5520 temp[1 .. len+1] = result[0..$]; 5521 temp[0] = 1; 5522 result = temp; 5523 } else { 5524 result[rstart--] = 1; 5525 } 5526 } 5527 5528 value = result; 5529 intLen = resultLen; 5530 offset = cast(int)result.length - resultLen; 5531 } 5532 5533 /** 5534 * Adds the value of {@code addend} shifted {@code n} ints to the left. 5535 * Has the same effect as {@code addend.leftShift(32*ints); add(addend);} 5536 * but doesn't change the value of {@code addend}. 5537 */ 5538 void addShifted(MutableBigInteger addend, int n) { 5539 if (addend.isZero()) { 5540 return; 5541 } 5542 5543 int x = intLen; 5544 int y = addend.intLen + n; 5545 int resultLen = (intLen > y ? intLen : y); 5546 int[] result = (value.length < resultLen ? new int[resultLen] : value); 5547 5548 int rstart = cast(int)result.length-1; 5549 long sum; 5550 long carry = 0; 5551 5552 // Add common parts of both numbers 5553 while (x > 0 && y > 0) { 5554 x--; y--; 5555 int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0; 5556 sum = (value[x+offset] & LONG_MASK) + 5557 (bval & LONG_MASK) + carry; 5558 result[rstart--] = cast(int)sum; 5559 carry = sum >>> 32; 5560 } 5561 5562 // Add remainder of the longer number 5563 while (x > 0) { 5564 x--; 5565 if (carry == 0 && result == value && rstart == (x + offset)) { 5566 return; 5567 } 5568 sum = (value[x+offset] & LONG_MASK) + carry; 5569 result[rstart--] = cast(int)sum; 5570 carry = sum >>> 32; 5571 } 5572 while (y > 0) { 5573 y--; 5574 int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0; 5575 sum = (bval & LONG_MASK) + carry; 5576 result[rstart--] = cast(int)sum; 5577 carry = sum >>> 32; 5578 } 5579 5580 if (carry > 0) { // Result must grow in length 5581 resultLen++; 5582 size_t len = cast(int)result.length; 5583 if (len < resultLen) { 5584 int[] temp = new int[resultLen]; 5585 // Result one word longer from carry-out; copy low-order 5586 // bits into new result. 5587 // System.arraycopy(result, 0, temp, 1, result.length); 5588 temp[1 .. len+1] = result[0..$]; 5589 temp[0] = 1; 5590 result = temp; 5591 } else { 5592 result[rstart--] = 1; 5593 } 5594 } 5595 5596 value = result; 5597 intLen = resultLen; 5598 offset = cast(int)result.length - resultLen; 5599 } 5600 5601 /** 5602 * Like {@link #addShifted(MutableBigInteger, int)} but {@code this.intLen} must 5603 * not be greater than {@code n}. In other words, concatenates {@code this} 5604 * and {@code addend}. 5605 */ 5606 void addDisjoint(MutableBigInteger addend, int n) { 5607 if (addend.isZero()) 5608 return; 5609 5610 int x = intLen; 5611 int y = addend.intLen + n; 5612 int resultLen = (intLen > y ? intLen : y); 5613 int[] result; 5614 if (value.length < resultLen) 5615 result = new int[resultLen]; 5616 else { 5617 result = value; 5618 //Arrays.fill(value, offset+intLen, value.length, 0); 5619 value[offset+intLen .. $] = 0; 5620 } 5621 5622 int rstart = cast(int)result.length-1; 5623 5624 // copy from this if needed 5625 // System.arraycopy(value, offset, result, rstart+1-x, x); 5626 result[rstart+1-x .. rstart+1] = value[offset .. x]; 5627 y -= x; 5628 rstart -= x; 5629 5630 int len = std.algorithm.min(y, addend.value.length-addend.offset); 5631 // System.arraycopy(addend.value, addend.offset, result, rstart+1-y, len); 5632 result[rstart+1-y .. rstart+1] = addend.value[addend.offset .. len]; 5633 5634 5635 // zero the gap 5636 for (int i=rstart+1-y+len; i < rstart+1; i++) 5637 result[i] = 0; 5638 5639 value = result; 5640 intLen = resultLen; 5641 offset = cast(int)result.length - resultLen; 5642 } 5643 5644 /** 5645 * Adds the low {@code n} ints of {@code addend}. 5646 */ 5647 void addLower(MutableBigInteger addend, int n) { 5648 MutableBigInteger a = new MutableBigInteger(addend); 5649 if (a.offset + a.intLen >= n) { 5650 a.offset = a.offset + a.intLen - n; 5651 a.intLen = n; 5652 } 5653 a.normalize(); 5654 add(a); 5655 } 5656 5657 /** 5658 * Subtracts the smaller of this and b from the larger and places the 5659 * result into this MutableBigInteger. 5660 */ 5661 int subtract(MutableBigInteger b) { 5662 MutableBigInteger a = this; 5663 5664 int[] result = value; 5665 int sign = a.compare(b); 5666 5667 if (sign == 0) { 5668 reset(); 5669 return 0; 5670 } 5671 if (sign < 0) { 5672 MutableBigInteger tmp = a; 5673 a = b; 5674 b = tmp; 5675 } 5676 5677 int resultLen = a.intLen; 5678 if (result.length < resultLen) 5679 result = new int[resultLen]; 5680 5681 long diff = 0; 5682 int x = a.intLen; 5683 int y = b.intLen; 5684 int rstart = cast(int)result.length - 1; 5685 5686 // Subtract common parts of both numbers 5687 while (y > 0) { 5688 x--; y--; 5689 5690 diff = (a.value[x+a.offset] & LONG_MASK) - 5691 (b.value[y+b.offset] & LONG_MASK) - (cast(int)-(diff>>32)); 5692 result[rstart--] = cast(int)diff; 5693 } 5694 // Subtract remainder of longer number 5695 while (x > 0) { 5696 x--; 5697 diff = (a.value[x+a.offset] & LONG_MASK) - (cast(int)-(diff>>32)); 5698 result[rstart--] = cast(int)diff; 5699 } 5700 5701 value = result; 5702 intLen = resultLen; 5703 offset = cast(int)value.length - resultLen; 5704 normalize(); 5705 return sign; 5706 } 5707 5708 /** 5709 * Subtracts the smaller of a and b from the larger and places the result 5710 * into the larger. Returns 1 if the answer is in a, -1 if in b, 0 if no 5711 * operation was performed. 5712 */ 5713 private int difference(MutableBigInteger b) { 5714 MutableBigInteger a = this; 5715 int sign = a.compare(b); 5716 if (sign == 0) 5717 return 0; 5718 if (sign < 0) { 5719 MutableBigInteger tmp = a; 5720 a = b; 5721 b = tmp; 5722 } 5723 5724 long diff = 0; 5725 int x = a.intLen; 5726 int y = b.intLen; 5727 5728 // Subtract common parts of both numbers 5729 while (y > 0) { 5730 x--; y--; 5731 diff = (a.value[a.offset+ x] & LONG_MASK) - 5732 (b.value[b.offset+ y] & LONG_MASK) - (cast(int)-(diff>>32)); 5733 a.value[a.offset+x] = cast(int)diff; 5734 } 5735 // Subtract remainder of longer number 5736 while (x > 0) { 5737 x--; 5738 diff = (a.value[a.offset+ x] & LONG_MASK) - (cast(int)-(diff>>32)); 5739 a.value[a.offset+x] = cast(int)diff; 5740 } 5741 5742 a.normalize(); 5743 return sign; 5744 } 5745 5746 /** 5747 * Multiply the contents of two MutableBigInteger objects. The result is 5748 * placed into MutableBigInteger z. The contents of y are not changed. 5749 */ 5750 void multiply(MutableBigInteger y, MutableBigInteger z) { 5751 int xLen = intLen; 5752 int yLen = y.intLen; 5753 int newLen = xLen + yLen; 5754 5755 // Put z into an appropriate state to receive product 5756 if (z.value.length < newLen) 5757 z.value = new int[newLen]; 5758 z.offset = 0; 5759 z.intLen = newLen; 5760 5761 // The first iteration is hoisted out of the loop to avoid extra add 5762 long carry = 0; 5763 for (int j=yLen-1, k=yLen+xLen-1; j >= 0; j--, k--) { 5764 long product = (y.value[j+y.offset] & LONG_MASK) * 5765 (value[xLen-1+offset] & LONG_MASK) + carry; 5766 z.value[k] = cast(int)product; 5767 carry = product >>> 32; 5768 } 5769 z.value[xLen-1] = cast(int)carry; 5770 5771 // Perform the multiplication word by word 5772 for (int i = xLen-2; i >= 0; i--) { 5773 carry = 0; 5774 for (int j=yLen-1, k=yLen+i; j >= 0; j--, k--) { 5775 long product = (y.value[j+y.offset] & LONG_MASK) * 5776 (value[i+offset] & LONG_MASK) + 5777 (z.value[k] & LONG_MASK) + carry; 5778 z.value[k] = cast(int)product; 5779 carry = product >>> 32; 5780 } 5781 z.value[i] = cast(int)carry; 5782 } 5783 5784 // Remove leading zeros from product 5785 z.normalize(); 5786 } 5787 5788 /** 5789 * Multiply the contents of this MutableBigInteger by the word y. The 5790 * result is placed into z. 5791 */ 5792 void mul(int y, MutableBigInteger z) { 5793 if (y == 1) { 5794 z.copyValue(this); 5795 return; 5796 } 5797 5798 if (y == 0) { 5799 z.clear(); 5800 return; 5801 } 5802 5803 // Perform the multiplication word by word 5804 long ylong = y & LONG_MASK; 5805 int[] zval = (z.value.length < intLen+1 ? new int[intLen + 1] 5806 : z.value); 5807 long carry = 0; 5808 for (int i = intLen-1; i >= 0; i--) { 5809 long product = ylong * (value[i+offset] & LONG_MASK) + carry; 5810 zval[i+1] = cast(int)product; 5811 carry = product >>> 32; 5812 } 5813 5814 if (carry == 0) { 5815 z.offset = 1; 5816 z.intLen = intLen; 5817 } else { 5818 z.offset = 0; 5819 z.intLen = intLen + 1; 5820 zval[0] = cast(int)carry; 5821 } 5822 z.value = zval; 5823 } 5824 5825 /** 5826 * This method is used for division of an n word dividend by a one word 5827 * divisor. The quotient is placed into quotient. The one word divisor is 5828 * specified by divisor. 5829 * 5830 * @return the remainder of the division is returned. 5831 * 5832 */ 5833 int divideOneWord(int divisor, MutableBigInteger quotient) { 5834 long divisorLong = divisor & LONG_MASK; 5835 5836 // Special case of one word dividend 5837 if (intLen == 1) { 5838 long dividendValue = value[offset] & LONG_MASK; 5839 int q = cast(int) (dividendValue / divisorLong); 5840 int r = cast(int) (dividendValue - q * divisorLong); 5841 quotient.value[0] = q; 5842 quotient.intLen = (q == 0) ? 0 : 1; 5843 quotient.offset = 0; 5844 return r; 5845 } 5846 5847 if (quotient.value.length < intLen) 5848 quotient.value = new int[intLen]; 5849 quotient.offset = 0; 5850 quotient.intLen = intLen; 5851 5852 // Normalize the divisor 5853 int shift = Integer.numberOfLeadingZeros(divisor); 5854 5855 int rem = value[offset]; 5856 long remLong = rem & LONG_MASK; 5857 if (remLong < divisorLong) { 5858 quotient.value[0] = 0; 5859 } else { 5860 quotient.value[0] = cast(int)(remLong / divisorLong); 5861 rem = cast(int) (remLong - (quotient.value[0] * divisorLong)); 5862 remLong = rem & LONG_MASK; 5863 } 5864 int xlen = intLen; 5865 while (--xlen > 0) { 5866 long dividendEstimate = (remLong << 32) | 5867 (value[offset + intLen - xlen] & LONG_MASK); 5868 int q; 5869 if (dividendEstimate >= 0) { 5870 q = cast(int) (dividendEstimate / divisorLong); 5871 rem = cast(int) (dividendEstimate - q * divisorLong); 5872 } else { 5873 long tmp = divWord(dividendEstimate, divisor); 5874 q = cast(int) (tmp & LONG_MASK); 5875 rem = cast(int) (tmp >>> 32); 5876 } 5877 quotient.value[intLen - xlen] = q; 5878 remLong = rem & LONG_MASK; 5879 } 5880 5881 quotient.normalize(); 5882 // Unnormalize 5883 if (shift > 0) 5884 return rem % divisor; 5885 else 5886 return rem; 5887 } 5888 5889 /** 5890 * Calculates the quotient of this div b and places the quotient in the 5891 * provided MutableBigInteger objects and the remainder object is returned. 5892 * 5893 */ 5894 MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) { 5895 return divide(b,quotient,true); 5896 } 5897 5898 MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient, bool needRemainder) { 5899 if (b.intLen < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD || 5900 intLen - b.intLen < BigInteger.BURNIKEL_ZIEGLER_OFFSET) { 5901 return divideKnuth(b, quotient, needRemainder); 5902 } else { 5903 return divideAndRemainderBurnikelZiegler(b, quotient); 5904 } 5905 } 5906 5907 /** 5908 * @see #divideKnuth(MutableBigInteger, MutableBigInteger, bool) 5909 */ 5910 MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient) { 5911 return divideKnuth(b,quotient,true); 5912 } 5913 5914 /** 5915 * Calculates the quotient of this div b and places the quotient in the 5916 * provided MutableBigInteger objects and the remainder object is returned. 5917 * 5918 * Uses Algorithm D in Knuth section 4.3.1. 5919 * Many optimizations to that algorithm have been adapted from the Colin 5920 * Plumb C library. 5921 * It special cases one word divisors for speed. The content of b is not 5922 * changed. 5923 * 5924 */ 5925 MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient, bool needRemainder) { 5926 if (b.intLen == 0) 5927 throw new ArithmeticException("BigInteger divide by zero"); 5928 5929 // Dividend is zero 5930 if (intLen == 0) { 5931 quotient.intLen = quotient.offset = 0; 5932 return needRemainder ? new MutableBigInteger() : null; 5933 } 5934 5935 int cmp = compare(b); 5936 // Dividend less than divisor 5937 if (cmp < 0) { 5938 quotient.intLen = quotient.offset = 0; 5939 return needRemainder ? new MutableBigInteger(this) : null; 5940 } 5941 // Dividend equal to divisor 5942 if (cmp == 0) { 5943 quotient.value[0] = quotient.intLen = 1; 5944 quotient.offset = 0; 5945 return needRemainder ? new MutableBigInteger() : null; 5946 } 5947 5948 quotient.clear(); 5949 // Special case one word divisor 5950 if (b.intLen == 1) { 5951 int r = divideOneWord(b.value[b.offset], quotient); 5952 if(needRemainder) { 5953 if (r == 0) 5954 return new MutableBigInteger(); 5955 return new MutableBigInteger(r); 5956 } else { 5957 return null; 5958 } 5959 } 5960 5961 // Cancel common powers of two if we're above the KNUTH_POW2_* thresholds 5962 if (intLen >= KNUTH_POW2_THRESH_LEN) { 5963 int trailingZeroBits = std.algorithm.min(getLowestSetBit(), b.getLowestSetBit()); 5964 if (trailingZeroBits >= KNUTH_POW2_THRESH_ZEROS*32) { 5965 MutableBigInteger a = new MutableBigInteger(this); 5966 b = new MutableBigInteger(b); 5967 a.rightShift(trailingZeroBits); 5968 b.rightShift(trailingZeroBits); 5969 MutableBigInteger r = a.divideKnuth(b, quotient); 5970 r.leftShift(trailingZeroBits); 5971 return r; 5972 } 5973 } 5974 5975 return divideMagnitude(b, quotient, needRemainder); 5976 } 5977 5978 /** 5979 * Computes {@code this/b} and {@code this%b} using the 5980 * <a href="http://cr.yp.to/bib/1998/burnikel.ps"> Burnikel-Ziegler algorithm</a>. 5981 * This method implements algorithm 3 from pg. 9 of the Burnikel-Ziegler paper. 5982 * The parameter beta was chosen to b 2<sup>32</sup> so almost all shifts are 5983 * multiples of 32 bits.<br/> 5984 * {@code this} and {@code b} must be nonnegative. 5985 * @param b the divisor 5986 * @param quotient output parameter for {@code this/b} 5987 * @return the remainder 5988 */ 5989 MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) { 5990 int r = intLen; 5991 int s = b.intLen; 5992 5993 // Clear the quotient 5994 quotient.offset = quotient.intLen = 0; 5995 5996 if (r < s) { 5997 return this; 5998 } else { 5999 // Unlike Knuth division, we don't check for common powers of two here because 6000 // BZ already runs faster if both numbers contain powers of two and cancelling them has no 6001 // additional benefit. 6002 6003 // step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s} 6004 int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD)); 6005 6006 int j = (s+m-1) / m; // step 2a: j = ceil(s/m) 6007 int n = j * m; // step 2b: block length in 32-bit units 6008 long n32 = 32L * n; // block length in bits 6009 int sigma = cast(int) std.algorithm.max(0, n32 - b.bitLength()); // step 3: sigma = max{T | (2^T)*B < beta^n} 6010 MutableBigInteger bShifted = new MutableBigInteger(b); 6011 bShifted.safeLeftShift(sigma); // step 4a: shift b so its length is a multiple of n 6012 MutableBigInteger aShifted = new MutableBigInteger (this); 6013 aShifted.safeLeftShift(sigma); // step 4b: shift a by the same amount 6014 6015 // step 5: t is the number of blocks needed to accommodate a plus one additional bit 6016 int t = cast(int) ((aShifted.bitLength()+n32) / n32); 6017 if (t < 2) { 6018 t = 2; 6019 } 6020 6021 // step 6: conceptually split a into blocks a[t-1], ..., a[0] 6022 MutableBigInteger a1 = aShifted.getBlock(t-1, t, n); // the most significant block of a 6023 6024 // step 7: z[t-2] = [a[t-1], a[t-2]] 6025 MutableBigInteger z = aShifted.getBlock(t-2, t, n); // the second to most significant block 6026 z.addDisjoint(a1, n); // z[t-2] 6027 6028 // do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers 6029 MutableBigInteger qi = new MutableBigInteger(); 6030 MutableBigInteger ri; 6031 for (int i=t-2; i > 0; i--) { 6032 // step 8a: compute (qi,ri) such that z=b*qi+ri 6033 ri = z.divide2n1n(bShifted, qi); 6034 6035 // step 8b: z = [ri, a[i-1]] 6036 z = aShifted.getBlock(i-1, t, n); // a[i-1] 6037 z.addDisjoint(ri, n); 6038 quotient.addShifted(qi, i*n); // update q (part of step 9) 6039 } 6040 // final iteration of step 8: do the loop one more time for i=0 but leave z unchanged 6041 ri = z.divide2n1n(bShifted, qi); 6042 quotient.add(qi); 6043 6044 ri.rightShift(sigma); // step 9: a and b were shifted, so shift back 6045 return ri; 6046 } 6047 } 6048 6049 /** 6050 * This method implements algorithm 1 from pg. 4 of the Burnikel-Ziegler paper. 6051 * It divides a 2n-digit number by a n-digit number.<br/> 6052 * The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits. 6053 * <br/> 6054 * {@code this} must be a nonnegative number such that {@code this.bitLength() <= 2*b.bitLength()} 6055 * @param b a positive number such that {@code b.bitLength()} is even 6056 * @param quotient output parameter for {@code this/b} 6057 * @return {@code this%b} 6058 */ 6059 private MutableBigInteger divide2n1n(MutableBigInteger b, MutableBigInteger quotient) { 6060 int n = b.intLen; 6061 6062 // step 1: base case 6063 if (n%2 != 0 || n < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD) { 6064 return divideKnuth(b, quotient); 6065 } 6066 6067 // step 2: view this as [a1,a2,a3,a4] where each ai is n/2 ints or less 6068 MutableBigInteger aUpper = new MutableBigInteger(this); 6069 aUpper.safeRightShift(32*(n/2)); // aUpper = [a1,a2,a3] 6070 keepLower(n/2); // this = a4 6071 6072 // step 3: q1=aUpper/b, r1=aUpper%b 6073 MutableBigInteger q1 = new MutableBigInteger(); 6074 MutableBigInteger r1 = aUpper.divide3n2n(b, q1); 6075 6076 // step 4: quotient=[r1,this]/b, r2=[r1,this]%b 6077 addDisjoint(r1, n/2); // this = [r1,this] 6078 MutableBigInteger r2 = divide3n2n(b, quotient); 6079 6080 // step 5: let quotient=[q1,quotient] and return r2 6081 quotient.addDisjoint(q1, n/2); 6082 return r2; 6083 } 6084 6085 /** 6086 * This method implements algorithm 2 from pg. 5 of the Burnikel-Ziegler paper. 6087 * It divides a 3n-digit number by a 2n-digit number.<br/> 6088 * The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.<br/> 6089 * <br/> 6090 * {@code this} must be a nonnegative number such that {@code 2*this.bitLength() <= 3*b.bitLength()} 6091 * @param quotient output parameter for {@code this/b} 6092 * @return {@code this%b} 6093 */ 6094 private MutableBigInteger divide3n2n(MutableBigInteger b, MutableBigInteger quotient) { 6095 int n = b.intLen / 2; // half the length of b in ints 6096 6097 // step 1: view this as [a1,a2,a3] where each ai is n ints or less; let a12=[a1,a2] 6098 MutableBigInteger a12 = new MutableBigInteger(this); 6099 a12.safeRightShift(32*n); 6100 6101 // step 2: view b as [b1,b2] where each bi is n ints or less 6102 MutableBigInteger b1 = new MutableBigInteger(b); 6103 b1.safeRightShift(n * 32); 6104 BigInteger b2 = b.getLower(n); 6105 6106 MutableBigInteger r; 6107 MutableBigInteger d; 6108 if (compareShifted(b, n) < 0) { 6109 // step 3a: if a1<b1, let quotient=a12/b1 and r=a12%b1 6110 r = a12.divide2n1n(b1, quotient); 6111 6112 // step 4: d=quotient*b2 6113 d = new MutableBigInteger(quotient.toBigInteger().multiply(b2)); 6114 } else { 6115 // step 3b: if a1>=b1, let quotient=beta^n-1 and r=a12-b1*2^n+b1 6116 quotient.ones(n); 6117 a12.add(b1); 6118 b1.leftShift(32*n); 6119 a12.subtract(b1); 6120 r = a12; 6121 6122 // step 4: d=quotient*b2=(b2 << 32*n) - b2 6123 d = new MutableBigInteger(b2); 6124 d.leftShift(32 * n); 6125 d.subtract(new MutableBigInteger(b2)); 6126 } 6127 6128 // step 5: r = r*beta^n + a3 - d (paper says a4) 6129 // However, don't subtract d until after the while loop so r doesn't become negative 6130 r.leftShift(32 * n); 6131 r.addLower(this, n); 6132 6133 // step 6: add b until r>=d 6134 while (r.compare(d) < 0) { 6135 r.add(b); 6136 quotient.subtract(MutableBigInteger.ONE); 6137 } 6138 r.subtract(d); 6139 6140 return r; 6141 } 6142 6143 /** 6144 * Returns a {@code MutableBigInteger} containing {@code blockLength} ints from 6145 * {@code this} number, starting at {@code index*blockLength}.<br/> 6146 * Used by Burnikel-Ziegler division. 6147 * @param index the block index 6148 * @param numBlocks the total number of blocks in {@code this} number 6149 * @param blockLength length of one block in units of 32 bits 6150 * @return 6151 */ 6152 private MutableBigInteger getBlock(int index, int numBlocks, int blockLength) { 6153 int blockStart = index * blockLength; 6154 if (blockStart >= intLen) { 6155 return new MutableBigInteger(); 6156 } 6157 6158 int blockEnd; 6159 if (index == numBlocks-1) { 6160 blockEnd = intLen; 6161 } else { 6162 blockEnd = (index+1) * blockLength; 6163 } 6164 if (blockEnd > intLen) { 6165 return new MutableBigInteger(); 6166 } 6167 6168 // int[] newVal = Arrays.copyOfRange(value, offset+intLen-blockEnd, offset+intLen-blockStart); 6169 int[] newVal = value[offset+intLen-blockEnd .. offset+intLen-blockStart]; 6170 return new MutableBigInteger(newVal); 6171 } 6172 6173 /** @see BigInteger#bitLength() */ 6174 long bitLength() { 6175 if (intLen == 0) 6176 return 0; 6177 return intLen*32L - Integer.numberOfLeadingZeros(value[offset]); 6178 } 6179 6180 /** 6181 * Internally used to calculate the quotient of this div v and places the 6182 * quotient in the provided MutableBigInteger object and the remainder is 6183 * returned. 6184 * 6185 * @return the remainder of the division will be returned. 6186 */ 6187 long divide(long v, MutableBigInteger quotient) { 6188 if (v == 0) 6189 throw new ArithmeticException("BigInteger divide by zero"); 6190 6191 // Dividend is zero 6192 if (intLen == 0) { 6193 quotient.intLen = quotient.offset = 0; 6194 return 0; 6195 } 6196 if (v < 0) 6197 v = -v; 6198 6199 int d = cast(int)(v >>> 32); 6200 quotient.clear(); 6201 // Special case on word divisor 6202 if (d == 0) 6203 return divideOneWord(cast(int)v, quotient) & LONG_MASK; 6204 else { 6205 return divideLongMagnitude(v, quotient).toLong(); 6206 } 6207 } 6208 6209 private static void copyAndShift(int[] src, int srcFrom, int srcLen, int[] dst, int dstFrom, int shift) { 6210 int n2 = 32 - shift; 6211 int c=src[srcFrom]; 6212 for (int i=0; i < srcLen-1; i++) { 6213 int b = c; 6214 c = src[++srcFrom]; 6215 dst[dstFrom+i] = (b << shift) | (c >>> n2); 6216 } 6217 dst[dstFrom+srcLen-1] = c << shift; 6218 } 6219 6220 /** 6221 * Divide this MutableBigInteger by the divisor. 6222 * The quotient will be placed into the provided quotient object & 6223 * the remainder object is returned. 6224 */ 6225 private MutableBigInteger divideMagnitude(MutableBigInteger div, 6226 MutableBigInteger quotient, 6227 bool needRemainder ) { 6228 // assert div.intLen > 1 6229 // D1 normalize the divisor 6230 int shift = Integer.numberOfLeadingZeros(div.value[div.offset]); 6231 // Copy divisor value to protect divisor 6232 int dlen = div.intLen; 6233 int[] divisor; 6234 MutableBigInteger rem; // Remainder starts as dividend with space for a leading zero 6235 if (shift > 0) { 6236 divisor = new int[dlen]; 6237 copyAndShift(div.value,div.offset,dlen,divisor,0,shift); 6238 if (Integer.numberOfLeadingZeros(value[offset]) >= shift) { 6239 int[] remarr = new int[intLen + 1]; 6240 rem = new MutableBigInteger(remarr); 6241 rem.intLen = intLen; 6242 rem.offset = 1; 6243 copyAndShift(value,offset,intLen,remarr,1,shift); 6244 } else { 6245 int[] remarr = new int[intLen + 2]; 6246 rem = new MutableBigInteger(remarr); 6247 rem.intLen = intLen+1; 6248 rem.offset = 1; 6249 int rFrom = offset; 6250 int c=0; 6251 int n2 = 32 - shift; 6252 for (int i=1; i < intLen+1; i++,rFrom++) { 6253 int b = c; 6254 c = value[rFrom]; 6255 remarr[i] = (b << shift) | (c >>> n2); 6256 } 6257 remarr[intLen+1] = c << shift; 6258 } 6259 } else { 6260 // divisor = Arrays.copyOfRange(div.value, div.offset, div.offset + div.intLen); 6261 divisor = div.cloneValue(); 6262 rem = new MutableBigInteger(new int[intLen + 1]); 6263 // System.arraycopy(value, offset, rem.value, 1, intLen); 6264 rem.value[1 .. 1+intLen] = value[offset .. offset+intLen]; 6265 rem.intLen = intLen; 6266 rem.offset = 1; 6267 } 6268 6269 int nlen = rem.intLen; 6270 6271 // Set the quotient size 6272 int limit = nlen - dlen + 1; 6273 if (quotient.value.length < limit) { 6274 quotient.value = new int[limit]; 6275 quotient.offset = 0; 6276 } 6277 quotient.intLen = limit; 6278 int[] q = quotient.value; 6279 6280 6281 // Must insert leading 0 in rem if its length did not change 6282 if (rem.intLen == nlen) { 6283 rem.offset = 0; 6284 rem.value[0] = 0; 6285 rem.intLen++; 6286 } 6287 6288 int dh = divisor[0]; 6289 long dhLong = dh & LONG_MASK; 6290 int dl = divisor[1]; 6291 6292 // D2 Initialize j 6293 for (int j=0; j < limit-1; j++) { 6294 // D3 Calculate qhat 6295 // estimate qhat 6296 int qhat = 0; 6297 int qrem = 0; 6298 bool skipCorrection = false; 6299 int nh = rem.value[j+rem.offset]; 6300 int nh2 = nh + 0x80000000; 6301 int nm = rem.value[j+1+rem.offset]; 6302 6303 if (nh == dh) { 6304 qhat = ~0; 6305 qrem = nh + nm; 6306 skipCorrection = qrem + 0x80000000 < nh2; 6307 } else { 6308 long nChunk = ((cast(long)nh) << 32) | (nm & LONG_MASK); 6309 if (nChunk >= 0) { 6310 qhat = cast(int) (nChunk / dhLong); 6311 qrem = cast(int) (nChunk - (qhat * dhLong)); 6312 } else { 6313 long tmp = divWord(nChunk, dh); 6314 qhat = cast(int) (tmp & LONG_MASK); 6315 qrem = cast(int) (tmp >>> 32); 6316 } 6317 } 6318 6319 if (qhat == 0) 6320 continue; 6321 6322 if (!skipCorrection) { // Correct qhat 6323 long nl = rem.value[j+2+rem.offset] & LONG_MASK; 6324 long rs = ((qrem & LONG_MASK) << 32) | nl; 6325 long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); 6326 6327 if (unsignedLongCompare(estProduct, rs)) { 6328 qhat--; 6329 qrem = cast(int)((qrem & LONG_MASK) + dhLong); 6330 if ((qrem & LONG_MASK) >= dhLong) { 6331 estProduct -= (dl & LONG_MASK); 6332 rs = ((qrem & LONG_MASK) << 32) | nl; 6333 if (unsignedLongCompare(estProduct, rs)) 6334 qhat--; 6335 } 6336 } 6337 } 6338 6339 // D4 Multiply and subtract 6340 rem.value[j+rem.offset] = 0; 6341 int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset); 6342 6343 // D5 Test remainder 6344 if (borrow + 0x80000000 > nh2) { 6345 // D6 Add back 6346 divadd(divisor, rem.value, j+1+rem.offset); 6347 qhat--; 6348 } 6349 6350 // Store the quotient digit 6351 q[j] = qhat; 6352 } // D7 loop on j 6353 // D3 Calculate qhat 6354 // estimate qhat 6355 int qhat = 0; 6356 int qrem = 0; 6357 bool skipCorrection = false; 6358 int nh = rem.value[limit - 1 + rem.offset]; 6359 int nh2 = nh + 0x80000000; 6360 int nm = rem.value[limit + rem.offset]; 6361 6362 if (nh == dh) { 6363 qhat = ~0; 6364 qrem = nh + nm; 6365 skipCorrection = qrem + 0x80000000 < nh2; 6366 } else { 6367 long nChunk = ((cast(long) nh) << 32) | (nm & LONG_MASK); 6368 if (nChunk >= 0) { 6369 qhat = cast(int) (nChunk / dhLong); 6370 qrem = cast(int) (nChunk - (qhat * dhLong)); 6371 } else { 6372 long tmp = divWord(nChunk, dh); 6373 qhat = cast(int) (tmp & LONG_MASK); 6374 qrem = cast(int) (tmp >>> 32); 6375 } 6376 } 6377 if (qhat != 0) { 6378 if (!skipCorrection) { // Correct qhat 6379 long nl = rem.value[limit + 1 + rem.offset] & LONG_MASK; 6380 long rs = ((qrem & LONG_MASK) << 32) | nl; 6381 long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); 6382 6383 if (unsignedLongCompare(estProduct, rs)) { 6384 qhat--; 6385 qrem = cast(int) ((qrem & LONG_MASK) + dhLong); 6386 if ((qrem & LONG_MASK) >= dhLong) { 6387 estProduct -= (dl & LONG_MASK); 6388 rs = ((qrem & LONG_MASK) << 32) | nl; 6389 if (unsignedLongCompare(estProduct, rs)) 6390 qhat--; 6391 } 6392 } 6393 } 6394 6395 6396 // D4 Multiply and subtract 6397 int borrow; 6398 rem.value[limit - 1 + rem.offset] = 0; 6399 if(needRemainder) 6400 borrow = mulsub(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset); 6401 else 6402 borrow = mulsubBorrow(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset); 6403 6404 // D5 Test remainder 6405 if (borrow + 0x80000000 > nh2) { 6406 // D6 Add back 6407 if(needRemainder) 6408 divadd(divisor, rem.value, limit - 1 + 1 + rem.offset); 6409 qhat--; 6410 } 6411 6412 // Store the quotient digit 6413 q[(limit - 1)] = qhat; 6414 } 6415 6416 6417 if (needRemainder) { 6418 // D8 Unnormalize 6419 if (shift > 0) 6420 rem.rightShift(shift); 6421 rem.normalize(); 6422 } 6423 quotient.normalize(); 6424 return needRemainder ? rem : null; 6425 } 6426 6427 /** 6428 * Divide this MutableBigInteger by the divisor represented by positive long 6429 * value. The quotient will be placed into the provided quotient object & 6430 * the remainder object is returned. 6431 */ 6432 private MutableBigInteger divideLongMagnitude(long ldivisor, MutableBigInteger quotient) { 6433 // Remainder starts as dividend with space for a leading zero 6434 MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]); 6435 // System.arraycopy(value, offset, rem.value, 1, intLen); 6436 rem.value[1 .. 1+intLen] = value[offset .. offset+intLen].dup; 6437 rem.intLen = intLen; 6438 rem.offset = 1; 6439 6440 int nlen = rem.intLen; 6441 6442 int limit = nlen - 2 + 1; 6443 if (quotient.value.length < limit) { 6444 quotient.value = new int[limit]; 6445 quotient.offset = 0; 6446 } 6447 quotient.intLen = limit; 6448 int[] q = quotient.value; 6449 6450 // D1 normalize the divisor 6451 int shift = Long.numberOfLeadingZeros(ldivisor); 6452 if (shift > 0) { 6453 ldivisor<<=shift; 6454 rem.leftShift(shift); 6455 } 6456 6457 // Must insert leading 0 in rem if its length did not change 6458 if (rem.intLen == nlen) { 6459 rem.offset = 0; 6460 rem.value[0] = 0; 6461 rem.intLen++; 6462 } 6463 6464 int dh = cast(int)(ldivisor >>> 32); 6465 long dhLong = dh & LONG_MASK; 6466 int dl = cast(int)(ldivisor & LONG_MASK); 6467 6468 // D2 Initialize j 6469 for (int j = 0; j < limit; j++) { 6470 // D3 Calculate qhat 6471 // estimate qhat 6472 int qhat = 0; 6473 int qrem = 0; 6474 bool skipCorrection = false; 6475 int nh = rem.value[j + rem.offset]; 6476 int nh2 = nh + 0x80000000; 6477 int nm = rem.value[j + 1 + rem.offset]; 6478 6479 if (nh == dh) { 6480 qhat = ~0; 6481 qrem = nh + nm; 6482 skipCorrection = qrem + 0x80000000 < nh2; 6483 } else { 6484 long nChunk = ((cast(long) nh) << 32) | (nm & LONG_MASK); 6485 if (nChunk >= 0) { 6486 qhat = cast(int) (nChunk / dhLong); 6487 qrem = cast(int) (nChunk - (qhat * dhLong)); 6488 } else { 6489 long tmp = divWord(nChunk, dh); 6490 qhat = cast(int)(tmp & LONG_MASK); 6491 qrem = cast(int)(tmp>>>32); 6492 } 6493 } 6494 6495 if (qhat == 0) 6496 continue; 6497 6498 if (!skipCorrection) { // Correct qhat 6499 long nl = rem.value[j + 2 + rem.offset] & LONG_MASK; 6500 long rs = ((qrem & LONG_MASK) << 32) | nl; 6501 long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); 6502 6503 if (unsignedLongCompare(estProduct, rs)) { 6504 qhat--; 6505 qrem = cast(int) ((qrem & LONG_MASK) + dhLong); 6506 if ((qrem & LONG_MASK) >= dhLong) { 6507 estProduct -= (dl & LONG_MASK); 6508 rs = ((qrem & LONG_MASK) << 32) | nl; 6509 if (unsignedLongCompare(estProduct, rs)) 6510 qhat--; 6511 } 6512 } 6513 } 6514 6515 // D4 Multiply and subtract 6516 rem.value[j + rem.offset] = 0; 6517 int borrow = mulsubLong(rem.value, dh, dl, qhat, j + rem.offset); 6518 6519 // D5 Test remainder 6520 if (borrow + 0x80000000 > nh2) { 6521 // D6 Add back 6522 divaddLong(dh,dl, rem.value, j + 1 + rem.offset); 6523 qhat--; 6524 } 6525 6526 // Store the quotient digit 6527 q[j] = qhat; 6528 } // D7 loop on j 6529 6530 // D8 Unnormalize 6531 if (shift > 0) 6532 rem.rightShift(shift); 6533 6534 quotient.normalize(); 6535 rem.normalize(); 6536 return rem; 6537 } 6538 6539 /** 6540 * A primitive used for division by long. 6541 * Specialized version of the method divadd. 6542 * dh is a high part of the divisor, dl is a low part 6543 */ 6544 private int divaddLong(int dh, int dl, int[] result, int offset) { 6545 long carry = 0; 6546 6547 long sum = (dl & LONG_MASK) + (result[1+offset] & LONG_MASK); 6548 result[1+offset] = cast(int)sum; 6549 6550 sum = (dh & LONG_MASK) + (result[offset] & LONG_MASK) + carry; 6551 result[offset] = cast(int)sum; 6552 carry = sum >>> 32; 6553 return cast(int)carry; 6554 } 6555 6556 /** 6557 * This method is used for division by long. 6558 * Specialized version of the method sulsub. 6559 * dh is a high part of the divisor, dl is a low part 6560 */ 6561 private int mulsubLong(int[] q, int dh, int dl, int x, int offset) { 6562 long xLong = x & LONG_MASK; 6563 offset += 2; 6564 long product = (dl & LONG_MASK) * xLong; 6565 long difference = q[offset] - product; 6566 q[offset--] = cast(int)difference; 6567 long carry = (product >>> 32) 6568 + (((difference & LONG_MASK) > 6569 (((~cast(int)product) & LONG_MASK))) ? 1:0); 6570 product = (dh & LONG_MASK) * xLong + carry; 6571 difference = q[offset] - product; 6572 q[offset--] = cast(int)difference; 6573 carry = (product >>> 32) 6574 + (((difference & LONG_MASK) > 6575 (((~cast(int)product) & LONG_MASK))) ? 1:0); 6576 return cast(int)carry; 6577 } 6578 6579 /** 6580 * Compare two longs as if they were unsigned. 6581 * Returns true iff one is bigger than two. 6582 */ 6583 private bool unsignedLongCompare(long one, long two) { 6584 return (one+long.min) > (two+long.min); 6585 } 6586 6587 /** 6588 * This method divides a long quantity by an int to estimate 6589 * qhat for two multi precision numbers. It is used when 6590 * the signed value of n is less than zero. 6591 * Returns long value where high 32 bits contain remainder value and 6592 * low 32 bits contain quotient value. 6593 */ 6594 static long divWord(long n, int d) { 6595 long dLong = d & LONG_MASK; 6596 long r; 6597 long q; 6598 if (dLong == 1) { 6599 q = cast(int)n; 6600 r = 0; 6601 return (r << 32) | (q & LONG_MASK); 6602 } 6603 6604 // Approximate the quotient and remainder 6605 q = (n >>> 1) / (dLong >>> 1); 6606 r = n - q*dLong; 6607 6608 // Correct the approximation 6609 while (r < 0) { 6610 r += dLong; 6611 q--; 6612 } 6613 while (r >= dLong) { 6614 r -= dLong; 6615 q++; 6616 } 6617 // n - q*dlong == r && 0 <= r <dLong, hence we're done. 6618 return (r << 32) | (q & LONG_MASK); 6619 } 6620 6621 /** 6622 * Calculate the integer square root {@code floor(sqrt(this))} where 6623 * {@code sqrt(.)} denotes the mathematical square root. The contents of 6624 * {@code this} are <b>not</b> changed. The value of {@code this} is assumed 6625 * to be non-negative. 6626 * 6627 * @implNote The implementation is based on the material in Henry S. Warren, 6628 * Jr., <i>Hacker's Delight (2nd ed.)</i> (Addison Wesley, 2013), 279-282. 6629 * 6630 * @throws ArithmeticException if the value returned by {@code bitLength()} 6631 * overflows the range of {@code int}. 6632 * @return the integer square root of {@code this} 6633 * @since 9 6634 */ 6635 MutableBigInteger sqrt() { 6636 // Special cases. 6637 if (this.isZero()) { 6638 return new MutableBigInteger(0); 6639 } else if (this.value.length == 1 6640 && (this.value[0] & LONG_MASK) < 4) { // result is unity 6641 return ONE; 6642 } 6643 6644 if (bitLength() <= 63) { 6645 // Initial estimate is the square root of the positive long value. 6646 long v = new BigInteger(this.value, 1).longValueExact(); 6647 long xk = cast(long)std.math.floor(std.math.sqrt(cast(float)v)); 6648 6649 // Refine the estimate. 6650 do { 6651 long xk1 = (xk + v/xk)/2; 6652 6653 // Terminate when non-decreasing. 6654 if (xk1 >= xk) { 6655 return new MutableBigInteger( [cast(int)(xk >>> 32), 6656 cast(int)(xk & LONG_MASK)] ); 6657 } 6658 6659 xk = xk1; 6660 } while (true); 6661 } else { 6662 // Set up the initial estimate of the iteration. 6663 6664 // Obtain the bitLength > 63. 6665 int bitLength = cast(int) this.bitLength(); 6666 if (bitLength != this.bitLength()) { 6667 throw new ArithmeticException("bitLength() integer overflow"); 6668 } 6669 6670 // Determine an even valued right shift into positive long range. 6671 int shift = bitLength - 63; 6672 if (shift % 2 == 1) { 6673 shift++; 6674 } 6675 6676 // Shift the value into positive long range. 6677 MutableBigInteger xk = new MutableBigInteger(this); 6678 xk.rightShift(shift); 6679 xk.normalize(); 6680 6681 // Use the square root of the shifted value as an approximation. 6682 double d = new BigInteger(xk.value, 1).doubleValue(); 6683 BigInteger bi = BigInteger.valueOf(cast(long)std.math.ceil(std.math.sqrt(d))); 6684 xk = new MutableBigInteger(bi.mag); 6685 6686 // Shift the approximate square root back into the original range. 6687 xk.leftShift(shift / 2); 6688 6689 // Refine the estimate. 6690 MutableBigInteger xk1 = new MutableBigInteger(); 6691 do { 6692 // xk1 = (xk + n/xk)/2 6693 this.divide(xk, xk1, false); 6694 xk1.add(xk); 6695 xk1.rightShift(1); 6696 6697 // Terminate when non-decreasing. 6698 if (xk1.compare(xk) >= 0) { 6699 return xk; 6700 } 6701 6702 // xk = xk1 6703 xk.copyValue(xk1); 6704 6705 xk1.reset(); 6706 } while (true); 6707 } 6708 } 6709 6710 /** 6711 * Calculate GCD of this and b. This and b are changed by the computation. 6712 */ 6713 MutableBigInteger hybridGCD(MutableBigInteger b) { 6714 // Use Euclid's algorithm until the numbers are approximately the 6715 // same length, then use the binary GCD algorithm to find the GCD. 6716 MutableBigInteger a = this; 6717 MutableBigInteger q = new MutableBigInteger(); 6718 6719 while (b.intLen != 0) { 6720 if (std.math.abs(a.intLen - b.intLen) < 2) 6721 return a.binaryGCD(b); 6722 6723 MutableBigInteger r = a.divide(b, q); 6724 a = b; 6725 b = r; 6726 } 6727 return a; 6728 } 6729 6730 /** 6731 * Calculate GCD of this and v. 6732 * Assumes that this and v are not zero. 6733 */ 6734 private MutableBigInteger binaryGCD(MutableBigInteger v) { 6735 // Algorithm B from Knuth section 4.5.2 6736 MutableBigInteger u = this; 6737 MutableBigInteger r = new MutableBigInteger(); 6738 6739 // step B1 6740 int s1 = u.getLowestSetBit(); 6741 int s2 = v.getLowestSetBit(); 6742 int k = (s1 < s2) ? s1 : s2; 6743 if (k != 0) { 6744 u.rightShift(k); 6745 v.rightShift(k); 6746 } 6747 6748 // step B2 6749 bool uOdd = (k == s1); 6750 MutableBigInteger t = uOdd ? v: u; 6751 int tsign = uOdd ? -1 : 1; 6752 6753 int lb; 6754 while ((lb = t.getLowestSetBit()) >= 0) { 6755 // steps B3 and B4 6756 t.rightShift(lb); 6757 // step B5 6758 if (tsign > 0) 6759 u = t; 6760 else 6761 v = t; 6762 6763 // Special case one word numbers 6764 if (u.intLen < 2 && v.intLen < 2) { 6765 int x = u.value[u.offset]; 6766 int y = v.value[v.offset]; 6767 x = binaryGcd(x, y); 6768 r.value[0] = x; 6769 r.intLen = 1; 6770 r.offset = 0; 6771 if (k > 0) 6772 r.leftShift(k); 6773 return r; 6774 } 6775 6776 // step B6 6777 if ((tsign = u.difference(v)) == 0) 6778 break; 6779 t = (tsign >= 0) ? u : v; 6780 } 6781 6782 if (k > 0) 6783 u.leftShift(k); 6784 return u; 6785 } 6786 6787 /** 6788 * Calculate GCD of a and b interpreted as unsigned integers. 6789 */ 6790 static int binaryGcd(int a, int b) { 6791 if (b == 0) 6792 return a; 6793 if (a == 0) 6794 return b; 6795 6796 // Right shift a & b till their last bits equal to 1. 6797 int aZeros = Integer.numberOfTrailingZeros(a); 6798 int bZeros = Integer.numberOfTrailingZeros(b); 6799 a >>>= aZeros; 6800 b >>>= bZeros; 6801 6802 int t = (aZeros < bZeros ? aZeros : bZeros); 6803 6804 while (a != b) { 6805 if ((a+0x80000000) > (b+0x80000000)) { // a > b as unsigned 6806 a -= b; 6807 a >>>= Integer.numberOfTrailingZeros(a); 6808 } else { 6809 b -= a; 6810 b >>>= Integer.numberOfTrailingZeros(b); 6811 } 6812 } 6813 return a<<t; 6814 } 6815 6816 /** 6817 * Returns the modInverse of this mod p. This and p are not affected by 6818 * the operation. 6819 */ 6820 MutableBigInteger mutableModInverse(MutableBigInteger p) { 6821 // Modulus is odd, use Schroeppel's algorithm 6822 if (p.isOdd()) 6823 return modInverse(p); 6824 6825 // Base and modulus are even, throw exception 6826 if (isEven()) 6827 throw new ArithmeticException("BigInteger not invertible."); 6828 6829 // Get even part of modulus expressed as a power of 2 6830 int powersOf2 = p.getLowestSetBit(); 6831 6832 // Construct odd part of modulus 6833 MutableBigInteger oddMod = new MutableBigInteger(p); 6834 oddMod.rightShift(powersOf2); 6835 6836 if (oddMod.isOne()) 6837 return modInverseMP2(powersOf2); 6838 6839 // Calculate 1/a mod oddMod 6840 MutableBigInteger oddPart = modInverse(oddMod); 6841 6842 // Calculate 1/a mod evenMod 6843 MutableBigInteger evenPart = modInverseMP2(powersOf2); 6844 6845 // Combine the results using Chinese Remainder Theorem 6846 MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2); 6847 MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2); 6848 6849 MutableBigInteger temp1 = new MutableBigInteger(); 6850 MutableBigInteger temp2 = new MutableBigInteger(); 6851 MutableBigInteger result = new MutableBigInteger(); 6852 6853 oddPart.leftShift(powersOf2); 6854 oddPart.multiply(y1, result); 6855 6856 evenPart.multiply(oddMod, temp1); 6857 temp1.multiply(y2, temp2); 6858 6859 result.add(temp2); 6860 return result.divide(p, temp1); 6861 } 6862 6863 /* 6864 * Calculate the multiplicative inverse of this mod 2^k. 6865 */ 6866 MutableBigInteger modInverseMP2(int k) { 6867 if (isEven()) 6868 throw new ArithmeticException("Non-invertible. (GCD != 1)"); 6869 6870 if (k > 64) 6871 return euclidModInverse(k); 6872 6873 int t = inverseMod32(value[offset+intLen-1]); 6874 6875 if (k < 33) { 6876 t = (k == 32 ? t : t & ((1 << k) - 1)); 6877 return new MutableBigInteger(t); 6878 } 6879 6880 long pLong = (value[offset+intLen-1] & LONG_MASK); 6881 if (intLen > 1) 6882 pLong |= (cast(long)value[offset+intLen-2] << 32); 6883 long tLong = t & LONG_MASK; 6884 tLong = tLong * (2 - pLong * tLong); // 1 more Newton iter step 6885 tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1)); 6886 6887 MutableBigInteger result = new MutableBigInteger(new int[2]); 6888 result.value[0] = cast(int)(tLong >>> 32); 6889 result.value[1] = cast(int)tLong; 6890 result.intLen = 2; 6891 result.normalize(); 6892 return result; 6893 } 6894 6895 /** 6896 * Returns the multiplicative inverse of val mod 2^32. Assumes val is odd. 6897 */ 6898 static int inverseMod32(int val) { 6899 // Newton's iteration! 6900 int t = val; 6901 t *= 2 - val*t; 6902 t *= 2 - val*t; 6903 t *= 2 - val*t; 6904 t *= 2 - val*t; 6905 return t; 6906 } 6907 6908 /** 6909 * Returns the multiplicative inverse of val mod 2^64. Assumes val is odd. 6910 */ 6911 static long inverseMod64(long val) { 6912 // Newton's iteration! 6913 long t = val; 6914 t *= 2 - val*t; 6915 t *= 2 - val*t; 6916 t *= 2 - val*t; 6917 t *= 2 - val*t; 6918 t *= 2 - val*t; 6919 assert(t * val == 1); 6920 return t; 6921 } 6922 6923 /** 6924 * Calculate the multiplicative inverse of 2^k mod mod, where mod is odd. 6925 */ 6926 static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) { 6927 // Copy the mod to protect original 6928 return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k); 6929 } 6930 6931 /** 6932 * Calculate the multiplicative inverse of this mod mod, where mod is odd. 6933 * This and mod are not changed by the calculation. 6934 * 6935 * This method implements an algorithm due to Richard Schroeppel, that uses 6936 * the same intermediate representation as Montgomery Reduction 6937 * ("Montgomery Form"). The algorithm is described in an unpublished 6938 * manuscript entitled "Fast Modular Reciprocals." 6939 */ 6940 private MutableBigInteger modInverse(MutableBigInteger mod) { 6941 MutableBigInteger p = new MutableBigInteger(mod); 6942 MutableBigInteger f = new MutableBigInteger(this); 6943 MutableBigInteger g = new MutableBigInteger(p); 6944 SignedMutableBigInteger c = new SignedMutableBigInteger(1); 6945 SignedMutableBigInteger d = new SignedMutableBigInteger(); 6946 MutableBigInteger temp = null; 6947 SignedMutableBigInteger sTemp = null; 6948 6949 int k = 0; 6950 // Right shift f k times until odd, left shift d k times 6951 if (f.isEven()) { 6952 int trailingZeros = f.getLowestSetBit(); 6953 f.rightShift(trailingZeros); 6954 d.leftShift(trailingZeros); 6955 k = trailingZeros; 6956 } 6957 6958 // The Almost Inverse Algorithm 6959 while (!f.isOne()) { 6960 // If gcd(f, g) != 1, number is not invertible modulo mod 6961 if (f.isZero()) 6962 throw new ArithmeticException("BigInteger not invertible."); 6963 6964 // If f < g exchange f, g and c, d 6965 if (f.compare(g) < 0) { 6966 temp = f; f = g; g = temp; 6967 sTemp = d; d = c; c = sTemp; 6968 } 6969 6970 // If f == g (mod 4) 6971 if (((f.value[f.offset + f.intLen - 1] ^ 6972 g.value[g.offset + g.intLen - 1]) & 3) == 0) { 6973 f.subtract(g); 6974 c.signedSubtract(d); 6975 } else { // If f != g (mod 4) 6976 f.add(g); 6977 c.signedAdd(d); 6978 } 6979 6980 // Right shift f k times until odd, left shift d k times 6981 int trailingZeros = f.getLowestSetBit(); 6982 f.rightShift(trailingZeros); 6983 d.leftShift(trailingZeros); 6984 k += trailingZeros; 6985 } 6986 6987 while (c.sign < 0) 6988 c.signedAdd(p); 6989 6990 return fixup(c, p, k); 6991 } 6992 6993 /** 6994 * The Fixup Algorithm 6995 * Calculates X such that X = C * 2^(-k) (mod P) 6996 * Assumes C<P and P is odd. 6997 */ 6998 static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p, 6999 int k) { 7000 MutableBigInteger temp = new MutableBigInteger(); 7001 // Set r to the multiplicative inverse of p mod 2^32 7002 int r = -inverseMod32(p.value[p.offset+p.intLen-1]); 7003 7004 for (int i=0, numWords = k >> 5; i < numWords; i++) { 7005 // V = R * c (mod 2^j) 7006 int v = r * c.value[c.offset + c.intLen-1]; 7007 // c = c + (v * p) 7008 p.mul(v, temp); 7009 c.add(temp); 7010 // c = c / 2^j 7011 c.intLen--; 7012 } 7013 int numBits = k & 0x1f; 7014 if (numBits != 0) { 7015 // V = R * c (mod 2^j) 7016 int v = r * c.value[c.offset + c.intLen-1]; 7017 v &= ((1<<numBits) - 1); 7018 // c = c + (v * p) 7019 p.mul(v, temp); 7020 c.add(temp); 7021 // c = c / 2^j 7022 c.rightShift(numBits); 7023 } 7024 7025 // In theory, c may be greater than p at this point (Very rare!) 7026 while (c.compare(p) >= 0) 7027 c.subtract(p); 7028 7029 return c; 7030 } 7031 7032 /** 7033 * Uses the extended Euclidean algorithm to compute the modInverse of base 7034 * mod a modulus that is a power of 2. The modulus is 2^k. 7035 */ 7036 MutableBigInteger euclidModInverse(int k) { 7037 MutableBigInteger b = new MutableBigInteger(1); 7038 b.leftShift(k); 7039 MutableBigInteger mod = new MutableBigInteger(b); 7040 7041 MutableBigInteger a = new MutableBigInteger(this); 7042 MutableBigInteger q = new MutableBigInteger(); 7043 MutableBigInteger r = b.divide(a, q); 7044 7045 MutableBigInteger swapper = b; 7046 // swap b & r 7047 b = r; 7048 r = swapper; 7049 7050 MutableBigInteger t1 = new MutableBigInteger(q); 7051 MutableBigInteger t0 = new MutableBigInteger(1); 7052 MutableBigInteger temp = new MutableBigInteger(); 7053 7054 while (!b.isOne()) { 7055 r = a.divide(b, q); 7056 7057 if (r.intLen == 0) 7058 throw new ArithmeticException("BigInteger not invertible."); 7059 7060 swapper = r; 7061 a = swapper; 7062 7063 if (q.intLen == 1) 7064 t1.mul(q.value[q.offset], temp); 7065 else 7066 q.multiply(t1, temp); 7067 swapper = q; 7068 q = temp; 7069 temp = swapper; 7070 t0.add(q); 7071 7072 if (a.isOne()) 7073 return t0; 7074 7075 r = b.divide(a, q); 7076 7077 if (r.intLen == 0) 7078 throw new ArithmeticException("BigInteger not invertible."); 7079 7080 swapper = b; 7081 b = r; 7082 7083 if (q.intLen == 1) 7084 t0.mul(q.value[q.offset], temp); 7085 else 7086 q.multiply(t0, temp); 7087 swapper = q; q = temp; temp = swapper; 7088 7089 t1.add(q); 7090 } 7091 mod.subtract(t1); 7092 return mod; 7093 } 7094 } 7095 7096 7097 7098 /** 7099 * A class used to represent multiprecision integers that makes efficient 7100 * use of allocated space by allowing a number to occupy only part of 7101 * an array so that the arrays do not have to be reallocated as often. 7102 * When performing an operation with many iterations the array used to 7103 * hold a number is only increased when necessary and does not have to 7104 * be the same size as the number it represents. A mutable number allows 7105 * calculations to occur on the same number without having to create 7106 * a new number for every step of the calculation as occurs with 7107 * BigIntegers. 7108 * 7109 * Note that SignedMutableBigIntegers only support signed addition and 7110 * subtraction. All other operations occur as with MutableBigIntegers. 7111 * 7112 * @see BigInteger 7113 * @author Michael McCloskey 7114 * @since 1.3 7115 */ 7116 7117 class SignedMutableBigInteger : MutableBigInteger { 7118 7119 /** 7120 * The sign of this MutableBigInteger. 7121 */ 7122 int sign = 1; 7123 7124 // Constructors 7125 7126 /** 7127 * The default constructor. An empty MutableBigInteger is created with 7128 * a one word capacity. 7129 */ 7130 this() { 7131 super(); 7132 } 7133 7134 /** 7135 * Construct a new MutableBigInteger with a magnitude specified by 7136 * the int val. 7137 */ 7138 this(int val) { 7139 super(val); 7140 } 7141 7142 /** 7143 * Construct a new MutableBigInteger with a magnitude equal to the 7144 * specified MutableBigInteger. 7145 */ 7146 this(MutableBigInteger val) { 7147 super(val); 7148 } 7149 7150 // Arithmetic Operations 7151 7152 /** 7153 * Signed addition built upon unsigned add and subtract. 7154 */ 7155 void signedAdd(SignedMutableBigInteger addend) { 7156 if (sign == addend.sign) 7157 add(addend); 7158 else 7159 sign = sign * subtract(addend); 7160 7161 } 7162 7163 /** 7164 * Signed addition built upon unsigned add and subtract. 7165 */ 7166 void signedAdd(MutableBigInteger addend) { 7167 if (sign == 1) 7168 add(addend); 7169 else 7170 sign = sign * subtract(addend); 7171 7172 } 7173 7174 /** 7175 * Signed subtraction built upon unsigned add and subtract. 7176 */ 7177 void signedSubtract(SignedMutableBigInteger addend) { 7178 if (sign == addend.sign) 7179 sign = sign * subtract(addend); 7180 else 7181 add(addend); 7182 7183 } 7184 7185 /** 7186 * Signed subtraction built upon unsigned add and subtract. 7187 */ 7188 void signedSubtract(MutableBigInteger addend) { 7189 if (sign == 1) 7190 sign = sign * subtract(addend); 7191 else 7192 add(addend); 7193 if (intLen == 0) 7194 sign = 1; 7195 } 7196 7197 /** 7198 * Print out the first intLen ints of this MutableBigInteger's value 7199 * array starting at offset. 7200 */ 7201 override string toString() { 7202 return this.toBigInteger(sign).toString(); 7203 } 7204 7205 } 7206 7207 7208 7209 /** 7210 * A simple bit sieve used for finding prime number candidates. Allows setting 7211 * and clearing of bits in a storage array. The size of the sieve is assumed to 7212 * be constant to reduce overhead. All the bits of a new bitSieve are zero, and 7213 * bits are removed from it by setting them. 7214 * 7215 * To reduce storage space and increase efficiency, no even numbers are 7216 * represented in the sieve (each bit in the sieve represents an odd number). 7217 * The relationship between the index of a bit and the number it represents is 7218 * given by 7219 * N = offset + (2*index + 1); 7220 * Where N is the integer represented by a bit in the sieve, offset is some 7221 * even integer offset indicating where the sieve begins, and index is the 7222 * index of a bit in the sieve array. 7223 * 7224 * @see BigInteger 7225 * @author Michael McCloskey 7226 * @since 1.3 7227 */ 7228 class BitSieve { 7229 /** 7230 * Stores the bits in this bitSieve. 7231 */ 7232 private long[] bits; 7233 7234 /** 7235 * Length is how many bits this sieve holds. 7236 */ 7237 private int length; 7238 7239 /** 7240 * A small sieve used to filter out multiples of small primes in a search 7241 * sieve. 7242 */ 7243 private __gshared BitSieve smallSieve; 7244 7245 shared static this() { 7246 smallSieve = new BitSieve(); 7247 } 7248 7249 /** 7250 * Construct a "small sieve" with a base of 0. This constructor is 7251 * used internally to generate the set of "small primes" whose multiples 7252 * are excluded from sieves generated by the main (package private) 7253 * constructor, BitSieve(BigInteger base, int searchLen). The length 7254 * of the sieve generated by this constructor was chosen for performance; 7255 * it controls a tradeoff between how much time is spent constructing 7256 * other sieves, and how much time is wasted testing composite candidates 7257 * for primality. The length was chosen experimentally to yield good 7258 * performance. 7259 */ 7260 private this() { 7261 length = 150 * 64; 7262 bits = new long[(unitIndex(length - 1) + 1)]; 7263 7264 // Mark 1 as composite 7265 set(0); 7266 int nextIndex = 1; 7267 int nextPrime = 3; 7268 7269 // Find primes and remove their multiples from sieve 7270 do { 7271 sieveSingle(length, nextIndex + nextPrime, nextPrime); 7272 nextIndex = sieveSearch(length, nextIndex + 1); 7273 nextPrime = 2*nextIndex + 1; 7274 } while((nextIndex > 0) && (nextPrime < length)); 7275 } 7276 7277 /** 7278 * Construct a bit sieve of searchLen bits used for finding prime number 7279 * candidates. The new sieve begins at the specified base, which must 7280 * be even. 7281 */ 7282 this(BigInteger base, int searchLen) { 7283 /* 7284 * Candidates are indicated by clear bits in the sieve. As a candidates 7285 * nonprimality is calculated, a bit is set in the sieve to eliminate 7286 * it. To reduce storage space and increase efficiency, no even numbers 7287 * are represented in the sieve (each bit in the sieve represents an 7288 * odd number). 7289 */ 7290 bits = new long[(unitIndex(searchLen-1) + 1)]; 7291 length = searchLen; 7292 int start = 0; 7293 7294 int step = smallSieve.sieveSearch(smallSieve.length, start); 7295 int convertedStep = (step *2) + 1; 7296 7297 // Construct the large sieve at an even offset specified by base 7298 MutableBigInteger b = new MutableBigInteger(base); 7299 MutableBigInteger q = new MutableBigInteger(); 7300 do { 7301 // Calculate base mod convertedStep 7302 start = b.divideOneWord(convertedStep, q); 7303 7304 // Take each multiple of step out of sieve 7305 start = convertedStep - start; 7306 if (start%2 == 0) 7307 start += convertedStep; 7308 sieveSingle(searchLen, (start-1)/2, convertedStep); 7309 7310 // Find next prime from small sieve 7311 step = smallSieve.sieveSearch(smallSieve.length, step+1); 7312 convertedStep = (step *2) + 1; 7313 } while (step > 0); 7314 } 7315 7316 /** 7317 * Given a bit index return unit index containing it. 7318 */ 7319 private static int unitIndex(int bitIndex) { 7320 return bitIndex >>> 6; 7321 } 7322 7323 /** 7324 * Return a unit that masks the specified bit in its unit. 7325 */ 7326 private static long bit(int bitIndex) { 7327 return 1L << (bitIndex & ((1<<6) - 1)); 7328 } 7329 7330 /** 7331 * Get the value of the bit at the specified index. 7332 */ 7333 private bool get(int bitIndex) { 7334 int unitIndex = unitIndex(bitIndex); 7335 return ((bits[unitIndex] & bit(bitIndex)) != 0); 7336 } 7337 7338 /** 7339 * Set the bit at the specified index. 7340 */ 7341 private void set(int bitIndex) { 7342 int unitIndex = unitIndex(bitIndex); 7343 bits[unitIndex] |= bit(bitIndex); 7344 } 7345 7346 /** 7347 * This method returns the index of the first clear bit in the search 7348 * array that occurs at or after start. It will not search past the 7349 * specified limit. It returns -1 if there is no such clear bit. 7350 */ 7351 private int sieveSearch(int limit, int start) { 7352 if (start >= limit) 7353 return -1; 7354 7355 int index = start; 7356 do { 7357 if (!get(index)) 7358 return index; 7359 index++; 7360 } while(index < limit-1); 7361 return -1; 7362 } 7363 7364 /** 7365 * Sieve a single set of multiples out of the sieve. Begin to remove 7366 * multiples of the specified step starting at the specified start index, 7367 * up to the specified limit. 7368 */ 7369 private void sieveSingle(int limit, int start, int step) { 7370 while(start < limit) { 7371 set(start); 7372 start += step; 7373 } 7374 } 7375 7376 /** 7377 * Test probable primes in the sieve and return successful candidates. 7378 */ 7379 BigInteger retrieve(BigInteger initValue, int certainty, Random* random) { 7380 // Examine the sieve one long at a time to find possible primes 7381 int offset = 1; 7382 for (int i=0; i<bits.length; i++) { 7383 long nextLong = ~bits[i]; 7384 for (int j=0; j<64; j++) { 7385 if ((nextLong & 1) == 1) { 7386 BigInteger candidate = initValue.add( 7387 BigInteger.valueOf(offset)); 7388 if (candidate.primeToCertainty(certainty, random)) 7389 return candidate; 7390 } 7391 nextLong >>>= 1; 7392 offset+=2; 7393 } 7394 } 7395 return null; 7396 } 7397 7398 }