001/* 002 * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences. 003 * Copyright (C) 2006 - JScience (http://jscience.org/) 004 * All rights reserved. 005 * 006 * Permission to use, copy, modify, and distribute this software is 007 * freely granted, provided that this notice is preserved. 008 */ 009package org.jscience.mathematics.number; 010 011import java.io.IOException; 012 013import javolution.context.ArrayFactory; 014import javolution.context.ConcurrentContext; 015import javolution.context.ObjectFactory; 016import javolution.context.StackContext; 017import javolution.lang.Configurable; 018import javolution.lang.MathLib; 019import javolution.text.Text; 020import javolution.text.TextBuilder; 021import javolution.text.TextFormat; 022import javolution.text.TypeFormat; 023import javolution.text.TextFormat.Cursor; 024import javolution.xml.XMLFormat; 025import javolution.xml.stream.XMLStreamException; 026import static org.jscience.mathematics.number.Calculus.*; 027 028/** 029 * <p> This class represents an immutable integer number of arbitrary size.</p> 030 * 031 * <p> It has the following advantages over the 032 * <code>java.math.BigInteger</code> class: 033 * <ul> 034 * <li> Optimized for 64 bits architectures. But still runs significantly 035 * faster on 32 bits processors.</li> 036 * <li> Real-time compliant for improved performance and predictability 037 * (no garbage generated when executing in 038 * {@link javolution.context.StackContext StackContext}).</li> 039 * <li> Improved algorithms (e.g. Concurrent Karabutsa multiplication in 040 * O(n<sup>Log3</sup>) instead of O(n<sup>2</sup>).</li> 041 * </ul></p> 042 * 043 * <p> <b>Note:</b> This class uses {@link ConcurrentContext ConcurrentContext} 044 * to accelerate calculations on multi-cores systems.</p> 045 * 046 * @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a> 047 * @version 3.3, January 14, 2007 048 * @see <a href="http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic"> 049 * Wikipedia: Arbitrary-precision Arithmetic</a> 050 */ 051public final class LargeInteger extends Number<LargeInteger> { 052 053 /** 054 * Holds the certainty required when testing for primality 055 * (default <code>100</code>, the probability for a composite to 056 * pass the primality test is less than <code>2<sup>-100</sup></code>). 057 */ 058 public static final Configurable<Integer> PRIME_CERTAINTY = new Configurable<Integer>( 059 100); 060 061 /** 062 * Holds the format for large integers (decimal representation by default). 063 * 064 * @see #parse(CharSequence, int, TextFormat.Cursor) 065 * @see #format(LargeInteger, int, Appendable) 066 */ 067 static final TextFormat<LargeInteger> DECIMAL_FORMAT = 068 new TextFormat<LargeInteger>() { 069 070 @Override 071 public Appendable format(LargeInteger li, Appendable out) 072 throws IOException { 073 return LargeInteger.format(li, 10, out); 074 } 075 076 @Override 077 public LargeInteger parse(CharSequence csq, Cursor cursor) { 078 return LargeInteger.parse(csq, 10, cursor); 079 } 080 }; 081 static { 082 TextFormat.setInstance(LargeInteger.class, DECIMAL_FORMAT); 083 } 084 085 /** 086 * Holds factory for LargeInteger with variable size arrays. 087 */ 088 private static final ArrayFactory<LargeInteger> ARRAY_FACTORY = new ArrayFactory<LargeInteger>() { 089 090 @Override 091 protected LargeInteger create(int capacity) { 092 return new LargeInteger(capacity); 093 } 094 095 }; 096 097 /** 098 * Holds the factory for LargeInteger with no intrinsic array (wrapper instances). 099 */ 100 private static final ObjectFactory<LargeInteger> NO_ARRAY_FACTORY = new ObjectFactory<LargeInteger>() { 101 102 @Override 103 protected LargeInteger create() { 104 return new LargeInteger(); 105 } 106 107 }; 108 109 /** 110 * Holds the default XML representation for large integers. 111 * This representation consists of a simple <code>value</code> attribute 112 * holding the {@link #toText() textual} representation. 113 */ 114 static final XMLFormat<LargeInteger> XML = new XMLFormat<LargeInteger>( 115 LargeInteger.class) { 116 117 @Override 118 public LargeInteger newInstance(Class<LargeInteger> cls, 119 InputElement xml) throws XMLStreamException { 120 return LargeInteger.valueOf(xml.getAttribute("value")); 121 } 122 123 public void write(LargeInteger li, OutputElement xml) 124 throws XMLStreamException { 125 xml.setAttribute("value", li.toText()); 126 } 127 128 public void read(InputElement xml, LargeInteger li) { 129 // Nothing to do, immutable. 130 } 131 }; 132 133 /** 134 * The large integer representing the additive identity. 135 */ 136 public static final LargeInteger ZERO = new LargeInteger(1); 137 138 /** 139 * The large integer representing the multiplicative identity. 140 */ 141 public static final LargeInteger ONE = new LargeInteger(1); 142 static { 143 ONE._words[0] = 1; 144 ONE._size = 1; 145 } 146 147 /** 148 * Holds Long.MIN_VALUE 149 */ 150 static final LargeInteger LONG_MIN_VALUE = new LargeInteger(2); 151 static { 152 LONG_MIN_VALUE._words[1] = 1; 153 LONG_MIN_VALUE._size = 2; 154 } 155 156 /** 157 * Holds five. 158 */ 159 static final LargeInteger FIVE = new LargeInteger(1); 160 static { 161 LONG_MIN_VALUE._words[1] = 5; 162 LONG_MIN_VALUE._size = 1; 163 } 164 165 /** 166 * Holds the remainder after a {@link #divide} operation. 167 */ 168 private LargeInteger _remainder; 169 170 /** 171 * Indicates if this large integer is negative. 172 */ 173 private boolean _isNegative; 174 175 /** 176 * The size of this large integer in words. 177 * The most significand word different from 0 is at index: _size-1 178 */ 179 private int _size; 180 181 /** 182 * This large integer positive words (63 bits). 183 * Least significant word first (index 0). 184 */ 185 private long[] _words; 186 187 /** 188 * Default constructor (no words array). 189 */ 190 private LargeInteger() { 191 } 192 193 /** 194 * Creates a large integer with the specified 63 bits word capacity. 195 * 196 * @link wordLength the internal positive <code>long</code> array length. 197 */ 198 private LargeInteger(int wordLength) { 199 _words = new long[wordLength]; 200 } 201 202 /** 203 * Returns the large integer of specified <code>long</code> value. 204 * 205 * @param value the <code>long</code> value. 206 * @return the corresponding large integer number. 207 */ 208 public static LargeInteger valueOf(long value) { 209 if (value == 0) 210 return ZERO; 211 if (value == Long.MIN_VALUE) 212 return LONG_MIN_VALUE; 213 LargeInteger li = ARRAY_FACTORY.array(1); 214 boolean negative = li._isNegative = value < 0; 215 li._words[0] = negative ? -value : value; 216 li._size = 1; 217 return li; 218 } 219 220 /** 221 * Returns the large integer of specified two's-complement binary 222 * representation. The input array is assumed to be in <i>big-endian</i> 223 * byte-order: the most significant byte is at the offset position. 224 * 225 * @param bytes the binary representation (two's-complement). 226 * @param offset the offset at which to start reading the bytes. 227 * @param length the maximum number of bytes to read. 228 * @return the corresponding large integer number. 229 * @throws IndexOutOfBoundsException 230 * if <code>offset + length > bytes.length</code> 231 * @see #toByteArray 232 */ 233 public static LargeInteger valueOf(byte[] bytes, int offset, int length) { 234 // Ensures result is large enough (takes into account potential 235 // extra bits during negative to positive conversion). 236 LargeInteger li = ARRAY_FACTORY.array(((length * 8 + 1) / 63) + 1); 237 final boolean isNegative = bytes[offset] < 0; 238 int wordIndex = 0; 239 int bitIndex = 0; 240 li._words[0] = 0; 241 for (int i = offset + length; i > offset; bitIndex += 8) { 242 long bits = (isNegative ? ~bytes[--i] : bytes[--i]) & MASK_8; 243 if (bitIndex < 63 - 8) { 244 li._words[wordIndex] |= bits << bitIndex; 245 } else { // End of word reached. 246 li._words[wordIndex] |= (bits << bitIndex) & MASK_63; 247 bitIndex -= 63; // In range [-8..-1] 248 li._words[++wordIndex] = bits >> -bitIndex; 249 } 250 } 251 // Calculates size. 252 while (li._words[wordIndex] == 0) { 253 if (--wordIndex < 0) 254 break; 255 } 256 li._size = wordIndex + 1; 257 li._isNegative = isNegative; 258 259 // Converts one's-complement to two's-complement if negative. 260 if (isNegative) { // Adds ONE. 261 li._size = Calculus.add(li._words, li._size, ONE._words, 1, 262 li._words); 263 } 264 return li; 265 } 266 267 /** 268 * Returns the two's-complement binary representation of this 269 * large integer. The output array is in <i>big-endian</i> 270 * byte-order: the most significant byte is at the offset position. 271 * 272 * @param bytes the bytes to hold the binary representation 273 * (two's-complement) of this large integer. 274 * @param offset the offset at which to start writing the bytes. 275 * @return the number of bytes written. 276 * @throws IndexOutOfBoundsException 277 * if <code>bytes.length < (bitLength() >> 3) + 1</code> 278 * @see #valueOf(byte[], int, int) 279 * @see #bitLength 280 */ 281 public int toByteArray(byte[] bytes, int offset) { 282 int bytesLength = (bitLength() >> 3) + 1; 283 int wordIndex = 0; 284 int bitIndex = 0; 285 if (_isNegative) { 286 long word = _words[0] - 1; 287 long borrow = word >> 63; // -1 if borrow 288 word = ~word & MASK_63; 289 for (int i = bytesLength + offset; i > offset; bitIndex += 8) { 290 if (bitIndex < 63 - 8) { 291 bytes[--i] = (byte) word; 292 word >>= 8; 293 } else { // End of word reached. 294 byte bits = (byte) word; 295 word = (++wordIndex < _size) ? _words[wordIndex] + borrow 296 : borrow; 297 borrow = word >> 63; // -1 if borrow 298 word = ~word & MASK_63; 299 bitIndex -= 63; // In range [-8..-1] 300 bytes[--i] = (byte) ((word << -bitIndex) | bits); 301 word >>= (8 + bitIndex); 302 } 303 } 304 } else { 305 if (_size != 0) { 306 long word = _words[0]; 307 for (int i = bytesLength + offset; i > offset; bitIndex += 8) { 308 if (bitIndex < 63 - 8) { 309 bytes[--i] = (byte) word; 310 word >>= 8; 311 } else { // End of word reached. 312 byte bits = (byte) word; 313 word = (++wordIndex < _size) ? _words[wordIndex] : 0; 314 bitIndex -= 63; // In range [-8..-1] 315 bytes[--i] = (byte) ((word << -bitIndex) | bits); 316 word >>= (8 + bitIndex); 317 } 318 } 319 } else { // ZERO 320 bytes[offset] = 0; 321 } 322 } 323 return bytesLength; 324 } 325 326 /** 327 * Returns the large integer for the specified character sequence 328 * using the current {@link TextFormat#getInstance(Class) format}. 329 * 330 * @param csq the character sequence to parse. 331 * @return <code>TextFormat.getInstance(LargeInteger.class).parse(csq)</code> 332 * @throws NumberFormatException if error when parsing. 333 */ 334 public static LargeInteger valueOf(CharSequence csq) { 335 return TextFormat.getInstance(LargeInteger.class).parse(csq); 336 } 337 338 /** 339 * Returns the large integer for the specified character sequence in 340 * the specified radix. 341 * 342 * @param csq the character sequence to parse. 343 * @param radix the radix of the representation. 344 * @return <code>LargeInteger.parse(csq, radix, cursor)</code> 345 * @throws NumberFormatException if error when parsing. 346 */ 347 public static LargeInteger valueOf(CharSequence csq, int radix) { 348 Cursor cursor = Cursor.newInstance(0, csq.length()); 349 try { 350 return LargeInteger.parse(csq, radix, cursor); 351 } finally { 352 if (cursor.hasNext()) 353 throw new NumberFormatException("Cannot parse " + csq + " at " 354 + cursor); 355 Cursor.recycle(cursor); 356 } 357 } 358 359 /** 360 * Returns the large integer corresponding to the specified 361 * <code>java.math.BigInteger</code> instance. 362 * 363 * @param bigInteger the big integer instance. 364 * @return the large integer having the same value. 365 */ 366 public static LargeInteger valueOf(java.math.BigInteger bigInteger) { 367 byte[] bytes = bigInteger.toByteArray(); 368 return LargeInteger.valueOf(bytes, 0, bytes.length); 369 } 370 371 /** 372 * Indicates if this large integer is greater than {@link #ZERO} 373 * ({@link #ZERO}is not included). 374 * 375 * @return <code>this > ZERO</code> 376 */ 377 public boolean isPositive() { 378 return !_isNegative && (_size != 0); 379 } 380 381 /** 382 * Indicates if this large integer is less than {@link #ZERO}. 383 * 384 * @return <code>this < ZERO</code> 385 */ 386 public boolean isNegative() { 387 return _isNegative; 388 } 389 390 /** 391 * Indicates if this large integer is equal to {@link #ZERO}. 392 * 393 * @return <code>this == ZERO</code> 394 */ 395 public boolean isZero() { 396 return _size == 0; 397 } 398 399 /** 400 * Indicates if this large integer is an even number. 401 * 402 * @return <code>(this & 1) == ZERO</code> 403 */ 404 public boolean isEven() { 405 return (_size == 0) || ((_words[0] & 1) == 0); 406 } 407 408 /** 409 * Indicates if this large integer is an odd number. 410 * 411 * @return <code>(this & 1) != ZERO</code> 412 */ 413 public boolean isOdd() { 414 return !isEven(); 415 } 416 417 /** 418 * Indicates if this large integer is probably prime. 419 * 420 * @return <code>true</code> if this large integer is probable prime; 421 * <code>false</code> otherwise. 422 */ 423 public boolean isProbablyPrime() { 424 throw new UnsupportedOperationException("Not Implemented"); 425 } 426 427 /** 428 * Returns the minimal number of bits to represent this large integer 429 * in the minimal two's-complement (sign excluded). 430 * 431 * @return the length of this integer in bits (sign excluded). 432 */ 433 public int bitLength() { 434 if (_size == 0) 435 return 0; 436 final int n = _size - 1; 437 final int bitLength = MathLib.bitLength(_words[n]) + (n << 6) - n; 438 return (this.isNegative() && this.isPowerOfTwo()) ? bitLength - 1 439 : bitLength; 440 } 441 442 /** 443 * Returns the minimal number of decimal digits necessary to represent 444 * this large integer (sign excluded). 445 * 446 * @return the maximum number of digits. 447 */ 448 public int digitLength() { 449 int bitLength = this.bitLength(); 450 int min = (int) (bitLength * BITS_TO_DIGITS) + 1; 451 int max = (int) ((bitLength + 1) * BITS_TO_DIGITS) + 1; 452 if (min == max) 453 return min; 454 return (LargeInteger.ONE.times10pow(min + 1).isLargerThan(this)) ? min 455 : min + 1; 456 } 457 458 private static final double BITS_TO_DIGITS = MathLib.LOG2 / MathLib.LOG10; 459 460 /** 461 * Indicates if this number is a power of two (equals to 2<sup> 462 * ({@link #bitLength bitLength()} - 1)</sup>). 463 * 464 * @return <code>true</code> if this number is a power of two; 465 * <code>false</code> otherwise. 466 */ 467 public boolean isPowerOfTwo() { 468 if (_size == 0) 469 return false; 470 final int n = _size - 1; 471 for (int j = 0; j < n; j++) { 472 if (_words[j] != 0) 473 return false; 474 } 475 final int bitLength = MathLib.bitLength(_words[n]); 476 return _words[n] == (1L << (bitLength - 1)); 477 } 478 479 /** 480 * Returns the index of the lowest-order one bit in this large integer 481 * or <code>-1</code> if <code>this.equals(ZERO)</code>. 482 * 483 * @return the index of the rightmost bit set or <code>-1</code> 484 */ 485 public int getLowestSetBit() { 486 if (_size == 0) 487 return -1; 488 for (int i = 0;; i++) { 489 long w = _words[i]; 490 if (w == 0) 491 continue; 492 for (int j = 0;; j++) { 493 if (((1L << j) & w) != 0) 494 return i * 63 + j; 495 } 496 } 497 } 498 499 /** 500 * Returns the final undivided part after division that is less or of 501 * lower degree than the divisor. This value is only set by the 502 * {@link #divide} operation and is not considered as part of 503 * this large integer (ignored by all methods). 504 * 505 * @return the remainder of the division for which this large integer 506 * is the quotient. 507 */ 508 public LargeInteger getRemainder() { 509 return _remainder; 510 } 511 512 /** 513 * Indicates if this large integer is larger than the one 514 * specified in absolute value. 515 * 516 * @param that the integer to be compared with. 517 * @return <code>this.abs().compareTo(that.abs()) > 0</code>. 518 */ 519 public boolean isLargerThan(LargeInteger that) { 520 return (this._size > that._size) 521 || ((this._size == that._size) && Calculus.compare(this._words, 522 that._words, this._size) > 0); 523 } 524 525 /** 526 * Returns the absolute value of this large integer. 527 * 528 * @return <code>|this|</code>. 529 */ 530 public LargeInteger abs() { 531 if (_isNegative) 532 return this.opposite(); 533 return this; 534 } 535 536 /** 537 * Returns the opposite of this large integer. 538 * 539 * @return <code>-this</code>. 540 */ 541 public LargeInteger opposite() { 542 LargeInteger li = NO_ARRAY_FACTORY.object(); 543 li._words = _words; 544 li._size = _size; 545 li._isNegative = !_isNegative && (_size != 0); 546 return li; 547 } 548 549 /** 550 * Returns the sum of this large integer with the specified 551 * <code>long</code> integer (convenience method) 552 * 553 * @param value the <code>long</code> integer being added. 554 * @return <code>this + value</code>. 555 */ 556 public LargeInteger plus(long value) { 557 return this.plus(LargeInteger.valueOf(value)); 558 } 559 560 /** 561 * Returns the sum of this large integer with the one specified. 562 * 563 * @param that the integer to be added. 564 * @return <code>this + that</code>. 565 */ 566 public LargeInteger plus(LargeInteger that) { 567 if (this._size < that._size) // Adds smallest in size to largest. 568 return that.plus(this); 569 if ((this._isNegative != that._isNegative) && (that._size != 0)) 570 return this.minus(that.opposite()); // Switches that sign. 571 LargeInteger li = ARRAY_FACTORY.array(_size + 1); 572 li._size = Calculus.add(_words, _size, that._words, that._size, 573 li._words); 574 li._isNegative = _isNegative; 575 return li; 576 } 577 578 /** 579 * Returns the difference between this large integer and the one 580 * specified. 581 * 582 * @param that the integer to be subtracted. 583 * @return <code>this - that</code>. 584 */ 585 public LargeInteger minus(LargeInteger that) { 586 if ((this._isNegative != that._isNegative) && (that._size != 0)) 587 return this.plus(that.opposite()); // Switches that sign. 588 if (that.isLargerThan(this)) // Always subtract the smallest to the largest. 589 return that.minus(this).opposite(); 590 LargeInteger li = ARRAY_FACTORY.array(this._size); 591 li._size = Calculus.subtract(_words, _size, that._words, that._size, 592 li._words); 593 li._isNegative = this._isNegative && (li._size != 0); 594 return li; 595 } 596 597 /** 598 * Returns the difference between this large integer and the specified 599 * value 600 * 601 * @param value the value to be subtracted. 602 * @return <code>this - value</code>. 603 */ 604 public LargeInteger minus(long value) { 605 return this.minus(LargeInteger.valueOf(value)); 606 } 607 608 /** 609 * Returns the product of this large integer with the one specified. 610 * 611 * @param that the large integer multiplier. 612 * @return <code>this · that</code>. 613 */ 614 public LargeInteger times(LargeInteger that) { 615 if (that._size > this._size) // Always multiply the smallest to the largest. 616 return that.times(this); 617 if (that._size <= 1) // Direct times(long) multiplication. 618 return this.times(that.longValue()); 619 if (that._size < 10) { // Conventional multiplication. 620 LargeInteger li = ARRAY_FACTORY.array(this._size + that._size); 621 li._size = Calculus.multiply(this._words, this._size, that._words, 622 that._size, li._words); 623 li._isNegative = (this._isNegative != that._isNegative); 624 return li; 625 } else if (that._size < 20) { // Karatsuba (sequential). 626 int n = (that._size >> 1) + (that._size & 1); 627 // this = a + 2^(n*63) b, that = c + 2^(n*63) d 628 LargeInteger b = this.high(n); 629 LargeInteger a = this.low(n); 630 // Optimization for square (a == c, b == d). 631 LargeInteger d = (this == that) ? b : that.high(n); 632 LargeInteger c = (this == that) ? a : that.low(n); 633 LargeInteger ab = a.plus(b); 634 LargeInteger cd = (this == that) ? ab : c.plus(d); 635 LargeInteger abcd = ab.times(cd); 636 LargeInteger ac = a.times(c); 637 LargeInteger bd = b.times(d); 638 // li = a*c + ((a+b)*(c+d)-(a*c+b*d)) 2^n + b*d 2^2n 639 return ac.plus(abcd.minus(ac.plus(bd)).shiftWordLeft(n)).plus( 640 bd.shiftWordLeft(n << 1)); 641 } else { // Karatsuba (concurrent). 642 int n = (that._size >> 1) + (that._size & 1); 643 // this = a + 2^(63*n) b, that = c + 2^(63*n) d 644 LargeInteger b = this.high(n); 645 LargeInteger a = this.low(n); 646 // Optimization for square (a == c, b == d). 647 LargeInteger d = (this == that) ? b : that.high(n); 648 LargeInteger c = (this == that) ? a : that.low(n); 649 LargeInteger ab = a.plus(b); 650 LargeInteger cd = (this == that) ? ab : c.plus(d); 651 MultiplyLogic abcd = MultiplyLogic.newInstance(ab, cd); 652 MultiplyLogic ac = MultiplyLogic.newInstance(a, c); 653 MultiplyLogic bd = MultiplyLogic.newInstance(b, d); 654 ConcurrentContext.enter(); 655 try { // this = a + 2^n b, that = c + 2^n d 656 ConcurrentContext.execute(abcd); 657 ConcurrentContext.execute(ac); 658 ConcurrentContext.execute(bd); 659 } finally { 660 ConcurrentContext.exit(); 661 } 662 // result = a*c + ((a+b)*(c+d)-(a*c+b*d)) 2^n + b*d 2^2n 663 LargeInteger result = ac.value().plus( 664 abcd.value().minus(ac.value().plus(bd.value())) 665 .shiftWordLeft(n)).plus( 666 bd.value().shiftWordLeft(n << 1)); 667 return result; 668 } 669 } 670 671 private LargeInteger high(int w) { // this.shiftRight(w * 63) 672 LargeInteger li = ARRAY_FACTORY.array(_size - w); 673 li._isNegative = _isNegative; 674 li._size = _size - w; 675 System.arraycopy(_words, w, li._words, 0, _size - w); 676 return li; 677 } 678 679 private LargeInteger low(int w) { // this.minus(high(w).shiftLeft(w * 63)); 680 LargeInteger li = NO_ARRAY_FACTORY.object(); 681 li._words = _words; 682 li._isNegative = _isNegative; 683 for (int i = w; i > 0; i--) { 684 if (_words[i - 1] != 0) { 685 li._size = i; 686 return li; 687 } 688 } // Else zero. 689 return LargeInteger.ZERO; 690 } 691 692 private LargeInteger shiftWordLeft(int w) { // this.minus(high(w).shiftLeft(w * 63)); 693 if (_size == 0) 694 return LargeInteger.ZERO; 695 LargeInteger li = ARRAY_FACTORY.array(w + _size); 696 li._isNegative = _isNegative; 697 li._size = w + _size; 698 for (int i = 0; i < w;) { 699 li._words[i++] = 0; 700 } 701 System.arraycopy(_words, 0, li._words, w, _size); 702 return li; 703 } 704 705 /** 706 * Returns the product of this large integer with the specified 707 * <code>long</code> multiplier. 708 * 709 * @param multiplier the <code>long</code> multiplier. 710 * @return <code>this · multiplier</code>. 711 */ 712 public LargeInteger times(long multiplier) { 713 if ((this._size == 0) || (multiplier == 0)) 714 return LargeInteger.ZERO; 715 if (multiplier == Long.MIN_VALUE) 716 return times(LONG_MIN_VALUE); // Size 2. 717 boolean isNegative = _isNegative ^ (multiplier < 0); 718 multiplier = MathLib.abs(multiplier); 719 LargeInteger li = ARRAY_FACTORY.array(_size + 1); 720 li._size = Calculus.multiply(_words, _size, multiplier, li._words); 721 li._isNegative = isNegative; 722 return li; 723 } 724 725 /** 726 * Returns this large integer divided by the one specified (integer 727 * division). The remainder of this division is accessible using 728 * {@link #getRemainder}. 729 * 730 * @param that the integer divisor. 731 * @return <code>this / that</code> and <code>this % that</code> 732 * ({@link #getRemainder}) 733 * @throws ArithmeticException if <code>that.equals(ZERO)</code> 734 */ 735 public LargeInteger divide(LargeInteger that) { 736 if ((that._size <= 1) && ((that._words[0] >> 32) == 0)) 737 return divide(that.intValue()); 738 LargeInteger result; 739 LargeInteger remainder; 740 LargeInteger thisAbs = this.abs(); 741 LargeInteger thatAbs = that.abs(); 742 int precision = thisAbs.bitLength() - thatAbs.bitLength() + 1; 743 if (precision <= 0) { 744 result = LargeInteger.ZERO; 745 remainder = this; 746 } else { 747 LargeInteger thatReciprocal = thatAbs.inverseScaled(precision); 748 result = thisAbs.times(thatReciprocal); 749 result = result.shiftRight(thisAbs.bitLength() + 1); 750 751 // Calculates remainder, corrects for result +/- 1 error. 752 remainder = thisAbs.minus(thatAbs.times(result)); 753 if (remainder.compareTo(thatAbs) >= 0) { 754 remainder = remainder.minus(thatAbs); 755 result = result.plus(LargeInteger.ONE); 756 if (remainder.compareTo(thatAbs) >= 0) 757 throw new Error("Verification error for " + this + "/" 758 + that + ", please submit a bug report."); 759 } else if (remainder.isNegative()) { 760 remainder = remainder.plus(thatAbs); 761 result = result.minus(ONE); 762 if (remainder.isNegative()) 763 throw new Error("Verification error for " + this + "/" 764 + that + ", please submit a bug report."); 765 } 766 } 767 // Setups result and remainder. 768 LargeInteger li = NO_ARRAY_FACTORY.object(); 769 li._words = result._words; 770 li._size = result._size; 771 li._isNegative = (this._isNegative != that._isNegative) 772 && (result._size != 0); 773 li._remainder = _isNegative ? remainder.opposite() : remainder; 774 return li; 775 } 776 777 /** 778 * Returns this large integer divided by the specified <code>int</code> 779 * divisor. The remainder of this division is accessible using 780 * {@link #getRemainder}. 781 * 782 * @param divisor the <code>int</code> divisor. 783 * @return <code>this / divisor</code> and <code>this % divisor</code> 784 * ({@link #getRemainder}) 785 * @throws ArithmeticException if <code>divisor == 0</code> 786 */ 787 public LargeInteger divide(int divisor) { 788 if (divisor == 0) 789 throw new ArithmeticException("Division by zero"); 790 if (divisor == Integer.MIN_VALUE) { // abs(divisor) would overflow. 791 LargeInteger li = this.times2pow(-31).copy(); 792 li._isNegative = !_isNegative && (li._size != 0); 793 li._remainder = _isNegative ? LargeInteger 794 .valueOf(-(_words[0] & MASK_31)) : LargeInteger 795 .valueOf(_words[0] & MASK_31); 796 return li; 797 } 798 LargeInteger li = ARRAY_FACTORY.array(_size); 799 long rem = Calculus.divide(_words, _size, MathLib.abs(divisor), 800 li._words); 801 li._size = (_size > 0) && (li._words[_size - 1] == 0L) ? _size - 1 802 : _size; 803 li._isNegative = (_isNegative != (divisor < 0)) && (li._size != 0); 804 li._remainder = LargeInteger.valueOf(_isNegative ? -rem : rem); 805 return li; 806 } 807 808 /** 809 * Returns the remainder of the division of this large integer with 810 * the one specified (convenience method equivalent to 811 * <code>this.divide(that).getRemainder()</code>). 812 * 813 * @param that the value by which this integer is to be divided, and the 814 * remainder returned. 815 * @return <code>this % that</code> 816 * @throws ArithmeticException if <code>that.equals(ZERO)</code> 817 * @see #divide(LargeInteger) 818 */ 819 public LargeInteger remainder(LargeInteger that) { 820 return this.divide(that).getRemainder(); 821 } 822 823 /** 824 * Returns a scaled approximation of <code>1 / this</code>. 825 * 826 * @param precision the requested precision (reciprocal error being ± 1). 827 * @return <code>2<sup>(precision + this.bitLength())</sup> / this</code> 828 * @throws ArithmeticException if <code>this.isZero()</code> 829 */ 830 public LargeInteger inverseScaled(int precision) { 831 if (precision <= 30) { // Straight calculation. 832 long divisor = this.shiftRight(this.bitLength() - precision - 1)._words[0]; 833 long dividend = 1L << (precision * 2 + 1); 834 return (this.isNegative()) ? LargeInteger.valueOf(-dividend 835 / divisor) : LargeInteger.valueOf(dividend / divisor); 836 } else { // Newton iteration (x = 2 * x - x^2 * this). 837 LargeInteger x = inverseScaled(precision / 2 + 1); // Estimate. 838 LargeInteger thisTrunc = shiftRight(bitLength() - (precision + 2)); 839 LargeInteger prod = thisTrunc.times(x).times(x); 840 int diff = 2 * (precision / 2 + 2); 841 LargeInteger prodTrunc = prod.shiftRight(diff); 842 LargeInteger xPad = x.shiftLeft(precision - precision / 2 - 1); 843 LargeInteger tmp = xPad.minus(prodTrunc); 844 return xPad.plus(tmp); 845 } 846 } 847 848 /** 849 * Returns the integer square root of this integer. 850 * 851 * @return <code>k<code> such as <code>k^2 <= this < (k + 1)^2</code> 852 * @throws ArithmeticException if this integer is negative. 853 */ 854 public LargeInteger sqrt() { 855 if (this.isNegative()) 856 throw new ArithmeticException("Square root of negative integer"); 857 int bitLength = this.bitLength(); 858 StackContext.enter(); 859 try { 860 // First approximation. 861 LargeInteger k = this.times2pow(-((bitLength >> 1) + (bitLength & 1))); 862 while (true) { 863 LargeInteger newK = (k.plus(this.divide(k))).times2pow(-1); 864 if (newK.equals(k)) 865 return StackContext.outerCopy(k); 866 k = newK; 867 } 868 } finally { 869 StackContext.exit(); 870 } 871 } 872 873 /** 874 * Returns this large integer modulo the specified large integer. 875 * 876 * <p> Note: The result as the same sign as the divisor unlike the Java 877 * remainder (%) operator (which as the same sign as the dividend).</p> 878 * 879 * @param m the modulus. 880 * @return <code>this mod m</code> 881 * @see #getRemainder() 882 */ 883 public LargeInteger mod(LargeInteger m) { 884 final LargeInteger li = m.isLargerThan(this) ? this : this.divide(m) 885 .getRemainder(); 886 return (this._isNegative == m._isNegative) ? li : li.plus(m); 887 } 888 889 /** 890 * Returns the large integer whose value is <code>(this<sup>-1</sup> mod m) 891 * </code>. 892 * 893 * @param m the modulus. 894 * @return <code>this<sup>-1</sup> mod m</code>. 895 * @throws ArithmeticException <code> m <= 0</code>, or this integer 896 * has no multiplicative inverse mod m (that is, this integer 897 * is not <i>relatively prime</i> to m). 898 */ 899 public LargeInteger modInverse(LargeInteger m) { 900 if (!m.isPositive()) 901 throw new ArithmeticException("Modulus is not a positive number"); 902 StackContext.enter(); 903 try { 904 // Extended Euclidian Algorithm 905 LargeInteger a = this; 906 LargeInteger b = m; 907 LargeInteger p = ONE; 908 LargeInteger q = ZERO; 909 LargeInteger r = ZERO; 910 LargeInteger s = ONE; 911 while (!b.isZero()) { 912 LargeInteger quot = a.divide(b); 913 LargeInteger c = quot.getRemainder(); 914 a = b; 915 b = c; 916 917 LargeInteger new_r = p.minus(quot.times(r)); 918 LargeInteger new_s = q.minus(quot.times(s)); 919 p = r; 920 q = s; 921 r = new_r; 922 s = new_s; 923 } 924 if (!a.abs().equals(ONE)) // (a != 1) || (a != -1) 925 throw new ArithmeticException("GCD(" + this + ", " + m + ") = " 926 + a); 927 return StackContext.outerCopy(a.isNegative() ? p.opposite().mod(m) : p.mod(m)); 928 } finally { 929 StackContext.exit(); 930 } 931 } 932 933 /** 934 * Returns this large integer raised at the specified exponent modulo 935 * the specified modulus. 936 * 937 * @param exp the exponent. 938 * @param m the modulus. 939 * @return <code>this<sup>exp</sup> mod m</code> 940 * @throws ArithmeticException <code>m <= 0</code> 941 * @see #modInverse 942 */ 943 public LargeInteger modPow(LargeInteger exp, LargeInteger m) { 944 if (!m.isPositive()) 945 throw new ArithmeticException("Modulus is not a positive number"); 946 if (exp.isPositive()) { 947 StackContext.enter(); 948 try { 949 LargeInteger result = null; 950 LargeInteger pow2 = this.mod(m); 951 while (exp.compareTo(ONE) >= 0) { // Iteration. 952 if (exp.isOdd()) { 953 result = (result == null) ? pow2 : result.times(pow2) 954 .mod(m); 955 } 956 pow2 = pow2.times(pow2).mod(m); 957 exp = exp.shiftRight(1); 958 } 959 return StackContext.outerCopy(result); 960 } finally { 961 StackContext.exit(); 962 } 963 } else if (exp.isNegative()) { 964 return this.modPow(exp.opposite(), m).modInverse(m); 965 } else { // exp == 0 966 return LargeInteger.ONE; 967 } 968 } 969 970 /** 971 * Returns the greatest common divisor of this large integer and 972 * the one specified. 973 * 974 * @param that the other number to compute the GCD with. 975 * @return a positive number or {@link #ZERO} if 976 * <code>(this.isZero() && that.isZero())</code>. 977 */ 978 public LargeInteger gcd(LargeInteger that) { 979 if (this.isZero()) 980 return that; 981 if (that.isZero()) 982 return this; 983 // Works with local (modifiable) copies of the inputs. 984 LargeInteger u = this.copy(); 985 u._isNegative = false; // abs() 986 LargeInteger v = that.copy(); 987 v._isNegative = false; // abs() 988 989 // Euclidian algorithm until u, v about the same size. 990 while (MathLib.abs(u._size - v._size) > 1) { 991 LargeInteger tmp = u.divide(v); 992 LargeInteger rem = tmp.getRemainder(); 993 u = v; 994 v = rem; 995 if (v.isZero()) 996 return u; 997 } 998 999 // Binary GCD Implementation adapted from 1000 // http://en.wikipedia.org/wiki/Binary_GCD_algorithm 1001 final int uShift = u.getLowestSetBit(); 1002 u.shiftRightSelf(uShift); 1003 final int vShift = v.getLowestSetBit(); 1004 v.shiftRightSelf(vShift); 1005 1006 // From here on, u is always odd. 1007 while (true) { 1008 // Now u and v are both odd, so diff(u, v) is even. 1009 // Let u = min(u, v), v = diff(u, v)/2. 1010 if (u.compareTo(v) < 0) { 1011 v.subtract(u); 1012 } else { 1013 u.subtract(v); 1014 LargeInteger tmp = u; 1015 u = v; 1016 v = tmp; // Swaps. 1017 } 1018 v.shiftRightSelf(); 1019 if (v.isZero()) 1020 break; 1021 v.shiftRightSelf(v.getLowestSetBit()); 1022 } 1023 return u.shiftLeft(MathLib.min(uShift, vShift)); 1024 } 1025 1026 private void shiftRightSelf() { 1027 if (_size == 0) 1028 return; 1029 _size = Calculus.shiftRight(0, 1, _words, _size, _words); 1030 } 1031 1032 private void shiftRightSelf(int n) { 1033 if ((n == 0) || (_size == 0)) 1034 return; 1035 int wordShift = n < 63 ? 0 : n / 63; 1036 int bitShift = n - ((wordShift << 6) - wordShift); // n - wordShift * 63 1037 _size = Calculus.shiftRight(wordShift, bitShift, _words, _size, _words); 1038 } 1039 1040 private void subtract(LargeInteger that) { // this >= that 1041 _size = Calculus.subtract(_words, _size, that._words, that._size, 1042 _words); 1043 } 1044 1045 /** 1046 * Returns the value of this large integer after performing a binary 1047 * shift to left. The shift distance, <code>n</code>, may be negative, 1048 * in which case this method performs a right shift. 1049 * 1050 * @param n the shift distance, in bits. 1051 * @return <code>this << n</code>. 1052 * @see #shiftRight 1053 */ 1054 public LargeInteger shiftLeft(int n) { 1055 if (n < 0) 1056 return shiftRight(-n); 1057 if (_size == 0) 1058 return LargeInteger.ZERO; 1059 final int wordShift = n < 63 ? 0 : n / 63; 1060 final int bitShift = n - wordShift * 63; 1061 LargeInteger li = ARRAY_FACTORY.array(_size + wordShift + 1); 1062 li._isNegative = _isNegative; 1063 li._size = Calculus.shiftLeft(wordShift, bitShift, _words, _size, 1064 li._words); 1065 return li; 1066 } 1067 1068 /** 1069 * Returns the value of this large integer after performing a binary 1070 * shift to right with sign extension <code>(-1 >> 1 == -1)</code>. 1071 * The shift distance, <code>n</code>, may be negative, in which case 1072 * this method performs a {@link #shiftLeft(int)}. 1073 * 1074 * @param n the shift distance, in bits. 1075 * @return <code>this >> n</code>. 1076 */ 1077 public LargeInteger shiftRight(int n) { 1078 LargeInteger li = this.times2pow(-n); 1079 return (_isNegative) && (n > 0) && (isShiftRightCorrection(n)) ? li 1080 .minus(LargeInteger.ONE) : li; 1081 } 1082 1083 // Indicates if bits lost when shifting right the two's-complement 1084 // representation (affects only negative numbers). 1085 private boolean isShiftRightCorrection(int n) { 1086 int wordShift = n < 63 ? 0 : n / 63; 1087 int bitShift = n - ((wordShift << 6) - wordShift); // n - wordShift * 63 1088 int i = wordShift; 1089 boolean bitsLost = (bitShift != 0) 1090 && (_words[i] << (64 - bitShift)) != 0; 1091 while ((!bitsLost) && --i >= 0) { 1092 bitsLost = _words[i--] != 0; 1093 } 1094 return bitsLost; 1095 } 1096 1097 /** 1098 * Returns the value of this large integer after multiplication by 1099 * a power of two. This method is equivalent to {@link #shiftLeft(int)} 1100 * for positive <code>n</code>; but is different from 1101 * {@link #shiftRight(int)} for negative <code>n</code> as no sign 1102 * extension is performed (<code>-1 >>> 1 == 0</code>). 1103 * 1104 * @param n the power of 2 exponent. 1105 * @return <code>this · 2<sup>n</sup></code>. 1106 */ 1107 public LargeInteger times2pow(int n) { 1108 if (n >= 0) 1109 return shiftLeft(n); 1110 n = -n; // Works with positive n. 1111 int wordShift = n < 63 ? 0 : n / 63; 1112 int bitShift = n - ((wordShift << 6) - wordShift); // n - wordShift * 63 1113 if (_size <= wordShift) // All bits have been shifted. 1114 return LargeInteger.ZERO; 1115 LargeInteger li = ARRAY_FACTORY.array(_size - wordShift); 1116 li._size = Calculus.shiftRight(wordShift, bitShift, _words, _size, 1117 li._words); 1118 li._isNegative = _isNegative && (li._size != 0); 1119 return li; 1120 } 1121 1122 /** 1123 * Returns the value of this large integer after multiplication by 1124 * a power of ten. For example:[code] 1125 * LargeInteger billion = LargeInteger.ONE.times10pow(9); // 1E9 1126 * LargeInteger million = billion.times10pow(-3);[/code] 1127 * 1128 * @param n the decimal exponent. 1129 * @return <code>this · 10<sup>n</sup></code> 1130 */ 1131 public LargeInteger times10pow(int n) { 1132 if (this._size == 0) 1133 return LargeInteger.ZERO; 1134 if (n >= 0) { 1135 int bitLength = (int) (n * DIGITS_TO_BITS); 1136 LargeInteger li = ARRAY_FACTORY.array(_size + (bitLength / 63) + 1); // Approx. 1137 li._isNegative = _isNegative; 1138 int i = (n >= LONG_POW_5.length) ? LONG_POW_5.length - 1 : n; 1139 li._size = Calculus.multiply(_words, _size, LONG_POW_5[i], 1140 li._words); 1141 for (int j = n - i; j != 0; j -= i) { 1142 i = (j >= LONG_POW_5.length) ? LONG_POW_5.length - 1 : j; 1143 li._size = Calculus.multiply(li._words, li._size, 1144 LONG_POW_5[i], li._words); 1145 } 1146 // Multiplies by 2^n 1147 final int wordShift = n < 63 ? 0 : n / 63; 1148 final int bitShift = n - ((wordShift << 6) - wordShift); // n - 63 * wordShift 1149 li._size = Calculus.shiftLeft(wordShift, bitShift, li._words, 1150 li._size, li._words); 1151 return li; 1152 } else {// n < 0 1153 n = -n; 1154 // Divides by 2^n 1155 final int wordShift = n < 63 ? 0 : n / 63; 1156 final int bitShift = n - ((wordShift << 6) - wordShift); // n - 63 * wordShift 1157 if (_size <= wordShift) // All bits would be shifted. 1158 return LargeInteger.ZERO; 1159 LargeInteger li = ARRAY_FACTORY.array(_size - wordShift); 1160 li._size = Calculus.shiftRight(wordShift, bitShift, _words, _size, 1161 li._words); 1162 for (int j = n; j != 0;) { // Divides by 5^n 1163 int i = (j >= INT_POW_5.length) ? INT_POW_5.length - 1 : j; 1164 Calculus.divide(li._words, li._size, INT_POW_5[i], li._words); 1165 if ((li._size > 0) && (li._words[li._size - 1] == 0L)) { 1166 li._size--; 1167 } 1168 j -= i; 1169 } 1170 li._isNegative = _isNegative && (li._size != 0); 1171 return li; 1172 } 1173 } 1174 1175 private static final double DIGITS_TO_BITS = MathLib.LOG10 / MathLib.LOG2; 1176 1177 private static final int[] INT_POW_5 = new int[] { 1, 5, 25, 125, 625, 1178 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625, 1179 1220703125 }; 1180 1181 private static final long[] LONG_POW_5 = new long[] { 1L, 5L, 25L, 125L, 1182 625L, 3125L, 15625L, 78125L, 390625L, 1953125L, 9765625L, 1183 48828125L, 244140625L, 1220703125L, 6103515625L, 30517578125L, 1184 152587890625L, 762939453125L, 3814697265625L, 19073486328125L, 1185 95367431640625L, 476837158203125L, 2384185791015625L, 1186 11920928955078125L, 59604644775390625L, 298023223876953125L, 1187 1490116119384765625L, 7450580596923828125L }; 1188 1189 /** 1190 * Compares this large integer against the specified object. 1191 * 1192 * @param that the object to compare with. 1193 * @return <code>true</code> if the objects are the same; <code>false</code> 1194 * otherwise. 1195 */ 1196 public boolean equals(Object that) { 1197 if (!(that instanceof LargeInteger)) 1198 return false; 1199 LargeInteger li = (LargeInteger) that; 1200 return (_size == li._size) && (_isNegative == li._isNegative) 1201 && (compare(_words, li._words, _size) == 0); 1202 } 1203 1204 /** 1205 * Compares this large integer against the specified <code>long</code> 1206 * value. 1207 * 1208 * @param value <code>long</code> value to compare with. 1209 * @return <code>true</code> if this large integer has the specified value; 1210 * <code>false</code> otherwise. 1211 */ 1212 public boolean equals(long value) { 1213 if (_size == 0) return value == 0; 1214 return ((_size <= 1) && (_isNegative ? -_words[0] == value 1215 : _words[0] == value)) 1216 || ((value == Long.MIN_VALUE) && (_isNegative) && (_size == 2) 1217 && (_words[1] == 1) && (_words[0] == 0)); 1218 } 1219 1220 /** 1221 * Returns the hash code for this large integer number. 1222 * 1223 * @return the hash code value. 1224 */ 1225 public int hashCode() { 1226 long code = 0; 1227 for (int i = _size - 1; i >= 0; i--) { 1228 code = code * 31 + _words[i]; 1229 } 1230 return _isNegative ? -(int) code : (int) code; 1231 } 1232 1233 /** 1234 * Returns the low order bits of this large integer as a <code>long</code>. 1235 * 1236 * <p>Note: This conversion can lose information about the overall magnitude 1237 * of the integer value and may return a result with the opposite 1238 * sign.</p> 1239 * 1240 * @return the numeric value represented by this integer after conversion 1241 * to type <code>long</code>. 1242 */ 1243 public long longValue() { 1244 if (_size == 0) return 0; 1245 return (_size <= 1) ? (_isNegative ? -_words[0] : _words[0]) 1246 : (_isNegative ? -((_words[1] << 63) | _words[0]) 1247 : (_words[1] << 63) | _words[0]); // bitLength > 63 bits. 1248 } 1249 1250 /** 1251 * Returns the value of this large integer as a <code>double</code>. 1252 * 1253 * @return the numeric value represented by this integer after conversion 1254 * to type <code>double</code>. 1255 */ 1256 public double doubleValue() { 1257 if (_size == 0) return 0; 1258 if (_size <= 1) 1259 return _isNegative ? -_words[0] : _words[0]; 1260 1261 // Calculates bits length (ignores sign). 1262 final int n = _size - 1; 1263 final int bitLength = MathLib.bitLength(_words[n]) + (n << 6) - n; 1264 1265 // Keep 63 most significant bits. 1266 int shift = 63 - bitLength; 1267 LargeInteger int63 = this.times2pow(shift); 1268 double d = MathLib.toDoublePow2(int63._words[0], -shift); 1269 return _isNegative ? -d : d; 1270 } 1271 1272 /** 1273 * Compares two large integers numerically. 1274 * 1275 * @param that the integer to compare with. 1276 * @return -1, 0 or 1 as this integer is numerically less than, equal to, 1277 * or greater than <code>that</code>. 1278 * @throws ClassCastException <code>that</code> is not a 1279 * large integer. 1280 */ 1281 public int compareTo(LargeInteger that) { 1282 // Compares sign. 1283 if (_isNegative && !that._isNegative) 1284 return -1; 1285 if (!_isNegative && that._isNegative) 1286 return 1; 1287 // Same sign, compares size. 1288 if (_size > that._size) 1289 return _isNegative ? -1 : 1; 1290 if (that._size > _size) 1291 return _isNegative ? 1 : -1; 1292 // Same size. 1293 return _isNegative ? compare(that._words, _words, _size) : compare( 1294 _words, that._words, _size); 1295 } 1296 1297 /** 1298 * Compares this large integer to the specified <code>long</code> value. 1299 * 1300 * @param value the <code>long</code> value to compare with. 1301 * @return -1, 0 or 1 as this integer is numerically less than, equal to, 1302 * or greater than the specified value. 1303 */ 1304 public int compareTo(long value) { 1305 if (_size > 1) 1306 return (value == Long.MAX_VALUE) && (this.equals(Long.MIN_VALUE)) ? 0 1307 : (_isNegative ? -1 : 1); 1308 // size <= 1 1309 long thisValue = _isNegative ? -_words[0] : _words[0]; 1310 return thisValue < value ? -1 : ((thisValue == value) ? 0 : 1); 1311 } 1312 1313 @Override 1314 public LargeInteger copy() { 1315 LargeInteger li = ARRAY_FACTORY.array(_size); 1316 li._isNegative = _isNegative; 1317 li._size = _size; 1318 if (_size <= 1) { 1319 li._words[0] = _words[0]; 1320 return li; 1321 } 1322 System.arraycopy(_words, 0, li._words, 0, _size); 1323 return li; 1324 } 1325 1326 //////////////////////// 1327 // Parsing/Formatting // 1328 //////////////////////// 1329 1330 /** 1331 * Returns the text representation of this number using the current 1332 * {@link TextFormat#getInstance(Class) format}. 1333 * 1334 * @return <code>TextFormat.getInstance(LargeInteger.class).format(this)</code> 1335 */ 1336 public Text toText() { 1337 return TextFormat.getInstance(LargeInteger.class).format(this); 1338 } 1339 1340 /** 1341 * Returns the text representation of this number in the specified radix. 1342 * 1343 * @param radix the radix of the representation. 1344 * @return the text representation of this number in the specified radix. 1345 */ 1346 public Text toText(int radix) { 1347 TextBuilder tmp = TextBuilder.newInstance(); 1348 try { 1349 format(this, radix, tmp); 1350 return tmp.toText(); 1351 } catch (IOException e) { 1352 throw new Error(e); 1353 } finally { 1354 TextBuilder.recycle(tmp); 1355 } 1356 } 1357 1358 /** 1359 * Parses the specified character sequence from the specified position 1360 * as a large integer in the specified radix. 1361 * 1362 * @param csq the character sequence to parse. 1363 * @param radix the radix to be used while parsing. 1364 * @param cursor the current cursor position (being maintained). 1365 * @return the corresponding large integer. 1366 * @throws NumberFormatException if error when parsing. 1367 */ 1368 public static LargeInteger parse(CharSequence csq, int radix, Cursor cursor) { 1369 final int end = cursor.getEndIndex(); 1370 boolean isNegative = cursor.at('-', csq); 1371 cursor.increment(isNegative || cursor.at('+', csq) ? 1 : 0); 1372 LargeInteger li = null; 1373 final int maxDigits = (radix <= 10) ? 18 : (radix <= 16) ? 15 : 12; 1374 while (true) { // Reads up to digitsCount at a time. 1375 int start = cursor.getIndex(); 1376 cursor.setEndIndex(MathLib.min(start + maxDigits, end)); 1377 long l = TypeFormat.parseLong(csq, radix, cursor); 1378 int readCount = cursor.getIndex() - start; 1379 if (li == null) { 1380 li = LargeInteger.valueOf(l); 1381 } else { 1382 if (li._words.length < li._size + 2) { // Resizes. 1383 LargeInteger tmp = ARRAY_FACTORY.array(li._size + 2); 1384 System.arraycopy(li._words, 0, tmp._words, 0, li._size); 1385 tmp._isNegative = li._isNegative; 1386 tmp._size = li._size; 1387 li = tmp; 1388 } 1389 long factor = pow(radix, readCount); 1390 li._size = Calculus.multiply(li._words, li._size, factor, 1391 li._words); 1392 li._size = Calculus.add(li._words, li._size, l); 1393 } 1394 if (cursor.getIndex() == end) 1395 break; // Reached end. 1396 char c = csq.charAt(cursor.getIndex()); 1397 int digit = (c <= '9') ? c - '0' 1398 : ((c <= 'Z') && (c >= 'A')) ? c - 'A' + 10 1399 : ((c <= 'z') && (c >= 'a')) ? c - 'a' + 10 : -1; 1400 if ((digit < 0) || (digit >= radix)) 1401 break; // No more digit. 1402 } 1403 cursor.setEndIndex(end); // Restore end index. 1404 return isNegative ? li.opposite() : li; 1405 } 1406 1407 private static long pow(int radix, int n) { 1408 if (radix == 10) 1409 return LONG_POW_10[n]; 1410 if (radix == 16) 1411 return LONG_POW_16[n]; 1412 long l = 1; 1413 for (int i = 0; i < n; i++) { 1414 l *= radix; 1415 } 1416 return l; 1417 } 1418 1419 private static final long[] LONG_POW_10 = new long[] { 1, 10, 100, 1000, 1420 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 1421 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 1422 100000000000000L, 1000000000000000L, 10000000000000000L, 1423 100000000000000000L, 1000000000000000000L }; 1424 1425 private static final long[] LONG_POW_16 = new long[] { 0x1, 0x10, 0x100, 1426 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000L, 1427 0x1000000000L, 0x10000000000L, 0x100000000000L, 0x1000000000000L, 1428 0x10000000000000L, 0x100000000000000L, 0x1000000000000000L }; 1429 1430 /** 1431 * Formats the specified large integer in the specified radix and into 1432 * the specified <code>Appendable</code> argument. 1433 * 1434 * @param li the large integer to format. 1435 * @param radix the radix. 1436 * @param out the <code>Appendable</code> to append. 1437 * @return the specified <code>Appendable</code> object. 1438 * @throws IllegalArgumentException if radix is not in [2 .. 36] range. 1439 * @throws IOException if an I/O exception occurs. 1440 */ 1441 public static Appendable format(LargeInteger li, int radix, Appendable out) 1442 throws IOException { 1443 if (li._isNegative) { 1444 out.append('-'); 1445 } 1446 final int maxDigits = (radix <= 10) ? 9 : (radix <= 16) ? 7 : 5; 1447 return write(li.copy(), radix, (int) pow(radix, maxDigits), out); 1448 } 1449 1450 private static Appendable write(LargeInteger li, int radix, int divisor, 1451 Appendable out) throws IOException { 1452 if (li._size <= 1) // Direct long formatting. 1453 return TypeFormat.format(li._size == 0 ? 0 : li._words[0], radix, out); 1454 int rem = (int) Calculus 1455 .divide(li._words, li._size, divisor, li._words); 1456 if (li._words[li._size - 1] == 0L) { 1457 li._size--; 1458 } 1459 write(li, radix, divisor, out); // Writes high. 1460 divisor /= radix; 1461 while (rem < divisor) { 1462 out.append('0'); 1463 divisor /= radix; 1464 } 1465 return TypeFormat.format(rem, radix, out); // Writes low. 1466 } 1467 1468 private static final long serialVersionUID = 1L; 1469}