1 /* 2 * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.math; 27 28 /** 29 * A class used to represent multiprecision integers that makes efficient 30 * use of allocated space by allowing a number to occupy only part of 31 * an array so that the arrays do not have to be reallocated as often. 32 * When performing an operation with many iterations the array used to 33 * hold a number is only reallocated when necessary and does not have to 34 * be the same size as the number it represents. A mutable number allows 35 * calculations to occur on the same number without having to create 36 * a new number for every step of the calculation as occurs with 37 * BigIntegers. 38 * 39 * @see BigInteger 40 * @author Michael McCloskey 41 * @author Timothy Buktu 42 * @since 1.3 43 */ 44 45 import static java.math.BigDecimal.INFLATED; 46 import static java.math.BigInteger.LONG_MASK; 47 import java.util.Arrays; 48 49 class MutableBigInteger { 50 /** 51 * Holds the magnitude of this MutableBigInteger in big endian order. 52 * The magnitude may start at an offset into the value array, and it may 53 * end before the length of the value array. 54 */ 55 int[] value; 56 57 /** 58 * The number of ints of the value array that are currently used 59 * to hold the magnitude of this MutableBigInteger. The magnitude starts 60 * at an offset and offset + intLen may be less than value.length. 61 */ 62 int intLen; 63 64 /** 65 * The offset into the value array where the magnitude of this 66 * MutableBigInteger begins. 67 */ 68 int offset = 0; 69 70 // Constants 71 /** 72 * MutableBigInteger with one element value array with the value 1. Used by 73 * BigDecimal divideAndRound to increment the quotient. Use this constant 74 * only when the method is not going to modify this object. 75 */ 76 static final MutableBigInteger ONE = new MutableBigInteger(1); 77 78 /** 79 * The minimum {@code intLen} for cancelling powers of two before 80 * dividing. 81 * If the number of ints is less than this threshold, 82 * {@code divideKnuth} does not eliminate common powers of two from 83 * the dividend and divisor. 84 */ 85 static final int KNUTH_POW2_THRESH_LEN = 6; 86 87 /** 88 * The minimum number of trailing zero ints for cancelling powers of two 89 * before dividing. 90 * If the dividend and divisor don't share at least this many zero ints 91 * at the end, {@code divideKnuth} does not eliminate common powers 92 * of two from the dividend and divisor. 93 */ 94 static final int KNUTH_POW2_THRESH_ZEROS = 3; 95 96 // Constructors 97 98 /** 99 * The default constructor. An empty MutableBigInteger is created with 100 * a one word capacity. 101 */ MutableBigInteger()102 MutableBigInteger() { 103 value = new int[1]; 104 intLen = 0; 105 } 106 107 /** 108 * Construct a new MutableBigInteger with a magnitude specified by 109 * the int val. 110 */ MutableBigInteger(int val)111 MutableBigInteger(int val) { 112 value = new int[1]; 113 intLen = 1; 114 value[0] = val; 115 } 116 117 /** 118 * Construct a new MutableBigInteger with the specified value array 119 * up to the length of the array supplied. 120 */ MutableBigInteger(int[] val)121 MutableBigInteger(int[] val) { 122 value = val; 123 intLen = val.length; 124 } 125 126 /** 127 * Construct a new MutableBigInteger with a magnitude equal to the 128 * specified BigInteger. 129 */ MutableBigInteger(BigInteger b)130 MutableBigInteger(BigInteger b) { 131 intLen = b.mag.length; 132 value = Arrays.copyOf(b.mag, intLen); 133 } 134 135 /** 136 * Construct a new MutableBigInteger with a magnitude equal to the 137 * specified MutableBigInteger. 138 */ MutableBigInteger(MutableBigInteger val)139 MutableBigInteger(MutableBigInteger val) { 140 intLen = val.intLen; 141 value = Arrays.copyOfRange(val.value, val.offset, val.offset + intLen); 142 } 143 144 /** 145 * Makes this number an {@code n}-int number all of whose bits are ones. 146 * Used by Burnikel-Ziegler division. 147 * @param n number of ints in the {@code value} array 148 */ ones(int n)149 private void ones(int n) { 150 if (n > value.length) 151 value = new int[n]; 152 Arrays.fill(value, -1); 153 offset = 0; 154 intLen = n; 155 } 156 157 /** 158 * Internal helper method to return the magnitude array. The caller is not 159 * supposed to modify the returned array. 160 */ getMagnitudeArray()161 private int[] getMagnitudeArray() { 162 if (offset > 0 || value.length != intLen) { 163 // Shrink value to be the total magnitude 164 int[] tmp = Arrays.copyOfRange(value, offset, offset + intLen); 165 Arrays.fill(value, 0); 166 offset = 0; 167 intLen = tmp.length; 168 value = tmp; 169 } 170 return value; 171 } 172 173 /** 174 * Convert this MutableBigInteger to a long value. The caller has to make 175 * sure this MutableBigInteger can be fit into long. 176 */ toLong()177 private long toLong() { 178 assert (intLen <= 2) : "this MutableBigInteger exceeds the range of long"; 179 if (intLen == 0) 180 return 0; 181 long d = value[offset] & LONG_MASK; 182 return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d; 183 } 184 185 /** 186 * Convert this MutableBigInteger to a BigInteger object. 187 */ toBigInteger(int sign)188 BigInteger toBigInteger(int sign) { 189 if (intLen == 0 || sign == 0) 190 return BigInteger.ZERO; 191 return new BigInteger(getMagnitudeArray(), sign); 192 } 193 194 /** 195 * Converts this number to a nonnegative {@code BigInteger}. 196 */ toBigInteger()197 BigInteger toBigInteger() { 198 normalize(); 199 return toBigInteger(isZero() ? 0 : 1); 200 } 201 202 /** 203 * Convert this MutableBigInteger to BigDecimal object with the specified sign 204 * and scale. 205 */ toBigDecimal(int sign, int scale)206 BigDecimal toBigDecimal(int sign, int scale) { 207 if (intLen == 0 || sign == 0) 208 return BigDecimal.zeroValueOf(scale); 209 int[] mag = getMagnitudeArray(); 210 int len = mag.length; 211 int d = mag[0]; 212 // If this MutableBigInteger can't be fit into long, we need to 213 // make a BigInteger object for the resultant BigDecimal object. 214 if (len > 2 || (d < 0 && len == 2)) 215 return new BigDecimal(new BigInteger(mag, sign), INFLATED, scale, 0); 216 long v = (len == 2) ? 217 ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) : 218 d & LONG_MASK; 219 return BigDecimal.valueOf(sign == -1 ? -v : v, scale); 220 } 221 222 /** 223 * This is for internal use in converting from a MutableBigInteger 224 * object into a long value given a specified sign. 225 * returns INFLATED if value is not fit into long 226 */ toCompactValue(int sign)227 long toCompactValue(int sign) { 228 if (intLen == 0 || sign == 0) 229 return 0L; 230 int[] mag = getMagnitudeArray(); 231 int len = mag.length; 232 int d = mag[0]; 233 // If this MutableBigInteger can not be fitted into long, we need to 234 // make a BigInteger object for the resultant BigDecimal object. 235 if (len > 2 || (d < 0 && len == 2)) 236 return INFLATED; 237 long v = (len == 2) ? 238 ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) : 239 d & LONG_MASK; 240 return sign == -1 ? -v : v; 241 } 242 243 /** 244 * Clear out a MutableBigInteger for reuse. 245 */ clear()246 void clear() { 247 offset = intLen = 0; 248 for (int index=0, n=value.length; index < n; index++) 249 value[index] = 0; 250 } 251 252 /** 253 * Set a MutableBigInteger to zero, removing its offset. 254 */ reset()255 void reset() { 256 offset = intLen = 0; 257 } 258 259 /** 260 * Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1 261 * as this MutableBigInteger is numerically less than, equal to, or 262 * greater than {@code b}. 263 */ compare(MutableBigInteger b)264 final int compare(MutableBigInteger b) { 265 int blen = b.intLen; 266 if (intLen < blen) 267 return -1; 268 if (intLen > blen) 269 return 1; 270 271 // Add Integer.MIN_VALUE to make the comparison act as unsigned integer 272 // comparison. 273 int[] bval = b.value; 274 for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) { 275 int b1 = value[i] + 0x80000000; 276 int b2 = bval[j] + 0x80000000; 277 if (b1 < b2) 278 return -1; 279 if (b1 > b2) 280 return 1; 281 } 282 return 0; 283 } 284 285 /** 286 * Returns a value equal to what {@code b.leftShift(32*ints); return compare(b);} 287 * would return, but doesn't change the value of {@code b}. 288 */ compareShifted(MutableBigInteger b, int ints)289 private int compareShifted(MutableBigInteger b, int ints) { 290 int blen = b.intLen; 291 int alen = intLen - ints; 292 if (alen < blen) 293 return -1; 294 if (alen > blen) 295 return 1; 296 297 // Add Integer.MIN_VALUE to make the comparison act as unsigned integer 298 // comparison. 299 int[] bval = b.value; 300 for (int i = offset, j = b.offset; i < alen + offset; i++, j++) { 301 int b1 = value[i] + 0x80000000; 302 int b2 = bval[j] + 0x80000000; 303 if (b1 < b2) 304 return -1; 305 if (b1 > b2) 306 return 1; 307 } 308 return 0; 309 } 310 311 /** 312 * Compare this against half of a MutableBigInteger object (Needed for 313 * remainder tests). 314 * Assumes no leading unnecessary zeros, which holds for results 315 * from divide(). 316 */ compareHalf(MutableBigInteger b)317 final int compareHalf(MutableBigInteger b) { 318 int blen = b.intLen; 319 int len = intLen; 320 if (len <= 0) 321 return blen <= 0 ? 0 : -1; 322 if (len > blen) 323 return 1; 324 if (len < blen - 1) 325 return -1; 326 int[] bval = b.value; 327 int bstart = 0; 328 int carry = 0; 329 // Only 2 cases left:len == blen or len == blen - 1 330 if (len != blen) { // len == blen - 1 331 if (bval[bstart] == 1) { 332 ++bstart; 333 carry = 0x80000000; 334 } else 335 return -1; 336 } 337 // compare values with right-shifted values of b, 338 // carrying shifted-out bits across words 339 int[] val = value; 340 for (int i = offset, j = bstart; i < len + offset;) { 341 int bv = bval[j++]; 342 long hb = ((bv >>> 1) + carry) & LONG_MASK; 343 long v = val[i++] & LONG_MASK; 344 if (v != hb) 345 return v < hb ? -1 : 1; 346 carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0 347 } 348 return carry == 0 ? 0 : -1; 349 } 350 351 /** 352 * Return the index of the lowest set bit in this MutableBigInteger. If the 353 * magnitude of this MutableBigInteger is zero, -1 is returned. 354 */ getLowestSetBit()355 private final int getLowestSetBit() { 356 if (intLen == 0) 357 return -1; 358 int j, b; 359 for (j=intLen-1; (j > 0) && (value[j+offset] == 0); j--) 360 ; 361 b = value[j+offset]; 362 if (b == 0) 363 return -1; 364 return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b); 365 } 366 367 /** 368 * Return the int in use in this MutableBigInteger at the specified 369 * index. This method is not used because it is not inlined on all 370 * platforms. 371 */ getInt(int index)372 private final int getInt(int index) { 373 return value[offset+index]; 374 } 375 376 /** 377 * Return a long which is equal to the unsigned value of the int in 378 * use in this MutableBigInteger at the specified index. This method is 379 * not used because it is not inlined on all platforms. 380 */ getLong(int index)381 private final long getLong(int index) { 382 return value[offset+index] & LONG_MASK; 383 } 384 385 /** 386 * Ensure that the MutableBigInteger is in normal form, specifically 387 * making sure that there are no leading zeros, and that if the 388 * magnitude is zero, then intLen is zero. 389 */ normalize()390 final void normalize() { 391 if (intLen == 0) { 392 offset = 0; 393 return; 394 } 395 396 int index = offset; 397 if (value[index] != 0) 398 return; 399 400 int indexBound = index+intLen; 401 do { 402 index++; 403 } while(index < indexBound && value[index] == 0); 404 405 int numZeros = index - offset; 406 intLen -= numZeros; 407 offset = (intLen == 0 ? 0 : offset+numZeros); 408 } 409 410 /** 411 * If this MutableBigInteger cannot hold len words, increase the size 412 * of the value array to len words. 413 */ ensureCapacity(int len)414 private final void ensureCapacity(int len) { 415 if (value.length < len) { 416 value = new int[len]; 417 offset = 0; 418 intLen = len; 419 } 420 } 421 422 /** 423 * Convert this MutableBigInteger into an int array with no leading 424 * zeros, of a length that is equal to this MutableBigInteger's intLen. 425 */ toIntArray()426 int[] toIntArray() { 427 int[] result = new int[intLen]; 428 for(int i=0; i < intLen; i++) 429 result[i] = value[offset+i]; 430 return result; 431 } 432 433 /** 434 * Sets the int at index+offset in this MutableBigInteger to val. 435 * This does not get inlined on all platforms so it is not used 436 * as often as originally intended. 437 */ setInt(int index, int val)438 void setInt(int index, int val) { 439 value[offset + index] = val; 440 } 441 442 /** 443 * Sets this MutableBigInteger's value array to the specified array. 444 * The intLen is set to the specified length. 445 */ setValue(int[] val, int length)446 void setValue(int[] val, int length) { 447 value = val; 448 intLen = length; 449 offset = 0; 450 } 451 452 /** 453 * Sets this MutableBigInteger's value array to a copy of the specified 454 * array. The intLen is set to the length of the new array. 455 */ copyValue(MutableBigInteger src)456 void copyValue(MutableBigInteger src) { 457 int len = src.intLen; 458 if (value.length < len) 459 value = new int[len]; 460 System.arraycopy(src.value, src.offset, value, 0, len); 461 intLen = len; 462 offset = 0; 463 } 464 465 /** 466 * Sets this MutableBigInteger's value array to a copy of the specified 467 * array. The intLen is set to the length of the specified array. 468 */ copyValue(int[] val)469 void copyValue(int[] val) { 470 int len = val.length; 471 if (value.length < len) 472 value = new int[len]; 473 System.arraycopy(val, 0, value, 0, len); 474 intLen = len; 475 offset = 0; 476 } 477 478 /** 479 * Returns true iff this MutableBigInteger has a value of one. 480 */ isOne()481 boolean isOne() { 482 return (intLen == 1) && (value[offset] == 1); 483 } 484 485 /** 486 * Returns true iff this MutableBigInteger has a value of zero. 487 */ isZero()488 boolean isZero() { 489 return (intLen == 0); 490 } 491 492 /** 493 * Returns true iff this MutableBigInteger is even. 494 */ isEven()495 boolean isEven() { 496 return (intLen == 0) || ((value[offset + intLen - 1] & 1) == 0); 497 } 498 499 /** 500 * Returns true iff this MutableBigInteger is odd. 501 */ isOdd()502 boolean isOdd() { 503 return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1); 504 } 505 506 /** 507 * Returns true iff this MutableBigInteger is in normal form. A 508 * MutableBigInteger is in normal form if it has no leading zeros 509 * after the offset, and intLen + offset <= value.length. 510 */ isNormal()511 boolean isNormal() { 512 if (intLen + offset > value.length) 513 return false; 514 if (intLen == 0) 515 return true; 516 return (value[offset] != 0); 517 } 518 519 /** 520 * Returns a String representation of this MutableBigInteger in radix 10. 521 */ toString()522 public String toString() { 523 BigInteger b = toBigInteger(1); 524 return b.toString(); 525 } 526 527 /** 528 * Like {@link #rightShift(int)} but {@code n} can be greater than the length of the number. 529 */ safeRightShift(int n)530 void safeRightShift(int n) { 531 if (n/32 >= intLen) { 532 reset(); 533 } else { 534 rightShift(n); 535 } 536 } 537 538 /** 539 * Right shift this MutableBigInteger n bits. The MutableBigInteger is left 540 * in normal form. 541 */ rightShift(int n)542 void rightShift(int n) { 543 if (intLen == 0) 544 return; 545 int nInts = n >>> 5; 546 int nBits = n & 0x1F; 547 this.intLen -= nInts; 548 if (nBits == 0) 549 return; 550 int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]); 551 if (nBits >= bitsInHighWord) { 552 this.primitiveLeftShift(32 - nBits); 553 this.intLen--; 554 } else { 555 primitiveRightShift(nBits); 556 } 557 } 558 559 /** 560 * Like {@link #leftShift(int)} but {@code n} can be zero. 561 */ safeLeftShift(int n)562 void safeLeftShift(int n) { 563 if (n > 0) { 564 leftShift(n); 565 } 566 } 567 568 /** 569 * Left shift this MutableBigInteger n bits. 570 */ leftShift(int n)571 void leftShift(int n) { 572 /* 573 * If there is enough storage space in this MutableBigInteger already 574 * the available space will be used. Space to the right of the used 575 * ints in the value array is faster to utilize, so the extra space 576 * will be taken from the right if possible. 577 */ 578 if (intLen == 0) 579 return; 580 int nInts = n >>> 5; 581 int nBits = n&0x1F; 582 int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]); 583 584 // If shift can be done without moving words, do so 585 if (n <= (32-bitsInHighWord)) { 586 primitiveLeftShift(nBits); 587 return; 588 } 589 590 int newLen = intLen + nInts +1; 591 if (nBits <= (32-bitsInHighWord)) 592 newLen--; 593 if (value.length < newLen) { 594 // The array must grow 595 int[] result = new int[newLen]; 596 for (int i=0; i < intLen; i++) 597 result[i] = value[offset+i]; 598 setValue(result, newLen); 599 } else if (value.length - offset >= newLen) { 600 // Use space on right 601 for(int i=0; i < newLen - intLen; i++) 602 value[offset+intLen+i] = 0; 603 } else { 604 // Must use space on left 605 for (int i=0; i < intLen; i++) 606 value[i] = value[offset+i]; 607 for (int i=intLen; i < newLen; i++) 608 value[i] = 0; 609 offset = 0; 610 } 611 intLen = newLen; 612 if (nBits == 0) 613 return; 614 if (nBits <= (32-bitsInHighWord)) 615 primitiveLeftShift(nBits); 616 else 617 primitiveRightShift(32 -nBits); 618 } 619 620 /** 621 * A primitive used for division. This method adds in one multiple of the 622 * divisor a back to the dividend result at a specified offset. It is used 623 * when qhat was estimated too large, and must be adjusted. 624 */ divadd(int[] a, int[] result, int offset)625 private int divadd(int[] a, int[] result, int offset) { 626 long carry = 0; 627 628 for (int j=a.length-1; j >= 0; j--) { 629 long sum = (a[j] & LONG_MASK) + 630 (result[j+offset] & LONG_MASK) + carry; 631 result[j+offset] = (int)sum; 632 carry = sum >>> 32; 633 } 634 return (int)carry; 635 } 636 637 /** 638 * This method is used for division. It multiplies an n word input a by one 639 * word input x, and subtracts the n word product from q. This is needed 640 * when subtracting qhat*divisor from dividend. 641 */ mulsub(int[] q, int[] a, int x, int len, int offset)642 private int mulsub(int[] q, int[] a, int x, int len, int offset) { 643 long xLong = x & LONG_MASK; 644 long carry = 0; 645 offset += len; 646 647 for (int j=len-1; j >= 0; j--) { 648 long product = (a[j] & LONG_MASK) * xLong + carry; 649 long difference = q[offset] - product; 650 q[offset--] = (int)difference; 651 carry = (product >>> 32) 652 + (((difference & LONG_MASK) > 653 (((~(int)product) & LONG_MASK))) ? 1:0); 654 } 655 return (int)carry; 656 } 657 658 /** 659 * The method is the same as mulsun, except the fact that q array is not 660 * updated, the only result of the method is borrow flag. 661 */ mulsubBorrow(int[] q, int[] a, int x, int len, int offset)662 private int mulsubBorrow(int[] q, int[] a, int x, int len, int offset) { 663 long xLong = x & LONG_MASK; 664 long carry = 0; 665 offset += len; 666 for (int j=len-1; j >= 0; j--) { 667 long product = (a[j] & LONG_MASK) * xLong + carry; 668 long difference = q[offset--] - product; 669 carry = (product >>> 32) 670 + (((difference & LONG_MASK) > 671 (((~(int)product) & LONG_MASK))) ? 1:0); 672 } 673 return (int)carry; 674 } 675 676 /** 677 * Right shift this MutableBigInteger n bits, where n is 678 * less than 32. 679 * Assumes that intLen > 0, n > 0 for speed 680 */ primitiveRightShift(int n)681 private final void primitiveRightShift(int n) { 682 int[] val = value; 683 int n2 = 32 - n; 684 for (int i=offset+intLen-1, c=val[i]; i > offset; i--) { 685 int b = c; 686 c = val[i-1]; 687 val[i] = (c << n2) | (b >>> n); 688 } 689 val[offset] >>>= n; 690 } 691 692 /** 693 * Left shift this MutableBigInteger n bits, where n is 694 * less than 32. 695 * Assumes that intLen > 0, n > 0 for speed 696 */ primitiveLeftShift(int n)697 private final void primitiveLeftShift(int n) { 698 int[] val = value; 699 int n2 = 32 - n; 700 for (int i=offset, c=val[i], m=i+intLen-1; i < m; i++) { 701 int b = c; 702 c = val[i+1]; 703 val[i] = (b << n) | (c >>> n2); 704 } 705 val[offset+intLen-1] <<= n; 706 } 707 708 /** 709 * Returns a {@code BigInteger} equal to the {@code n} 710 * low ints of this number. 711 */ getLower(int n)712 private BigInteger getLower(int n) { 713 if (isZero()) { 714 return BigInteger.ZERO; 715 } else if (intLen < n) { 716 return toBigInteger(1); 717 } else { 718 // strip zeros 719 int len = n; 720 while (len > 0 && value[offset+intLen-len] == 0) 721 len--; 722 int sign = len > 0 ? 1 : 0; 723 return new BigInteger(Arrays.copyOfRange(value, offset+intLen-len, offset+intLen), sign); 724 } 725 } 726 727 /** 728 * Discards all ints whose index is greater than {@code n}. 729 */ keepLower(int n)730 private void keepLower(int n) { 731 if (intLen >= n) { 732 offset += intLen - n; 733 intLen = n; 734 } 735 } 736 737 /** 738 * Adds the contents of two MutableBigInteger objects.The result 739 * is placed within this MutableBigInteger. 740 * The contents of the addend are not changed. 741 */ add(MutableBigInteger addend)742 void add(MutableBigInteger addend) { 743 int x = intLen; 744 int y = addend.intLen; 745 int resultLen = (intLen > addend.intLen ? intLen : addend.intLen); 746 int[] result = (value.length < resultLen ? new int[resultLen] : value); 747 748 int rstart = result.length-1; 749 long sum; 750 long carry = 0; 751 752 // Add common parts of both numbers 753 while(x > 0 && y > 0) { 754 x--; y--; 755 sum = (value[x+offset] & LONG_MASK) + 756 (addend.value[y+addend.offset] & LONG_MASK) + carry; 757 result[rstart--] = (int)sum; 758 carry = sum >>> 32; 759 } 760 761 // Add remainder of the longer number 762 while(x > 0) { 763 x--; 764 if (carry == 0 && result == value && rstart == (x + offset)) 765 return; 766 sum = (value[x+offset] & LONG_MASK) + carry; 767 result[rstart--] = (int)sum; 768 carry = sum >>> 32; 769 } 770 while(y > 0) { 771 y--; 772 sum = (addend.value[y+addend.offset] & LONG_MASK) + carry; 773 result[rstart--] = (int)sum; 774 carry = sum >>> 32; 775 } 776 777 if (carry > 0) { // Result must grow in length 778 resultLen++; 779 if (result.length < resultLen) { 780 int temp[] = new int[resultLen]; 781 // Result one word longer from carry-out; copy low-order 782 // bits into new result. 783 System.arraycopy(result, 0, temp, 1, result.length); 784 temp[0] = 1; 785 result = temp; 786 } else { 787 result[rstart--] = 1; 788 } 789 } 790 791 value = result; 792 intLen = resultLen; 793 offset = result.length - resultLen; 794 } 795 796 /** 797 * Adds the value of {@code addend} shifted {@code n} ints to the left. 798 * Has the same effect as {@code addend.leftShift(32*ints); add(addend);} 799 * but doesn't change the value of {@code addend}. 800 */ addShifted(MutableBigInteger addend, int n)801 void addShifted(MutableBigInteger addend, int n) { 802 if (addend.isZero()) { 803 return; 804 } 805 806 int x = intLen; 807 int y = addend.intLen + n; 808 int resultLen = (intLen > y ? intLen : y); 809 int[] result = (value.length < resultLen ? new int[resultLen] : value); 810 811 int rstart = result.length-1; 812 long sum; 813 long carry = 0; 814 815 // Add common parts of both numbers 816 while (x > 0 && y > 0) { 817 x--; y--; 818 int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0; 819 sum = (value[x+offset] & LONG_MASK) + 820 (bval & LONG_MASK) + carry; 821 result[rstart--] = (int)sum; 822 carry = sum >>> 32; 823 } 824 825 // Add remainder of the longer number 826 while (x > 0) { 827 x--; 828 if (carry == 0 && result == value && rstart == (x + offset)) { 829 return; 830 } 831 sum = (value[x+offset] & LONG_MASK) + carry; 832 result[rstart--] = (int)sum; 833 carry = sum >>> 32; 834 } 835 while (y > 0) { 836 y--; 837 int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0; 838 sum = (bval & LONG_MASK) + carry; 839 result[rstart--] = (int)sum; 840 carry = sum >>> 32; 841 } 842 843 if (carry > 0) { // Result must grow in length 844 resultLen++; 845 if (result.length < resultLen) { 846 int temp[] = new int[resultLen]; 847 // Result one word longer from carry-out; copy low-order 848 // bits into new result. 849 System.arraycopy(result, 0, temp, 1, result.length); 850 temp[0] = 1; 851 result = temp; 852 } else { 853 result[rstart--] = 1; 854 } 855 } 856 857 value = result; 858 intLen = resultLen; 859 offset = result.length - resultLen; 860 } 861 862 /** 863 * Like {@link #addShifted(MutableBigInteger, int)} but {@code this.intLen} must 864 * not be greater than {@code n}. In other words, concatenates {@code this} 865 * and {@code addend}. 866 */ addDisjoint(MutableBigInteger addend, int n)867 void addDisjoint(MutableBigInteger addend, int n) { 868 if (addend.isZero()) 869 return; 870 871 int x = intLen; 872 int y = addend.intLen + n; 873 int resultLen = (intLen > y ? intLen : y); 874 int[] result; 875 if (value.length < resultLen) 876 result = new int[resultLen]; 877 else { 878 result = value; 879 Arrays.fill(value, offset+intLen, value.length, 0); 880 } 881 882 int rstart = result.length-1; 883 884 // copy from this if needed 885 System.arraycopy(value, offset, result, rstart+1-x, x); 886 y -= x; 887 rstart -= x; 888 889 int len = Math.min(y, addend.value.length-addend.offset); 890 System.arraycopy(addend.value, addend.offset, result, rstart+1-y, len); 891 892 // zero the gap 893 for (int i=rstart+1-y+len; i < rstart+1; i++) 894 result[i] = 0; 895 896 value = result; 897 intLen = resultLen; 898 offset = result.length - resultLen; 899 } 900 901 /** 902 * Adds the low {@code n} ints of {@code addend}. 903 */ addLower(MutableBigInteger addend, int n)904 void addLower(MutableBigInteger addend, int n) { 905 MutableBigInteger a = new MutableBigInteger(addend); 906 if (a.offset + a.intLen >= n) { 907 a.offset = a.offset + a.intLen - n; 908 a.intLen = n; 909 } 910 a.normalize(); 911 add(a); 912 } 913 914 /** 915 * Subtracts the smaller of this and b from the larger and places the 916 * result into this MutableBigInteger. 917 */ subtract(MutableBigInteger b)918 int subtract(MutableBigInteger b) { 919 MutableBigInteger a = this; 920 921 int[] result = value; 922 int sign = a.compare(b); 923 924 if (sign == 0) { 925 reset(); 926 return 0; 927 } 928 if (sign < 0) { 929 MutableBigInteger tmp = a; 930 a = b; 931 b = tmp; 932 } 933 934 int resultLen = a.intLen; 935 if (result.length < resultLen) 936 result = new int[resultLen]; 937 938 long diff = 0; 939 int x = a.intLen; 940 int y = b.intLen; 941 int rstart = result.length - 1; 942 943 // Subtract common parts of both numbers 944 while (y > 0) { 945 x--; y--; 946 947 diff = (a.value[x+a.offset] & LONG_MASK) - 948 (b.value[y+b.offset] & LONG_MASK) - ((int)-(diff>>32)); 949 result[rstart--] = (int)diff; 950 } 951 // Subtract remainder of longer number 952 while (x > 0) { 953 x--; 954 diff = (a.value[x+a.offset] & LONG_MASK) - ((int)-(diff>>32)); 955 result[rstart--] = (int)diff; 956 } 957 958 value = result; 959 intLen = resultLen; 960 offset = value.length - resultLen; 961 normalize(); 962 return sign; 963 } 964 965 /** 966 * Subtracts the smaller of a and b from the larger and places the result 967 * into the larger. Returns 1 if the answer is in a, -1 if in b, 0 if no 968 * operation was performed. 969 */ difference(MutableBigInteger b)970 private int difference(MutableBigInteger b) { 971 MutableBigInteger a = this; 972 int sign = a.compare(b); 973 if (sign == 0) 974 return 0; 975 if (sign < 0) { 976 MutableBigInteger tmp = a; 977 a = b; 978 b = tmp; 979 } 980 981 long diff = 0; 982 int x = a.intLen; 983 int y = b.intLen; 984 985 // Subtract common parts of both numbers 986 while (y > 0) { 987 x--; y--; 988 diff = (a.value[a.offset+ x] & LONG_MASK) - 989 (b.value[b.offset+ y] & LONG_MASK) - ((int)-(diff>>32)); 990 a.value[a.offset+x] = (int)diff; 991 } 992 // Subtract remainder of longer number 993 while (x > 0) { 994 x--; 995 diff = (a.value[a.offset+ x] & LONG_MASK) - ((int)-(diff>>32)); 996 a.value[a.offset+x] = (int)diff; 997 } 998 999 a.normalize(); 1000 return sign; 1001 } 1002 1003 /** 1004 * Multiply the contents of two MutableBigInteger objects. The result is 1005 * placed into MutableBigInteger z. The contents of y are not changed. 1006 */ multiply(MutableBigInteger y, MutableBigInteger z)1007 void multiply(MutableBigInteger y, MutableBigInteger z) { 1008 int xLen = intLen; 1009 int yLen = y.intLen; 1010 int newLen = xLen + yLen; 1011 1012 // Put z into an appropriate state to receive product 1013 if (z.value.length < newLen) 1014 z.value = new int[newLen]; 1015 z.offset = 0; 1016 z.intLen = newLen; 1017 1018 // The first iteration is hoisted out of the loop to avoid extra add 1019 long carry = 0; 1020 for (int j=yLen-1, k=yLen+xLen-1; j >= 0; j--, k--) { 1021 long product = (y.value[j+y.offset] & LONG_MASK) * 1022 (value[xLen-1+offset] & LONG_MASK) + carry; 1023 z.value[k] = (int)product; 1024 carry = product >>> 32; 1025 } 1026 z.value[xLen-1] = (int)carry; 1027 1028 // Perform the multiplication word by word 1029 for (int i = xLen-2; i >= 0; i--) { 1030 carry = 0; 1031 for (int j=yLen-1, k=yLen+i; j >= 0; j--, k--) { 1032 long product = (y.value[j+y.offset] & LONG_MASK) * 1033 (value[i+offset] & LONG_MASK) + 1034 (z.value[k] & LONG_MASK) + carry; 1035 z.value[k] = (int)product; 1036 carry = product >>> 32; 1037 } 1038 z.value[i] = (int)carry; 1039 } 1040 1041 // Remove leading zeros from product 1042 z.normalize(); 1043 } 1044 1045 /** 1046 * Multiply the contents of this MutableBigInteger by the word y. The 1047 * result is placed into z. 1048 */ mul(int y, MutableBigInteger z)1049 void mul(int y, MutableBigInteger z) { 1050 if (y == 1) { 1051 z.copyValue(this); 1052 return; 1053 } 1054 1055 if (y == 0) { 1056 z.clear(); 1057 return; 1058 } 1059 1060 // Perform the multiplication word by word 1061 long ylong = y & LONG_MASK; 1062 int[] zval = (z.value.length < intLen+1 ? new int[intLen + 1] 1063 : z.value); 1064 long carry = 0; 1065 for (int i = intLen-1; i >= 0; i--) { 1066 long product = ylong * (value[i+offset] & LONG_MASK) + carry; 1067 zval[i+1] = (int)product; 1068 carry = product >>> 32; 1069 } 1070 1071 if (carry == 0) { 1072 z.offset = 1; 1073 z.intLen = intLen; 1074 } else { 1075 z.offset = 0; 1076 z.intLen = intLen + 1; 1077 zval[0] = (int)carry; 1078 } 1079 z.value = zval; 1080 } 1081 1082 /** 1083 * This method is used for division of an n word dividend by a one word 1084 * divisor. The quotient is placed into quotient. The one word divisor is 1085 * specified by divisor. 1086 * 1087 * @return the remainder of the division is returned. 1088 * 1089 */ divideOneWord(int divisor, MutableBigInteger quotient)1090 int divideOneWord(int divisor, MutableBigInteger quotient) { 1091 long divisorLong = divisor & LONG_MASK; 1092 1093 // Special case of one word dividend 1094 if (intLen == 1) { 1095 long dividendValue = value[offset] & LONG_MASK; 1096 int q = (int) (dividendValue / divisorLong); 1097 int r = (int) (dividendValue - q * divisorLong); 1098 quotient.value[0] = q; 1099 quotient.intLen = (q == 0) ? 0 : 1; 1100 quotient.offset = 0; 1101 return r; 1102 } 1103 1104 if (quotient.value.length < intLen) 1105 quotient.value = new int[intLen]; 1106 quotient.offset = 0; 1107 quotient.intLen = intLen; 1108 1109 // Normalize the divisor 1110 int shift = Integer.numberOfLeadingZeros(divisor); 1111 1112 int rem = value[offset]; 1113 long remLong = rem & LONG_MASK; 1114 if (remLong < divisorLong) { 1115 quotient.value[0] = 0; 1116 } else { 1117 quotient.value[0] = (int)(remLong / divisorLong); 1118 rem = (int) (remLong - (quotient.value[0] * divisorLong)); 1119 remLong = rem & LONG_MASK; 1120 } 1121 int xlen = intLen; 1122 while (--xlen > 0) { 1123 long dividendEstimate = (remLong << 32) | 1124 (value[offset + intLen - xlen] & LONG_MASK); 1125 int q; 1126 if (dividendEstimate >= 0) { 1127 q = (int) (dividendEstimate / divisorLong); 1128 rem = (int) (dividendEstimate - q * divisorLong); 1129 } else { 1130 long tmp = divWord(dividendEstimate, divisor); 1131 q = (int) (tmp & LONG_MASK); 1132 rem = (int) (tmp >>> 32); 1133 } 1134 quotient.value[intLen - xlen] = q; 1135 remLong = rem & LONG_MASK; 1136 } 1137 1138 quotient.normalize(); 1139 // Unnormalize 1140 if (shift > 0) 1141 return rem % divisor; 1142 else 1143 return rem; 1144 } 1145 1146 /** 1147 * Calculates the quotient of this div b and places the quotient in the 1148 * provided MutableBigInteger objects and the remainder object is returned. 1149 * 1150 */ divide(MutableBigInteger b, MutableBigInteger quotient)1151 MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) { 1152 return divide(b,quotient,true); 1153 } 1154 divide(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder)1155 MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder) { 1156 if (b.intLen < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD || 1157 intLen - b.intLen < BigInteger.BURNIKEL_ZIEGLER_OFFSET) { 1158 return divideKnuth(b, quotient, needRemainder); 1159 } else { 1160 return divideAndRemainderBurnikelZiegler(b, quotient); 1161 } 1162 } 1163 1164 /** 1165 * @see #divideKnuth(MutableBigInteger, MutableBigInteger, boolean) 1166 */ divideKnuth(MutableBigInteger b, MutableBigInteger quotient)1167 MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient) { 1168 return divideKnuth(b,quotient,true); 1169 } 1170 1171 /** 1172 * Calculates the quotient of this div b and places the quotient in the 1173 * provided MutableBigInteger objects and the remainder object is returned. 1174 * 1175 * Uses Algorithm D from Knuth TAOCP Vol. 2, 3rd edition, section 4.3.1. 1176 * Many optimizations to that algorithm have been adapted from the Colin 1177 * Plumb C library. 1178 * It special cases one word divisors for speed. The content of b is not 1179 * changed. 1180 * 1181 */ divideKnuth(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder)1182 MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder) { 1183 if (b.intLen == 0) 1184 throw new ArithmeticException("BigInteger divide by zero"); 1185 1186 // Dividend is zero 1187 if (intLen == 0) { 1188 quotient.intLen = quotient.offset = 0; 1189 return needRemainder ? new MutableBigInteger() : null; 1190 } 1191 1192 int cmp = compare(b); 1193 // Dividend less than divisor 1194 if (cmp < 0) { 1195 quotient.intLen = quotient.offset = 0; 1196 return needRemainder ? new MutableBigInteger(this) : null; 1197 } 1198 // Dividend equal to divisor 1199 if (cmp == 0) { 1200 quotient.value[0] = quotient.intLen = 1; 1201 quotient.offset = 0; 1202 return needRemainder ? new MutableBigInteger() : null; 1203 } 1204 1205 quotient.clear(); 1206 // Special case one word divisor 1207 if (b.intLen == 1) { 1208 int r = divideOneWord(b.value[b.offset], quotient); 1209 if(needRemainder) { 1210 if (r == 0) 1211 return new MutableBigInteger(); 1212 return new MutableBigInteger(r); 1213 } else { 1214 return null; 1215 } 1216 } 1217 1218 // Cancel common powers of two if we're above the KNUTH_POW2_* thresholds 1219 if (intLen >= KNUTH_POW2_THRESH_LEN) { 1220 int trailingZeroBits = Math.min(getLowestSetBit(), b.getLowestSetBit()); 1221 if (trailingZeroBits >= KNUTH_POW2_THRESH_ZEROS*32) { 1222 MutableBigInteger a = new MutableBigInteger(this); 1223 b = new MutableBigInteger(b); 1224 a.rightShift(trailingZeroBits); 1225 b.rightShift(trailingZeroBits); 1226 MutableBigInteger r = a.divideKnuth(b, quotient); 1227 r.leftShift(trailingZeroBits); 1228 return r; 1229 } 1230 } 1231 1232 return divideMagnitude(b, quotient, needRemainder); 1233 } 1234 1235 /** 1236 * Computes {@code this/b} and {@code this%b} using the 1237 * <a href="http://cr.yp.to/bib/1998/burnikel.ps"> Burnikel-Ziegler algorithm</a>. 1238 * This method implements algorithm 3 from pg. 9 of the Burnikel-Ziegler paper. 1239 * The parameter beta was chosen to b 2<sup>32</sup> so almost all shifts are 1240 * multiples of 32 bits.<br/> 1241 * {@code this} and {@code b} must be nonnegative. 1242 * @param b the divisor 1243 * @param quotient output parameter for {@code this/b} 1244 * @return the remainder 1245 */ divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient)1246 MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) { 1247 int r = intLen; 1248 int s = b.intLen; 1249 1250 // Clear the quotient 1251 quotient.offset = quotient.intLen = 0; 1252 1253 if (r < s) { 1254 return this; 1255 } else { 1256 // Unlike Knuth division, we don't check for common powers of two here because 1257 // BZ already runs faster if both numbers contain powers of two and cancelling them has no 1258 // additional benefit. 1259 1260 // step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s} 1261 int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD)); 1262 1263 int j = (s+m-1) / m; // step 2a: j = ceil(s/m) 1264 int n = j * m; // step 2b: block length in 32-bit units 1265 long n32 = 32L * n; // block length in bits 1266 int sigma = (int) Math.max(0, n32 - b.bitLength()); // step 3: sigma = max{T | (2^T)*B < beta^n} 1267 MutableBigInteger bShifted = new MutableBigInteger(b); 1268 bShifted.safeLeftShift(sigma); // step 4a: shift b so its length is a multiple of n 1269 MutableBigInteger aShifted = new MutableBigInteger (this); 1270 aShifted.safeLeftShift(sigma); // step 4b: shift a by the same amount 1271 1272 // step 5: t is the number of blocks needed to accommodate a plus one additional bit 1273 int t = (int) ((aShifted.bitLength()+n32) / n32); 1274 if (t < 2) { 1275 t = 2; 1276 } 1277 1278 // step 6: conceptually split a into blocks a[t-1], ..., a[0] 1279 MutableBigInteger a1 = aShifted.getBlock(t-1, t, n); // the most significant block of a 1280 1281 // step 7: z[t-2] = [a[t-1], a[t-2]] 1282 MutableBigInteger z = aShifted.getBlock(t-2, t, n); // the second to most significant block 1283 z.addDisjoint(a1, n); // z[t-2] 1284 1285 // do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers 1286 MutableBigInteger qi = new MutableBigInteger(); 1287 MutableBigInteger ri; 1288 for (int i=t-2; i > 0; i--) { 1289 // step 8a: compute (qi,ri) such that z=b*qi+ri 1290 ri = z.divide2n1n(bShifted, qi); 1291 1292 // step 8b: z = [ri, a[i-1]] 1293 z = aShifted.getBlock(i-1, t, n); // a[i-1] 1294 z.addDisjoint(ri, n); 1295 quotient.addShifted(qi, i*n); // update q (part of step 9) 1296 } 1297 // final iteration of step 8: do the loop one more time for i=0 but leave z unchanged 1298 ri = z.divide2n1n(bShifted, qi); 1299 quotient.add(qi); 1300 1301 ri.rightShift(sigma); // step 9: a and b were shifted, so shift back 1302 return ri; 1303 } 1304 } 1305 1306 /** 1307 * This method implements algorithm 1 from pg. 4 of the Burnikel-Ziegler paper. 1308 * It divides a 2n-digit number by a n-digit number.<br/> 1309 * The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits. 1310 * <br/> 1311 * {@code this} must be a nonnegative number such that {@code this.bitLength() <= 2*b.bitLength()} 1312 * @param b a positive number such that {@code b.bitLength()} is even 1313 * @param quotient output parameter for {@code this/b} 1314 * @return {@code this%b} 1315 */ divide2n1n(MutableBigInteger b, MutableBigInteger quotient)1316 private MutableBigInteger divide2n1n(MutableBigInteger b, MutableBigInteger quotient) { 1317 int n = b.intLen; 1318 1319 // step 1: base case 1320 if (n%2 != 0 || n < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD) { 1321 return divideKnuth(b, quotient); 1322 } 1323 1324 // step 2: view this as [a1,a2,a3,a4] where each ai is n/2 ints or less 1325 MutableBigInteger aUpper = new MutableBigInteger(this); 1326 aUpper.safeRightShift(32*(n/2)); // aUpper = [a1,a2,a3] 1327 keepLower(n/2); // this = a4 1328 1329 // step 3: q1=aUpper/b, r1=aUpper%b 1330 MutableBigInteger q1 = new MutableBigInteger(); 1331 MutableBigInteger r1 = aUpper.divide3n2n(b, q1); 1332 1333 // step 4: quotient=[r1,this]/b, r2=[r1,this]%b 1334 addDisjoint(r1, n/2); // this = [r1,this] 1335 MutableBigInteger r2 = divide3n2n(b, quotient); 1336 1337 // step 5: let quotient=[q1,quotient] and return r2 1338 quotient.addDisjoint(q1, n/2); 1339 return r2; 1340 } 1341 1342 /** 1343 * This method implements algorithm 2 from pg. 5 of the Burnikel-Ziegler paper. 1344 * It divides a 3n-digit number by a 2n-digit number.<br/> 1345 * The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.<br/> 1346 * <br/> 1347 * {@code this} must be a nonnegative number such that {@code 2*this.bitLength() <= 3*b.bitLength()} 1348 * @param quotient output parameter for {@code this/b} 1349 * @return {@code this%b} 1350 */ divide3n2n(MutableBigInteger b, MutableBigInteger quotient)1351 private MutableBigInteger divide3n2n(MutableBigInteger b, MutableBigInteger quotient) { 1352 int n = b.intLen / 2; // half the length of b in ints 1353 1354 // step 1: view this as [a1,a2,a3] where each ai is n ints or less; let a12=[a1,a2] 1355 MutableBigInteger a12 = new MutableBigInteger(this); 1356 a12.safeRightShift(32*n); 1357 1358 // step 2: view b as [b1,b2] where each bi is n ints or less 1359 MutableBigInteger b1 = new MutableBigInteger(b); 1360 b1.safeRightShift(n * 32); 1361 BigInteger b2 = b.getLower(n); 1362 1363 MutableBigInteger r; 1364 MutableBigInteger d; 1365 if (compareShifted(b, n) < 0) { 1366 // step 3a: if a1<b1, let quotient=a12/b1 and r=a12%b1 1367 r = a12.divide2n1n(b1, quotient); 1368 1369 // step 4: d=quotient*b2 1370 d = new MutableBigInteger(quotient.toBigInteger().multiply(b2)); 1371 } else { 1372 // step 3b: if a1>=b1, let quotient=beta^n-1 and r=a12-b1*2^n+b1 1373 quotient.ones(n); 1374 a12.add(b1); 1375 b1.leftShift(32*n); 1376 a12.subtract(b1); 1377 r = a12; 1378 1379 // step 4: d=quotient*b2=(b2 << 32*n) - b2 1380 d = new MutableBigInteger(b2); 1381 d.leftShift(32 * n); 1382 d.subtract(new MutableBigInteger(b2)); 1383 } 1384 1385 // step 5: r = r*beta^n + a3 - d (paper says a4) 1386 // However, don't subtract d until after the while loop so r doesn't become negative 1387 r.leftShift(32 * n); 1388 r.addLower(this, n); 1389 1390 // step 6: add b until r>=d 1391 while (r.compare(d) < 0) { 1392 r.add(b); 1393 quotient.subtract(MutableBigInteger.ONE); 1394 } 1395 r.subtract(d); 1396 1397 return r; 1398 } 1399 1400 /** 1401 * Returns a {@code MutableBigInteger} containing {@code blockLength} ints from 1402 * {@code this} number, starting at {@code index*blockLength}.<br/> 1403 * Used by Burnikel-Ziegler division. 1404 * @param index the block index 1405 * @param numBlocks the total number of blocks in {@code this} number 1406 * @param blockLength length of one block in units of 32 bits 1407 * @return 1408 */ getBlock(int index, int numBlocks, int blockLength)1409 private MutableBigInteger getBlock(int index, int numBlocks, int blockLength) { 1410 int blockStart = index * blockLength; 1411 if (blockStart >= intLen) { 1412 return new MutableBigInteger(); 1413 } 1414 1415 int blockEnd; 1416 if (index == numBlocks-1) { 1417 blockEnd = intLen; 1418 } else { 1419 blockEnd = (index+1) * blockLength; 1420 } 1421 if (blockEnd > intLen) { 1422 return new MutableBigInteger(); 1423 } 1424 1425 int[] newVal = Arrays.copyOfRange(value, offset+intLen-blockEnd, offset+intLen-blockStart); 1426 return new MutableBigInteger(newVal); 1427 } 1428 1429 /** @see BigInteger#bitLength() */ bitLength()1430 long bitLength() { 1431 if (intLen == 0) 1432 return 0; 1433 return intLen*32L - Integer.numberOfLeadingZeros(value[offset]); 1434 } 1435 1436 /** 1437 * Internally used to calculate the quotient of this div v and places the 1438 * quotient in the provided MutableBigInteger object and the remainder is 1439 * returned. 1440 * 1441 * @return the remainder of the division will be returned. 1442 */ divide(long v, MutableBigInteger quotient)1443 long divide(long v, MutableBigInteger quotient) { 1444 if (v == 0) 1445 throw new ArithmeticException("BigInteger divide by zero"); 1446 1447 // Dividend is zero 1448 if (intLen == 0) { 1449 quotient.intLen = quotient.offset = 0; 1450 return 0; 1451 } 1452 if (v < 0) 1453 v = -v; 1454 1455 int d = (int)(v >>> 32); 1456 quotient.clear(); 1457 // Special case on word divisor 1458 if (d == 0) 1459 return divideOneWord((int)v, quotient) & LONG_MASK; 1460 else { 1461 return divideLongMagnitude(v, quotient).toLong(); 1462 } 1463 } 1464 copyAndShift(int[] src, int srcFrom, int srcLen, int[] dst, int dstFrom, int shift)1465 private static void copyAndShift(int[] src, int srcFrom, int srcLen, int[] dst, int dstFrom, int shift) { 1466 int n2 = 32 - shift; 1467 int c=src[srcFrom]; 1468 for (int i=0; i < srcLen-1; i++) { 1469 int b = c; 1470 c = src[++srcFrom]; 1471 dst[dstFrom+i] = (b << shift) | (c >>> n2); 1472 } 1473 dst[dstFrom+srcLen-1] = c << shift; 1474 } 1475 1476 /** 1477 * Divide this MutableBigInteger by the divisor. 1478 * The quotient will be placed into the provided quotient object & 1479 * the remainder object is returned. 1480 */ divideMagnitude(MutableBigInteger div, MutableBigInteger quotient, boolean needRemainder )1481 private MutableBigInteger divideMagnitude(MutableBigInteger div, 1482 MutableBigInteger quotient, 1483 boolean needRemainder ) { 1484 // assert div.intLen > 1 1485 // D1 normalize the divisor 1486 int shift = Integer.numberOfLeadingZeros(div.value[div.offset]); 1487 // Copy divisor value to protect divisor 1488 final int dlen = div.intLen; 1489 int[] divisor; 1490 MutableBigInteger rem; // Remainder starts as dividend with space for a leading zero 1491 if (shift > 0) { 1492 divisor = new int[dlen]; 1493 copyAndShift(div.value,div.offset,dlen,divisor,0,shift); 1494 if (Integer.numberOfLeadingZeros(value[offset]) >= shift) { 1495 int[] remarr = new int[intLen + 1]; 1496 rem = new MutableBigInteger(remarr); 1497 rem.intLen = intLen; 1498 rem.offset = 1; 1499 copyAndShift(value,offset,intLen,remarr,1,shift); 1500 } else { 1501 int[] remarr = new int[intLen + 2]; 1502 rem = new MutableBigInteger(remarr); 1503 rem.intLen = intLen+1; 1504 rem.offset = 1; 1505 int rFrom = offset; 1506 int c=0; 1507 int n2 = 32 - shift; 1508 for (int i=1; i < intLen+1; i++,rFrom++) { 1509 int b = c; 1510 c = value[rFrom]; 1511 remarr[i] = (b << shift) | (c >>> n2); 1512 } 1513 remarr[intLen+1] = c << shift; 1514 } 1515 } else { 1516 divisor = Arrays.copyOfRange(div.value, div.offset, div.offset + div.intLen); 1517 rem = new MutableBigInteger(new int[intLen + 1]); 1518 System.arraycopy(value, offset, rem.value, 1, intLen); 1519 rem.intLen = intLen; 1520 rem.offset = 1; 1521 } 1522 1523 int nlen = rem.intLen; 1524 1525 // Set the quotient size 1526 final int limit = nlen - dlen + 1; 1527 if (quotient.value.length < limit) { 1528 quotient.value = new int[limit]; 1529 quotient.offset = 0; 1530 } 1531 quotient.intLen = limit; 1532 int[] q = quotient.value; 1533 1534 1535 // Must insert leading 0 in rem if its length did not change 1536 if (rem.intLen == nlen) { 1537 rem.offset = 0; 1538 rem.value[0] = 0; 1539 rem.intLen++; 1540 } 1541 1542 int dh = divisor[0]; 1543 long dhLong = dh & LONG_MASK; 1544 int dl = divisor[1]; 1545 1546 // D2 Initialize j 1547 for (int j=0; j < limit-1; j++) { 1548 // D3 Calculate qhat 1549 // estimate qhat 1550 int qhat = 0; 1551 int qrem = 0; 1552 boolean skipCorrection = false; 1553 int nh = rem.value[j+rem.offset]; 1554 int nh2 = nh + 0x80000000; 1555 int nm = rem.value[j+1+rem.offset]; 1556 1557 if (nh == dh) { 1558 qhat = ~0; 1559 qrem = nh + nm; 1560 skipCorrection = qrem + 0x80000000 < nh2; 1561 } else { 1562 long nChunk = (((long)nh) << 32) | (nm & LONG_MASK); 1563 if (nChunk >= 0) { 1564 qhat = (int) (nChunk / dhLong); 1565 qrem = (int) (nChunk - (qhat * dhLong)); 1566 } else { 1567 long tmp = divWord(nChunk, dh); 1568 qhat = (int) (tmp & LONG_MASK); 1569 qrem = (int) (tmp >>> 32); 1570 } 1571 } 1572 1573 if (qhat == 0) 1574 continue; 1575 1576 if (!skipCorrection) { // Correct qhat 1577 long nl = rem.value[j+2+rem.offset] & LONG_MASK; 1578 long rs = ((qrem & LONG_MASK) << 32) | nl; 1579 long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); 1580 1581 if (unsignedLongCompare(estProduct, rs)) { 1582 qhat--; 1583 qrem = (int)((qrem & LONG_MASK) + dhLong); 1584 if ((qrem & LONG_MASK) >= dhLong) { 1585 estProduct -= (dl & LONG_MASK); 1586 rs = ((qrem & LONG_MASK) << 32) | nl; 1587 if (unsignedLongCompare(estProduct, rs)) 1588 qhat--; 1589 } 1590 } 1591 } 1592 1593 // D4 Multiply and subtract 1594 rem.value[j+rem.offset] = 0; 1595 int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset); 1596 1597 // D5 Test remainder 1598 if (borrow + 0x80000000 > nh2) { 1599 // D6 Add back 1600 divadd(divisor, rem.value, j+1+rem.offset); 1601 qhat--; 1602 } 1603 1604 // Store the quotient digit 1605 q[j] = qhat; 1606 } // D7 loop on j 1607 // D3 Calculate qhat 1608 // estimate qhat 1609 int qhat = 0; 1610 int qrem = 0; 1611 boolean skipCorrection = false; 1612 int nh = rem.value[limit - 1 + rem.offset]; 1613 int nh2 = nh + 0x80000000; 1614 int nm = rem.value[limit + rem.offset]; 1615 1616 if (nh == dh) { 1617 qhat = ~0; 1618 qrem = nh + nm; 1619 skipCorrection = qrem + 0x80000000 < nh2; 1620 } else { 1621 long nChunk = (((long) nh) << 32) | (nm & LONG_MASK); 1622 if (nChunk >= 0) { 1623 qhat = (int) (nChunk / dhLong); 1624 qrem = (int) (nChunk - (qhat * dhLong)); 1625 } else { 1626 long tmp = divWord(nChunk, dh); 1627 qhat = (int) (tmp & LONG_MASK); 1628 qrem = (int) (tmp >>> 32); 1629 } 1630 } 1631 if (qhat != 0) { 1632 if (!skipCorrection) { // Correct qhat 1633 long nl = rem.value[limit + 1 + rem.offset] & LONG_MASK; 1634 long rs = ((qrem & LONG_MASK) << 32) | nl; 1635 long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); 1636 1637 if (unsignedLongCompare(estProduct, rs)) { 1638 qhat--; 1639 qrem = (int) ((qrem & LONG_MASK) + dhLong); 1640 if ((qrem & LONG_MASK) >= dhLong) { 1641 estProduct -= (dl & LONG_MASK); 1642 rs = ((qrem & LONG_MASK) << 32) | nl; 1643 if (unsignedLongCompare(estProduct, rs)) 1644 qhat--; 1645 } 1646 } 1647 } 1648 1649 1650 // D4 Multiply and subtract 1651 int borrow; 1652 rem.value[limit - 1 + rem.offset] = 0; 1653 if(needRemainder) 1654 borrow = mulsub(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset); 1655 else 1656 borrow = mulsubBorrow(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset); 1657 1658 // D5 Test remainder 1659 if (borrow + 0x80000000 > nh2) { 1660 // D6 Add back 1661 if(needRemainder) 1662 divadd(divisor, rem.value, limit - 1 + 1 + rem.offset); 1663 qhat--; 1664 } 1665 1666 // Store the quotient digit 1667 q[(limit - 1)] = qhat; 1668 } 1669 1670 1671 if (needRemainder) { 1672 // D8 Unnormalize 1673 if (shift > 0) 1674 rem.rightShift(shift); 1675 rem.normalize(); 1676 } 1677 quotient.normalize(); 1678 return needRemainder ? rem : null; 1679 } 1680 1681 /** 1682 * Divide this MutableBigInteger by the divisor represented by positive long 1683 * value. The quotient will be placed into the provided quotient object & 1684 * the remainder object is returned. 1685 */ 1686 private MutableBigInteger divideLongMagnitude(long ldivisor, MutableBigInteger quotient) { 1687 // Remainder starts as dividend with space for a leading zero 1688 MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]); 1689 System.arraycopy(value, offset, rem.value, 1, intLen); 1690 rem.intLen = intLen; 1691 rem.offset = 1; 1692 1693 int nlen = rem.intLen; 1694 1695 int limit = nlen - 2 + 1; 1696 if (quotient.value.length < limit) { 1697 quotient.value = new int[limit]; 1698 quotient.offset = 0; 1699 } 1700 quotient.intLen = limit; 1701 int[] q = quotient.value; 1702 1703 // D1 normalize the divisor 1704 int shift = Long.numberOfLeadingZeros(ldivisor); 1705 if (shift > 0) { 1706 ldivisor<<=shift; 1707 rem.leftShift(shift); 1708 } 1709 1710 // Must insert leading 0 in rem if its length did not change 1711 if (rem.intLen == nlen) { 1712 rem.offset = 0; 1713 rem.value[0] = 0; 1714 rem.intLen++; 1715 } 1716 1717 int dh = (int)(ldivisor >>> 32); 1718 long dhLong = dh & LONG_MASK; 1719 int dl = (int)(ldivisor & LONG_MASK); 1720 1721 // D2 Initialize j 1722 for (int j = 0; j < limit; j++) { 1723 // D3 Calculate qhat 1724 // estimate qhat 1725 int qhat = 0; 1726 int qrem = 0; 1727 boolean skipCorrection = false; 1728 int nh = rem.value[j + rem.offset]; 1729 int nh2 = nh + 0x80000000; 1730 int nm = rem.value[j + 1 + rem.offset]; 1731 1732 if (nh == dh) { 1733 qhat = ~0; 1734 qrem = nh + nm; 1735 skipCorrection = qrem + 0x80000000 < nh2; 1736 } else { 1737 long nChunk = (((long) nh) << 32) | (nm & LONG_MASK); 1738 if (nChunk >= 0) { 1739 qhat = (int) (nChunk / dhLong); 1740 qrem = (int) (nChunk - (qhat * dhLong)); 1741 } else { 1742 long tmp = divWord(nChunk, dh); 1743 qhat =(int)(tmp & LONG_MASK); 1744 qrem = (int)(tmp>>>32); 1745 } 1746 } 1747 1748 if (qhat == 0) 1749 continue; 1750 1751 if (!skipCorrection) { // Correct qhat 1752 long nl = rem.value[j + 2 + rem.offset] & LONG_MASK; 1753 long rs = ((qrem & LONG_MASK) << 32) | nl; 1754 long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK); 1755 1756 if (unsignedLongCompare(estProduct, rs)) { 1757 qhat--; 1758 qrem = (int) ((qrem & LONG_MASK) + dhLong); 1759 if ((qrem & LONG_MASK) >= dhLong) { 1760 estProduct -= (dl & LONG_MASK); 1761 rs = ((qrem & LONG_MASK) << 32) | nl; 1762 if (unsignedLongCompare(estProduct, rs)) 1763 qhat--; 1764 } 1765 } 1766 } 1767 1768 // D4 Multiply and subtract 1769 rem.value[j + rem.offset] = 0; 1770 int borrow = mulsubLong(rem.value, dh, dl, qhat, j + rem.offset); 1771 1772 // D5 Test remainder 1773 if (borrow + 0x80000000 > nh2) { 1774 // D6 Add back 1775 divaddLong(dh,dl, rem.value, j + 1 + rem.offset); 1776 qhat--; 1777 } 1778 1779 // Store the quotient digit 1780 q[j] = qhat; 1781 } // D7 loop on j 1782 1783 // D8 Unnormalize 1784 if (shift > 0) 1785 rem.rightShift(shift); 1786 1787 quotient.normalize(); 1788 rem.normalize(); 1789 return rem; 1790 } 1791 1792 /** 1793 * A primitive used for division by long. 1794 * Specialized version of the method divadd. 1795 * dh is a high part of the divisor, dl is a low part 1796 */ 1797 private int divaddLong(int dh, int dl, int[] result, int offset) { 1798 long carry = 0; 1799 1800 long sum = (dl & LONG_MASK) + (result[1+offset] & LONG_MASK); 1801 result[1+offset] = (int)sum; 1802 1803 sum = (dh & LONG_MASK) + (result[offset] & LONG_MASK) + carry; 1804 result[offset] = (int)sum; 1805 carry = sum >>> 32; 1806 return (int)carry; 1807 } 1808 1809 /** 1810 * This method is used for division by long. 1811 * Specialized version of the method sulsub. 1812 * dh is a high part of the divisor, dl is a low part 1813 */ 1814 private int mulsubLong(int[] q, int dh, int dl, int x, int offset) { 1815 long xLong = x & LONG_MASK; 1816 offset += 2; 1817 long product = (dl & LONG_MASK) * xLong; 1818 long difference = q[offset] - product; 1819 q[offset--] = (int)difference; 1820 long carry = (product >>> 32) 1821 + (((difference & LONG_MASK) > 1822 (((~(int)product) & LONG_MASK))) ? 1:0); 1823 product = (dh & LONG_MASK) * xLong + carry; 1824 difference = q[offset] - product; 1825 q[offset--] = (int)difference; 1826 carry = (product >>> 32) 1827 + (((difference & LONG_MASK) > 1828 (((~(int)product) & LONG_MASK))) ? 1:0); 1829 return (int)carry; 1830 } 1831 1832 /** 1833 * Compare two longs as if they were unsigned. 1834 * Returns true iff one is bigger than two. 1835 */ 1836 private boolean unsignedLongCompare(long one, long two) { 1837 return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE); 1838 } 1839 1840 /** 1841 * This method divides a long quantity by an int to estimate 1842 * qhat for two multi precision numbers. It is used when 1843 * the signed value of n is less than zero. 1844 * Returns long value where high 32 bits contain remainder value and 1845 * low 32 bits contain quotient value. 1846 */ 1847 static long divWord(long n, int d) { 1848 long dLong = d & LONG_MASK; 1849 long r; 1850 long q; 1851 if (dLong == 1) { 1852 q = (int)n; 1853 r = 0; 1854 return (r << 32) | (q & LONG_MASK); 1855 } 1856 1857 // Approximate the quotient and remainder 1858 q = (n >>> 1) / (dLong >>> 1); 1859 r = n - q*dLong; 1860 1861 // Correct the approximation 1862 while (r < 0) { 1863 r += dLong; 1864 q--; 1865 } 1866 while (r >= dLong) { 1867 r -= dLong; 1868 q++; 1869 } 1870 // n - q*dlong == r && 0 <= r <dLong, hence we're done. 1871 return (r << 32) | (q & LONG_MASK); 1872 } 1873 1874 /** 1875 * Calculate the integer square root {@code floor(sqrt(this))} where 1876 * {@code sqrt(.)} denotes the mathematical square root. The contents of 1877 * {@code this} are <b>not</b> changed. The value of {@code this} is assumed 1878 * to be non-negative. 1879 * 1880 * @implNote The implementation is based on the material in Henry S. Warren, 1881 * Jr., <i>Hacker's Delight (2nd ed.)</i> (Addison Wesley, 2013), 279-282. 1882 * 1883 * @throws ArithmeticException if the value returned by {@code bitLength()} 1884 * overflows the range of {@code int}. 1885 * @return the integer square root of {@code this} 1886 * @since 9 1887 */ 1888 MutableBigInteger sqrt() { 1889 // Special cases. 1890 if (this.isZero()) { 1891 return new MutableBigInteger(0); 1892 } else if (this.value.length == 1 1893 && (this.value[0] & LONG_MASK) < 4) { // result is unity 1894 return ONE; 1895 } 1896 1897 if (bitLength() <= 63) { 1898 // Initial estimate is the square root of the positive long value. 1899 long v = new BigInteger(this.value, 1).longValueExact(); 1900 long xk = (long)Math.floor(Math.sqrt(v)); 1901 1902 // Refine the estimate. 1903 do { 1904 long xk1 = (xk + v/xk)/2; 1905 1906 // Terminate when non-decreasing. 1907 if (xk1 >= xk) { 1908 return new MutableBigInteger(new int[] { 1909 (int)(xk >>> 32), (int)(xk & LONG_MASK) 1910 }); 1911 } 1912 1913 xk = xk1; 1914 } while (true); 1915 } else { 1916 // Set up the initial estimate of the iteration. 1917 1918 // Obtain the bitLength > 63. 1919 int bitLength = (int) this.bitLength(); 1920 if (bitLength != this.bitLength()) { 1921 throw new ArithmeticException("bitLength() integer overflow"); 1922 } 1923 1924 // Determine an even valued right shift into positive long range. 1925 int shift = bitLength - 63; 1926 if (shift % 2 == 1) { 1927 shift++; 1928 } 1929 1930 // Shift the value into positive long range. 1931 MutableBigInteger xk = new MutableBigInteger(this); 1932 xk.rightShift(shift); 1933 xk.normalize(); 1934 1935 // Use the square root of the shifted value as an approximation. 1936 double d = new BigInteger(xk.value, 1).doubleValue(); 1937 BigInteger bi = BigInteger.valueOf((long)Math.ceil(Math.sqrt(d))); 1938 xk = new MutableBigInteger(bi.mag); 1939 1940 // Shift the approximate square root back into the original range. 1941 xk.leftShift(shift / 2); 1942 1943 // Refine the estimate. 1944 MutableBigInteger xk1 = new MutableBigInteger(); 1945 do { 1946 // xk1 = (xk + n/xk)/2 1947 this.divide(xk, xk1, false); 1948 xk1.add(xk); 1949 xk1.rightShift(1); 1950 1951 // Terminate when non-decreasing. 1952 if (xk1.compare(xk) >= 0) { 1953 return xk; 1954 } 1955 1956 // xk = xk1 1957 xk.copyValue(xk1); 1958 1959 xk1.reset(); 1960 } while (true); 1961 } 1962 } 1963 1964 /** 1965 * Calculate GCD of this and b. This and b are changed by the computation. 1966 */ 1967 MutableBigInteger hybridGCD(MutableBigInteger b) { 1968 // Use Euclid's algorithm until the numbers are approximately the 1969 // same length, then use the binary GCD algorithm to find the GCD. 1970 MutableBigInteger a = this; 1971 MutableBigInteger q = new MutableBigInteger(); 1972 1973 while (b.intLen != 0) { 1974 if (Math.abs(a.intLen - b.intLen) < 2) 1975 return a.binaryGCD(b); 1976 1977 MutableBigInteger r = a.divide(b, q); 1978 a = b; 1979 b = r; 1980 } 1981 return a; 1982 } 1983 1984 /** 1985 * Calculate GCD of this and v. 1986 * Assumes that this and v are not zero. 1987 */ 1988 private MutableBigInteger binaryGCD(MutableBigInteger v) { 1989 // Algorithm B from Knuth TAOCP Vol. 2, 3rd edition, section 4.5.2 1990 MutableBigInteger u = this; 1991 MutableBigInteger r = new MutableBigInteger(); 1992 1993 // step B1 1994 int s1 = u.getLowestSetBit(); 1995 int s2 = v.getLowestSetBit(); 1996 int k = (s1 < s2) ? s1 : s2; 1997 if (k != 0) { 1998 u.rightShift(k); 1999 v.rightShift(k); 2000 } 2001 2002 // step B2 2003 boolean uOdd = (k == s1); 2004 MutableBigInteger t = uOdd ? v: u; 2005 int tsign = uOdd ? -1 : 1; 2006 2007 int lb; 2008 while ((lb = t.getLowestSetBit()) >= 0) { 2009 // steps B3 and B4 2010 t.rightShift(lb); 2011 // step B5 2012 if (tsign > 0) 2013 u = t; 2014 else 2015 v = t; 2016 2017 // Special case one word numbers 2018 if (u.intLen < 2 && v.intLen < 2) { 2019 int x = u.value[u.offset]; 2020 int y = v.value[v.offset]; 2021 x = binaryGcd(x, y); 2022 r.value[0] = x; 2023 r.intLen = 1; 2024 r.offset = 0; 2025 if (k > 0) 2026 r.leftShift(k); 2027 return r; 2028 } 2029 2030 // step B6 2031 if ((tsign = u.difference(v)) == 0) 2032 break; 2033 t = (tsign >= 0) ? u : v; 2034 } 2035 2036 if (k > 0) 2037 u.leftShift(k); 2038 return u; 2039 } 2040 2041 /** 2042 * Calculate GCD of a and b interpreted as unsigned integers. 2043 */ 2044 static int binaryGcd(int a, int b) { 2045 if (b == 0) 2046 return a; 2047 if (a == 0) 2048 return b; 2049 2050 // Right shift a & b till their last bits equal to 1. 2051 int aZeros = Integer.numberOfTrailingZeros(a); 2052 int bZeros = Integer.numberOfTrailingZeros(b); 2053 a >>>= aZeros; 2054 b >>>= bZeros; 2055 2056 int t = (aZeros < bZeros ? aZeros : bZeros); 2057 2058 while (a != b) { 2059 if ((a+0x80000000) > (b+0x80000000)) { // a > b as unsigned 2060 a -= b; 2061 a >>>= Integer.numberOfTrailingZeros(a); 2062 } else { 2063 b -= a; 2064 b >>>= Integer.numberOfTrailingZeros(b); 2065 } 2066 } 2067 return a<<t; 2068 } 2069 2070 /** 2071 * Returns the modInverse of this mod p. This and p are not affected by 2072 * the operation. 2073 */ 2074 MutableBigInteger mutableModInverse(MutableBigInteger p) { 2075 // Modulus is odd, use Schroeppel's algorithm 2076 if (p.isOdd()) 2077 return modInverse(p); 2078 2079 // Base and modulus are even, throw exception 2080 if (isEven()) 2081 throw new ArithmeticException("BigInteger not invertible."); 2082 2083 // Get even part of modulus expressed as a power of 2 2084 int powersOf2 = p.getLowestSetBit(); 2085 2086 // Construct odd part of modulus 2087 MutableBigInteger oddMod = new MutableBigInteger(p); 2088 oddMod.rightShift(powersOf2); 2089 2090 if (oddMod.isOne()) 2091 return modInverseMP2(powersOf2); 2092 2093 // Calculate 1/a mod oddMod 2094 MutableBigInteger oddPart = modInverse(oddMod); 2095 2096 // Calculate 1/a mod evenMod 2097 MutableBigInteger evenPart = modInverseMP2(powersOf2); 2098 2099 // Combine the results using Chinese Remainder Theorem 2100 MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2); 2101 MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2); 2102 2103 MutableBigInteger temp1 = new MutableBigInteger(); 2104 MutableBigInteger temp2 = new MutableBigInteger(); 2105 MutableBigInteger result = new MutableBigInteger(); 2106 2107 oddPart.leftShift(powersOf2); 2108 oddPart.multiply(y1, result); 2109 2110 evenPart.multiply(oddMod, temp1); 2111 temp1.multiply(y2, temp2); 2112 2113 result.add(temp2); 2114 return result.divide(p, temp1); 2115 } 2116 2117 /* 2118 * Calculate the multiplicative inverse of this mod 2^k. 2119 */ 2120 MutableBigInteger modInverseMP2(int k) { 2121 if (isEven()) 2122 throw new ArithmeticException("Non-invertible. (GCD != 1)"); 2123 2124 if (k > 64) 2125 return euclidModInverse(k); 2126 2127 int t = inverseMod32(value[offset+intLen-1]); 2128 2129 if (k < 33) { 2130 t = (k == 32 ? t : t & ((1 << k) - 1)); 2131 return new MutableBigInteger(t); 2132 } 2133 2134 long pLong = (value[offset+intLen-1] & LONG_MASK); 2135 if (intLen > 1) 2136 pLong |= ((long)value[offset+intLen-2] << 32); 2137 long tLong = t & LONG_MASK; 2138 tLong = tLong * (2 - pLong * tLong); // 1 more Newton iter step 2139 tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1)); 2140 2141 MutableBigInteger result = new MutableBigInteger(new int[2]); 2142 result.value[0] = (int)(tLong >>> 32); 2143 result.value[1] = (int)tLong; 2144 result.intLen = 2; 2145 result.normalize(); 2146 return result; 2147 } 2148 2149 /** 2150 * Returns the multiplicative inverse of val mod 2^32. Assumes val is odd. 2151 */ 2152 static int inverseMod32(int val) { 2153 // Newton's iteration! 2154 int t = val; 2155 t *= 2 - val*t; 2156 t *= 2 - val*t; 2157 t *= 2 - val*t; 2158 t *= 2 - val*t; 2159 return t; 2160 } 2161 2162 /** 2163 * Returns the multiplicative inverse of val mod 2^64. Assumes val is odd. 2164 */ 2165 static long inverseMod64(long val) { 2166 // Newton's iteration! 2167 long t = val; 2168 t *= 2 - val*t; 2169 t *= 2 - val*t; 2170 t *= 2 - val*t; 2171 t *= 2 - val*t; 2172 t *= 2 - val*t; 2173 assert(t * val == 1); 2174 return t; 2175 } 2176 2177 /** 2178 * Calculate the multiplicative inverse of 2^k mod mod, where mod is odd. 2179 */ 2180 static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) { 2181 // Copy the mod to protect original 2182 return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k); 2183 } 2184 2185 /** 2186 * Calculate the multiplicative inverse of this modulo mod, where the mod 2187 * argument is odd. This and mod are not changed by the calculation. 2188 * 2189 * This method implements an algorithm due to Richard Schroeppel, that uses 2190 * the same intermediate representation as Montgomery Reduction 2191 * ("Montgomery Form"). The algorithm is described in an unpublished 2192 * manuscript entitled "Fast Modular Reciprocals." 2193 */ 2194 private MutableBigInteger modInverse(MutableBigInteger mod) { 2195 MutableBigInteger p = new MutableBigInteger(mod); 2196 MutableBigInteger f = new MutableBigInteger(this); 2197 MutableBigInteger g = new MutableBigInteger(p); 2198 SignedMutableBigInteger c = new SignedMutableBigInteger(1); 2199 SignedMutableBigInteger d = new SignedMutableBigInteger(); 2200 MutableBigInteger temp = null; 2201 SignedMutableBigInteger sTemp = null; 2202 2203 int k = 0; 2204 // Right shift f k times until odd, left shift d k times 2205 if (f.isEven()) { 2206 int trailingZeros = f.getLowestSetBit(); 2207 f.rightShift(trailingZeros); 2208 d.leftShift(trailingZeros); 2209 k = trailingZeros; 2210 } 2211 2212 // The Almost Inverse Algorithm 2213 while (!f.isOne()) { 2214 // If gcd(f, g) != 1, number is not invertible modulo mod 2215 if (f.isZero()) 2216 throw new ArithmeticException("BigInteger not invertible."); 2217 2218 // If f < g exchange f, g and c, d 2219 if (f.compare(g) < 0) { 2220 temp = f; f = g; g = temp; 2221 sTemp = d; d = c; c = sTemp; 2222 } 2223 2224 // If f == g (mod 4) 2225 if (((f.value[f.offset + f.intLen - 1] ^ 2226 g.value[g.offset + g.intLen - 1]) & 3) == 0) { 2227 f.subtract(g); 2228 c.signedSubtract(d); 2229 } else { // If f != g (mod 4) 2230 f.add(g); 2231 c.signedAdd(d); 2232 } 2233 2234 // Right shift f k times until odd, left shift d k times 2235 int trailingZeros = f.getLowestSetBit(); 2236 f.rightShift(trailingZeros); 2237 d.leftShift(trailingZeros); 2238 k += trailingZeros; 2239 } 2240 2241 if (c.compare(p) >= 0) { // c has a larger magnitude than p 2242 MutableBigInteger remainder = c.divide(p, 2243 new MutableBigInteger()); 2244 // The previous line ignores the sign so we copy the data back 2245 // into c which will restore the sign as needed (and converts 2246 // it back to a SignedMutableBigInteger) 2247 c.copyValue(remainder); 2248 } 2249 2250 if (c.sign < 0) { 2251 c.signedAdd(p); 2252 } 2253 2254 return fixup(c, p, k); 2255 } 2256 2257 /** 2258 * The Fixup Algorithm 2259 * Calculates X such that X = C * 2^(-k) (mod P) 2260 * Assumes C<P and P is odd. 2261 */ 2262 static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p, 2263 int k) { 2264 MutableBigInteger temp = new MutableBigInteger(); 2265 // Set r to the multiplicative inverse of p mod 2^32 2266 int r = -inverseMod32(p.value[p.offset+p.intLen-1]); 2267 2268 for (int i=0, numWords = k >> 5; i < numWords; i++) { 2269 // V = R * c (mod 2^j) 2270 int v = r * c.value[c.offset + c.intLen-1]; 2271 // c = c + (v * p) 2272 p.mul(v, temp); 2273 c.add(temp); 2274 // c = c / 2^j 2275 c.intLen--; 2276 } 2277 int numBits = k & 0x1f; 2278 if (numBits != 0) { 2279 // V = R * c (mod 2^j) 2280 int v = r * c.value[c.offset + c.intLen-1]; 2281 v &= ((1<<numBits) - 1); 2282 // c = c + (v * p) 2283 p.mul(v, temp); 2284 c.add(temp); 2285 // c = c / 2^j 2286 c.rightShift(numBits); 2287 } 2288 2289 // In theory, c may be greater than p at this point (Very rare!) 2290 if (c.compare(p) >= 0) 2291 c = c.divide(p, new MutableBigInteger()); 2292 2293 return c; 2294 } 2295 2296 /** 2297 * Uses the extended Euclidean algorithm to compute the modInverse of base 2298 * mod a modulus that is a power of 2. The modulus is 2^k. 2299 */ 2300 MutableBigInteger euclidModInverse(int k) { 2301 MutableBigInteger b = new MutableBigInteger(1); 2302 b.leftShift(k); 2303 MutableBigInteger mod = new MutableBigInteger(b); 2304 2305 MutableBigInteger a = new MutableBigInteger(this); 2306 MutableBigInteger q = new MutableBigInteger(); 2307 MutableBigInteger r = b.divide(a, q); 2308 2309 MutableBigInteger swapper = b; 2310 // swap b & r 2311 b = r; 2312 r = swapper; 2313 2314 MutableBigInteger t1 = new MutableBigInteger(q); 2315 MutableBigInteger t0 = new MutableBigInteger(1); 2316 MutableBigInteger temp = new MutableBigInteger(); 2317 2318 while (!b.isOne()) { 2319 r = a.divide(b, q); 2320 2321 if (r.intLen == 0) 2322 throw new ArithmeticException("BigInteger not invertible."); 2323 2324 swapper = r; 2325 a = swapper; 2326 2327 if (q.intLen == 1) 2328 t1.mul(q.value[q.offset], temp); 2329 else 2330 q.multiply(t1, temp); 2331 swapper = q; 2332 q = temp; 2333 temp = swapper; 2334 t0.add(q); 2335 2336 if (a.isOne()) 2337 return t0; 2338 2339 r = b.divide(a, q); 2340 2341 if (r.intLen == 0) 2342 throw new ArithmeticException("BigInteger not invertible."); 2343 2344 swapper = b; 2345 b = r; 2346 2347 if (q.intLen == 1) 2348 t0.mul(q.value[q.offset], temp); 2349 else 2350 q.multiply(t0, temp); 2351 swapper = q; q = temp; temp = swapper; 2352 2353 t1.add(q); 2354 } 2355 mod.subtract(t1); 2356 return mod; 2357 } 2358 } 2359