1. /*
  2. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  3. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. */
  5. /*
  6. * @(#)BigInteger.java 1.55 03/01/29
  7. */
  8. package java.math;
  9. import java.util.Random;
  10. import java.io.*;
  11. /**
  12. * Immutable arbitrary-precision integers. All operations behave as if
  13. * BigIntegers were represented in two's-complement notation (like Java's
  14. * primitive integer types). BigInteger provides analogues to all of Java's
  15. * primitive integer operators, and all relevant methods from java.lang.Math.
  16. * Additionally, BigInteger provides operations for modular arithmetic, GCD
  17. * calculation, primality testing, prime generation, bit manipulation,
  18. * and a few other miscellaneous operations.
  19. * <p>
  20. * Semantics of arithmetic operations exactly mimic those of Java's integer
  21. * arithmetic operators, as defined in <i>The Java Language Specification</i>.
  22. * For example, division by zero throws an <tt>ArithmeticException</tt>, and
  23. * division of a negative by a positive yields a negative (or zero) remainder.
  24. * All of the details in the Spec concerning overflow are ignored, as
  25. * BigIntegers are made as large as necessary to accommodate the results of an
  26. * operation.
  27. * <p>
  28. * Semantics of shift operations extend those of Java's shift operators
  29. * to allow for negative shift distances. A right-shift with a negative
  30. * shift distance results in a left shift, and vice-versa. The unsigned
  31. * right shift operator (>>>) is omitted, as this operation makes
  32. * little sense in combination with the "infinite word size" abstraction
  33. * provided by this class.
  34. * <p>
  35. * Semantics of bitwise logical operations exactly mimic those of Java's
  36. * bitwise integer operators. The binary operators (<tt>and</tt>,
  37. * <tt>or</tt>, <tt>xor</tt>) implicitly perform sign extension on the shorter
  38. * of the two operands prior to performing the operation.
  39. * <p>
  40. * Comparison operations perform signed integer comparisons, analogous to
  41. * those performed by Java's relational and equality operators.
  42. * <p>
  43. * Modular arithmetic operations are provided to compute residues, perform
  44. * exponentiation, and compute multiplicative inverses. These methods always
  45. * return a non-negative result, between <tt>0</tt> and <tt>(modulus - 1)</tt>,
  46. * inclusive.
  47. * <p>
  48. * Bit operations operate on a single bit of the two's-complement
  49. * representation of their operand. If necessary, the operand is sign-
  50. * extended so that it contains the designated bit. None of the single-bit
  51. * operations can produce a BigInteger with a different sign from the
  52. * BigInteger being operated on, as they affect only a single bit, and the
  53. * "infinite word size" abstraction provided by this class ensures that there
  54. * are infinitely many "virtual sign bits" preceding each BigInteger.
  55. * <p>
  56. * For the sake of brevity and clarity, pseudo-code is used throughout the
  57. * descriptions of BigInteger methods. The pseudo-code expression
  58. * <tt>(i + j)</tt> is shorthand for "a BigInteger whose value is
  59. * that of the BigInteger <tt>i</tt> plus that of the BigInteger <tt>j</tt>."
  60. * The pseudo-code expression <tt>(i == j)</tt> is shorthand for
  61. * "<tt>true</tt> if and only if the BigInteger <tt>i</tt> represents the same
  62. * value as the the BigInteger <tt>j</tt>." Other pseudo-code expressions are
  63. * interpreted similarly.
  64. * <p>
  65. * All methods and constructors in this class throw
  66. * <CODE>NullPointerException</CODE> when passed
  67. * a null object reference for any input parameter.
  68. *
  69. * @see BigDecimal
  70. * @version 1.55, 01/29/03
  71. * @author Josh Bloch
  72. * @author Michael McCloskey
  73. * @since JDK1.1
  74. */
  75. public class BigInteger extends Number implements Comparable {
  76. /**
  77. * The signum of this BigInteger: -1 for negative, 0 for zero, or
  78. * 1 for positive. Note that the BigInteger zero <i>must</i> have
  79. * a signum of 0. This is necessary to ensures that there is exactly one
  80. * representation for each BigInteger value.
  81. *
  82. * @serial
  83. */
  84. int signum;
  85. /**
  86. * The magnitude of this BigInteger, in <i>big-endian</i> order: the
  87. * zeroth element of this array is the most-significant int of the
  88. * magnitude. The magnitude must be "minimal" in that the most-significant
  89. * int (<tt>mag[0]</tt>) must be non-zero. This is necessary to
  90. * ensure that there is exactly one representation for each BigInteger
  91. * value. Note that this implies that the BigInteger zero has a
  92. * zero-length mag array.
  93. */
  94. int[] mag;
  95. // These "redundant fields" are initialized with recognizable nonsense
  96. // values, and cached the first time they are needed (or never, if they
  97. // aren't needed).
  98. /**
  99. * The bitCount of this BigInteger, as returned by bitCount(), or -1
  100. * (either value is acceptable).
  101. *
  102. * @serial
  103. * @see #bitCount
  104. */
  105. private int bitCount = -1;
  106. /**
  107. * The bitLength of this BigInteger, as returned by bitLength(), or -1
  108. * (either value is acceptable).
  109. *
  110. * @serial
  111. * @see #bitLength
  112. */
  113. private int bitLength = -1;
  114. /**
  115. * The lowest set bit of this BigInteger, as returned by getLowestSetBit(),
  116. * or -2 (either value is acceptable).
  117. *
  118. * @serial
  119. * @see #getLowestSetBit
  120. */
  121. private int lowestSetBit = -2;
  122. /**
  123. * The index of the lowest-order byte in the magnitude of this BigInteger
  124. * that contains a nonzero byte, or -2 (either value is acceptable). The
  125. * least significant byte has int-number 0, the next byte in order of
  126. * increasing significance has byte-number 1, and so forth.
  127. *
  128. * @serial
  129. */
  130. private int firstNonzeroByteNum = -2;
  131. /**
  132. * The index of the lowest-order int in the magnitude of this BigInteger
  133. * that contains a nonzero int, or -2 (either value is acceptable). The
  134. * least significant int has int-number 0, the next int in order of
  135. * increasing significance has int-number 1, and so forth.
  136. */
  137. private int firstNonzeroIntNum = -2;
  138. /**
  139. * This mask is used to obtain the value of an int as if it were unsigned.
  140. */
  141. private final static long LONG_MASK = 0xffffffffL;
  142. //Constructors
  143. /**
  144. * Translates a byte array containing the two's-complement binary
  145. * representation of a BigInteger into a BigInteger. The input array is
  146. * assumed to be in <i>big-endian</i> byte-order: the most significant
  147. * byte is in the zeroth element.
  148. *
  149. * @param val big-endian two's-complement binary representation of
  150. * BigInteger.
  151. * @throws NumberFormatException <tt>val</tt> is zero bytes long.
  152. */
  153. public BigInteger(byte[] val) {
  154. if (val.length == 0)
  155. throw new NumberFormatException("Zero length BigInteger");
  156. if (val[0] < 0) {
  157. mag = makePositive(val);
  158. signum = -1;
  159. } else {
  160. mag = stripLeadingZeroBytes(val);
  161. signum = (mag.length == 0 ? 0 : 1);
  162. }
  163. }
  164. /**
  165. * This private constructor translates an int array containing the
  166. * two's-complement binary representation of a BigInteger into a
  167. * BigInteger. The input array is assumed to be in <i>big-endian</i>
  168. * int-order: the most significant int is in the zeroth element.
  169. */
  170. private BigInteger(int[] val) {
  171. if (val.length == 0)
  172. throw new NumberFormatException("Zero length BigInteger");
  173. if (val[0] < 0) {
  174. mag = makePositive(val);
  175. signum = -1;
  176. } else {
  177. mag = trustedStripLeadingZeroInts(val);
  178. signum = (mag.length == 0 ? 0 : 1);
  179. }
  180. }
  181. /**
  182. * Translates the sign-magnitude representation of a BigInteger into a
  183. * BigInteger. The sign is represented as an integer signum value: -1 for
  184. * negative, 0 for zero, or 1 for positive. The magnitude is a byte array
  185. * in <i>big-endian</i> byte-order: the most significant byte is in the
  186. * zeroth element. A zero-length magnitude array is permissible, and will
  187. * result in in a BigInteger value of 0, whether signum is -1, 0 or 1.
  188. *
  189. * @param signum signum of the number (-1 for negative, 0 for zero, 1
  190. * for positive).
  191. * @param magnitude big-endian binary representation of the magnitude of
  192. * the number.
  193. * @throws NumberFormatException <tt>signum</tt> is not one of the three
  194. * legal values (-1, 0, and 1), or <tt>signum</tt> is 0 and
  195. * <tt>magnitude</tt> contains one or more non-zero bytes.
  196. */
  197. public BigInteger(int signum, byte[] magnitude) {
  198. this.mag = stripLeadingZeroBytes(magnitude);
  199. if (signum < -1 || signum > 1)
  200. throw(new NumberFormatException("Invalid signum value"));
  201. if (this.mag.length==0) {
  202. this.signum = 0;
  203. } else {
  204. if (signum == 0)
  205. throw(new NumberFormatException("signum-magnitude mismatch"));
  206. this.signum = signum;
  207. }
  208. }
  209. /**
  210. * A constructor for internal use that translates the sign-magnitude
  211. * representation of a BigInteger into a BigInteger. It checks the
  212. * arguments and copies the magnitude so this constructor would be
  213. * safe for external use.
  214. */
  215. private BigInteger(int signum, int[] magnitude) {
  216. this.mag = stripLeadingZeroInts(magnitude);
  217. if (signum < -1 || signum > 1)
  218. throw(new NumberFormatException("Invalid signum value"));
  219. if (this.mag.length==0) {
  220. this.signum = 0;
  221. } else {
  222. if (signum == 0)
  223. throw(new NumberFormatException("signum-magnitude mismatch"));
  224. this.signum = signum;
  225. }
  226. }
  227. /**
  228. * Translates the String representation of a BigInteger in the specified
  229. * radix into a BigInteger. The String representation consists of an
  230. * optional minus sign followed by a sequence of one or more digits in the
  231. * specified radix. The character-to-digit mapping is provided by
  232. * <tt>Character.digit</tt>. The String may not contain any extraneous
  233. * characters (whitespace, for example).
  234. *
  235. * @param val String representation of BigInteger.
  236. * @param radix radix to be used in interpreting <tt>val</tt>.
  237. * @throws NumberFormatException <tt>val</tt> is not a valid representation
  238. * of a BigInteger in the specified radix, or <tt>radix</tt> is
  239. * outside the range from {@link Character#MIN_RADIX} to
  240. * {@link Character#MAX_RADIX}, inclusive.
  241. * @see Character#digit
  242. */
  243. public BigInteger(String val, int radix) {
  244. int cursor = 0, numDigits;
  245. int len = val.length();
  246. if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  247. throw new NumberFormatException("Radix out of range");
  248. if (val.length() == 0)
  249. throw new NumberFormatException("Zero length BigInteger");
  250. // Check for minus sign
  251. signum = 1;
  252. int index = val.indexOf('-');
  253. if (index != -1) {
  254. if (index == 0) {
  255. if (val.length() == 1)
  256. throw new NumberFormatException("Zero length BigInteger");
  257. signum = -1;
  258. cursor = 1;
  259. } else {
  260. throw new NumberFormatException("Illegal embedded minus sign");
  261. }
  262. }
  263. // Skip leading zeros and compute number of digits in magnitude
  264. while (cursor < len &&
  265. Character.digit(val.charAt(cursor),radix) == 0)
  266. cursor++;
  267. if (cursor == len) {
  268. signum = 0;
  269. mag = ZERO.mag;
  270. return;
  271. } else {
  272. numDigits = len - cursor;
  273. }
  274. // Pre-allocate array of expected size. May be too large but can
  275. // never be too small. Typically exact.
  276. int numBits = (int)(((numDigits * bitsPerDigit[radix]) >>> 10) + 1);
  277. int numWords = (numBits + 31) /32;
  278. mag = new int[numWords];
  279. // Process first (potentially short) digit group
  280. int firstGroupLen = numDigits % digitsPerInt[radix];
  281. if (firstGroupLen == 0)
  282. firstGroupLen = digitsPerInt[radix];
  283. String group = val.substring(cursor, cursor += firstGroupLen);
  284. mag[mag.length - 1] = Integer.parseInt(group, radix);
  285. if (mag[mag.length - 1] < 0)
  286. throw new NumberFormatException("Illegal digit");
  287. // Process remaining digit groups
  288. int superRadix = intRadix[radix];
  289. int groupVal = 0;
  290. while (cursor < val.length()) {
  291. group = val.substring(cursor, cursor += digitsPerInt[radix]);
  292. groupVal = Integer.parseInt(group, radix);
  293. if (groupVal < 0)
  294. throw new NumberFormatException("Illegal digit");
  295. destructiveMulAdd(mag, superRadix, groupVal);
  296. }
  297. // Required for cases where the array was overallocated.
  298. mag = trustedStripLeadingZeroInts(mag);
  299. }
  300. // Constructs a new BigInteger using a char array with radix=10
  301. BigInteger(char[] val) {
  302. int cursor = 0, numDigits;
  303. int len = val.length;
  304. // Check for leading minus sign
  305. signum = 1;
  306. if (val[0] == '-') {
  307. if (len == 1)
  308. throw new NumberFormatException("Zero length BigInteger");
  309. signum = -1;
  310. cursor = 1;
  311. }
  312. // Skip leading zeros and compute number of digits in magnitude
  313. while (cursor < len && Character.digit(val[cursor], 10) == 0)
  314. cursor++;
  315. if (cursor == len) {
  316. signum = 0;
  317. mag = ZERO.mag;
  318. return;
  319. } else {
  320. numDigits = len - cursor;
  321. }
  322. // Pre-allocate array of expected size
  323. int numWords;
  324. if (len < 10) {
  325. numWords = 1;
  326. } else {
  327. int numBits = (int)(((numDigits * bitsPerDigit[10]) >>> 10) + 1);
  328. numWords = (numBits + 31) /32;
  329. }
  330. mag = new int[numWords];
  331. // Process first (potentially short) digit group
  332. int firstGroupLen = numDigits % digitsPerInt[10];
  333. if (firstGroupLen == 0)
  334. firstGroupLen = digitsPerInt[10];
  335. mag[mag.length-1] = parseInt(val, cursor, cursor += firstGroupLen);
  336. // Process remaining digit groups
  337. while (cursor < len) {
  338. int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
  339. destructiveMulAdd(mag, intRadix[10], groupVal);
  340. }
  341. mag = trustedStripLeadingZeroInts(mag);
  342. }
  343. // Create an integer with the digits between the two indexes
  344. // Assumes start < end. The result may be negative, but it
  345. // is to be treated as an unsigned value.
  346. private int parseInt(char[] source, int start, int end) {
  347. int result = Character.digit(source[start++], 10);
  348. if (result == -1)
  349. throw new NumberFormatException(new String(source));
  350. for (int index = start; index<end; index++) {
  351. int nextVal = Character.digit(source[index], 10);
  352. if (nextVal == -1)
  353. throw new NumberFormatException(new String(source));
  354. result = 10*result + nextVal;
  355. }
  356. return result;
  357. }
  358. // bitsPerDigit in the given radix times 1024
  359. // Rounded up to avoid underallocation.
  360. private static long bitsPerDigit[] = { 0, 0,
  361. 1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
  362. 3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
  363. 4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
  364. 5253, 5295};
  365. // Multiply x array times word y in place, and add word z
  366. private static void destructiveMulAdd(int[] x, int y, int z) {
  367. // Perform the multiplication word by word
  368. long ylong = y & LONG_MASK;
  369. long zlong = z & LONG_MASK;
  370. int len = x.length;
  371. long product = 0;
  372. long carry = 0;
  373. for (int i = len-1; i >= 0; i--) {
  374. product = ylong * (x[i] & LONG_MASK) + carry;
  375. x[i] = (int)product;
  376. carry = product >>> 32;
  377. }
  378. // Perform the addition
  379. long sum = (x[len-1] & LONG_MASK) + zlong;
  380. x[len-1] = (int)sum;
  381. carry = sum >>> 32;
  382. for (int i = len-2; i >= 0; i--) {
  383. sum = (x[i] & LONG_MASK) + carry;
  384. x[i] = (int)sum;
  385. carry = sum >>> 32;
  386. }
  387. }
  388. /**
  389. * Translates the decimal String representation of a BigInteger into a
  390. * BigInteger. The String representation consists of an optional minus
  391. * sign followed by a sequence of one or more decimal digits. The
  392. * character-to-digit mapping is provided by <tt>Character.digit</tt>.
  393. * The String may not contain any extraneous characters (whitespace, for
  394. * example).
  395. *
  396. * @param val decimal String representation of BigInteger.
  397. * @throws NumberFormatException <tt>val</tt> is not a valid representation
  398. * of a BigInteger.
  399. * @see Character#digit
  400. */
  401. public BigInteger(String val) {
  402. this(val, 10);
  403. }
  404. /**
  405. * Constructs a randomly generated BigInteger, uniformly distributed over
  406. * the range <tt>0</tt> to <tt>(2<sup>numBits</sup> - 1)</tt>, inclusive.
  407. * The uniformity of the distribution assumes that a fair source of random
  408. * bits is provided in <tt>rnd</tt>. Note that this constructor always
  409. * constructs a non-negative BigInteger.
  410. *
  411. * @param numBits maximum bitLength of the new BigInteger.
  412. * @param rnd source of randomness to be used in computing the new
  413. * BigInteger.
  414. * @throws IllegalArgumentException <tt>numBits</tt> is negative.
  415. * @see #bitLength
  416. */
  417. public BigInteger(int numBits, Random rnd) {
  418. this(1, randomBits(numBits, rnd));
  419. }
  420. private static byte[] randomBits(int numBits, Random rnd) {
  421. if (numBits < 0)
  422. throw new IllegalArgumentException("numBits must be non-negative");
  423. int numBytes = (numBits+7)/8;
  424. byte[] randomBits = new byte[numBytes];
  425. // Generate random bytes and mask out any excess bits
  426. if (numBytes > 0) {
  427. rnd.nextBytes(randomBits);
  428. int excessBits = 8*numBytes - numBits;
  429. randomBits[0] &= (1 << (8-excessBits)) - 1;
  430. }
  431. return randomBits;
  432. }
  433. /**
  434. * Constructs a randomly generated positive BigInteger that is probably
  435. * prime, with the specified bitLength.<p>
  436. *
  437. * It is recommended that the {@link #probablePrime probablePrime}
  438. * method be used in preference to this constructor unless there
  439. * is a compelling need to specify a certainty.
  440. *
  441. * @param bitLength bitLength of the returned BigInteger.
  442. * @param certainty a measure of the uncertainty that the caller is
  443. * willing to tolerate. The probability that the new BigInteger
  444. * represents a prime number will exceed
  445. * <tt>(1 - 1/2<sup>certainty</sup></tt>). The execution time of
  446. * this constructor is proportional to the value of this parameter.
  447. * @param rnd source of random bits used to select candidates to be
  448. * tested for primality.
  449. * @throws ArithmeticException <tt>bitLength < 2</tt>.
  450. * @see #bitLength
  451. */
  452. public BigInteger(int bitLength, int certainty, Random rnd) {
  453. BigInteger prime;
  454. if (bitLength < 2)
  455. throw new ArithmeticException("bitLength < 2");
  456. // The cutoff of 95 was chosen empirically for best performance
  457. prime = (bitLength < 95 ? smallPrime(bitLength, certainty, rnd)
  458. : largePrime(bitLength, certainty, rnd));
  459. signum = 1;
  460. mag = prime.mag;
  461. }
  462. // Minimum size in bits that the requested prime number has
  463. // before we use the large prime number generating algorithms
  464. private static final int SMALL_PRIME_THRESHOLD = 95;
  465. /**
  466. * Returns a positive BigInteger that is probably prime, with the
  467. * specified bitLength. The probability that a BigInteger returned
  468. * by this method is composite does not exceed 2<sup>-100</sup>.
  469. *
  470. * @param bitLength bitLength of the returned BigInteger.
  471. * @param rnd source of random bits used to select candidates to be
  472. * tested for primality.
  473. * @return a BigInteger of <tt>bitLength</tt> bits that is probably prime
  474. * @throws ArithmeticException <tt>bitLength < 2</tt>.
  475. * @see #bitLength
  476. */
  477. public static BigInteger probablePrime(int bitLength, Random rnd) {
  478. if (bitLength < 2)
  479. throw new ArithmeticException("bitLength < 2");
  480. // The cutoff of 95 was chosen empirically for best performance
  481. return (bitLength < SMALL_PRIME_THRESHOLD ?
  482. smallPrime(bitLength, 100, rnd) :
  483. largePrime(bitLength, 100, rnd));
  484. }
  485. /**
  486. * Find a random number of the specified bitLength that is probably prime.
  487. * This method is used for smaller primes, its performance degrades on
  488. * larger bitlengths.
  489. *
  490. * This method assumes bitLength > 1.
  491. */
  492. private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
  493. int magLen = (bitLength + 31) >>> 5;
  494. int temp[] = new int[magLen];
  495. int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int
  496. int highMask = (highBit << 1) - 1; // Bits to keep in high int
  497. while(true) {
  498. // Construct a candidate
  499. for (int i=0; i<magLen; i++)
  500. temp[i] = rnd.nextInt();
  501. temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length
  502. if (bitLength > 2)
  503. temp[magLen-1] |= 1; // Make odd if bitlen > 2
  504. BigInteger p = new BigInteger(temp, 1);
  505. // Do cheap "pre-test" if applicable
  506. if (bitLength > 6) {
  507. long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
  508. if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
  509. (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
  510. (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
  511. continue; // Candidate is composite; try another
  512. }
  513. // All candidates of bitLength 2 and 3 are prime by this point
  514. if (bitLength < 4)
  515. return p;
  516. // Do expensive test if we survive pre-test (or it's inapplicable)
  517. if (p.primeToCertainty(certainty))
  518. return p;
  519. }
  520. }
  521. private static final BigInteger SMALL_PRIME_PRODUCT
  522. = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
  523. /**
  524. * Find a random number of the specified bitLength that is probably prime.
  525. * This method is more appropriate for larger bitlengths since it uses
  526. * a sieve to eliminate most composites before using a more expensive
  527. * test.
  528. */
  529. private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
  530. BigInteger p;
  531. p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
  532. p.mag[p.mag.length-1] &= 0xfffffffe;
  533. // Use a sieve length likely to contain the next prime number
  534. int searchLen = (bitLength / 20) * 64;
  535. BitSieve searchSieve = new BitSieve(p, searchLen);
  536. BigInteger candidate = searchSieve.retrieve(p, certainty);
  537. while ((candidate == null) || (candidate.bitLength() != bitLength)) {
  538. p = p.add(BigInteger.valueOf(2*searchLen));
  539. if (p.bitLength() != bitLength)
  540. p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
  541. p.mag[p.mag.length-1] &= 0xfffffffe;
  542. searchSieve = new BitSieve(p, searchLen);
  543. candidate = searchSieve.retrieve(p, certainty);
  544. }
  545. return candidate;
  546. }
  547. /**
  548. * Returns <tt>true</tt> if this BigInteger is probably prime,
  549. * <tt>false</tt> if it's definitely composite.
  550. *
  551. * This method assumes bitLength > 2.
  552. *
  553. * @param certainty a measure of the uncertainty that the caller is
  554. * willing to tolerate: if the call returns <tt>true</tt>
  555. * the probability that this BigInteger is prime exceeds
  556. * <tt>(1 - 1/2<sup>certainty</sup>)</tt>. The execution time of
  557. * this method is proportional to the value of this parameter.
  558. * @return <tt>true</tt> if this BigInteger is probably prime,
  559. * <tt>false</tt> if it's definitely composite.
  560. */
  561. boolean primeToCertainty(int certainty) {
  562. int rounds = 0;
  563. int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;
  564. // The relationship between the certainty and the number of rounds
  565. // we perform is given in the draft standard ANSI X9.80, "PRIME
  566. // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
  567. int sizeInBits = this.bitLength();
  568. if (sizeInBits < 100) {
  569. rounds = 50;
  570. rounds = n < rounds ? n : rounds;
  571. return passesMillerRabin(rounds);
  572. }
  573. if (sizeInBits < 256) {
  574. rounds = 27;
  575. } else if (sizeInBits < 512) {
  576. rounds = 15;
  577. } else if (sizeInBits < 768) {
  578. rounds = 8;
  579. } else if (sizeInBits < 1024) {
  580. rounds = 4;
  581. } else {
  582. rounds = 2;
  583. }
  584. rounds = n < rounds ? n : rounds;
  585. return passesMillerRabin(rounds) && passesLucasLehmer();
  586. }
  587. /**
  588. * Returns true iff this BigInteger is a Lucas-Lehmer probable prime.
  589. *
  590. * The following assumptions are made:
  591. * This BigInteger is a positive, odd number.
  592. */
  593. private boolean passesLucasLehmer() {
  594. BigInteger thisPlusOne = this.add(ONE);
  595. // Step 1
  596. int d = 5;
  597. while (jacobiSymbol(d, this) != -1) {
  598. // 5, -7, 9, -11, ...
  599. d = (d<0) ? Math.abs(d)+2 : -(d+2);
  600. }
  601. // Step 2
  602. BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);
  603. // Step 3
  604. return u.mod(this).equals(ZERO);
  605. }
  606. /**
  607. * Computes Jacobi(p,n).
  608. * Assumes n is positive, odd.
  609. */
  610. int jacobiSymbol(int p, BigInteger n) {
  611. if (p == 0)
  612. return 0;
  613. // Algorithm and comments adapted from Colin Plumb's C library.
  614. int j = 1;
  615. int u = n.mag[n.mag.length-1];
  616. // Make p positive
  617. if (p < 0) {
  618. p = -p;
  619. int n8 = u & 7;
  620. if ((n8 == 3) || (n8 == 7))
  621. j = -j; // 3 (011) or 7 (111) mod 8
  622. }
  623. // Get rid of factors of 2 in p
  624. while ((p & 3) == 0)
  625. p >>= 2;
  626. if ((p & 1) == 0) {
  627. p >>= 1;
  628. if (((u ^ u>>1) & 2) != 0)
  629. j = -j; // 3 (011) or 5 (101) mod 8
  630. }
  631. if (p == 1)
  632. return j;
  633. // Then, apply quadratic reciprocity
  634. if ((p & u & 2) != 0) // p = u = 3 (mod 4)?
  635. j = -j;
  636. // And reduce u mod p
  637. u = n.mod(BigInteger.valueOf(p)).intValue();
  638. // Now compute Jacobi(u,p), u < p
  639. while (u != 0) {
  640. while ((u & 3) == 0)
  641. u >>= 2;
  642. if ((u & 1) == 0) {
  643. u >>= 1;
  644. if (((p ^ p>>1) & 2) != 0)
  645. j = -j; // 3 (011) or 5 (101) mod 8
  646. }
  647. if (u == 1)
  648. return j;
  649. // Now both u and p are odd, so use quadratic reciprocity
  650. if (u < p) {
  651. int t = u; u = p; p = t;
  652. if ((u & p & 2) != 0)// u = p = 3 (mod 4)?
  653. j = -j;
  654. }
  655. // Now u >= p, so it can be reduced
  656. u %= p;
  657. }
  658. return 0;
  659. }
  660. private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
  661. BigInteger d = BigInteger.valueOf(z);
  662. BigInteger u = ONE; BigInteger u2;
  663. BigInteger v = ONE; BigInteger v2;
  664. for (int i=k.bitLength()-2; i>=0; i--) {
  665. u2 = u.multiply(v).mod(n);
  666. v2 = v.square().add(d.multiply(u.square())).mod(n);
  667. if (v2.testBit(0)) {
  668. v2 = n.subtract(v2);
  669. v2.signum = - v2.signum;
  670. }
  671. v2 = v2.shiftRight(1);
  672. u = u2; v = v2;
  673. if (k.testBit(i)) {
  674. u2 = u.add(v).mod(n);
  675. if (u2.testBit(0)) {
  676. u2 = n.subtract(u2);
  677. u2.signum = - u2.signum;
  678. }
  679. u2 = u2.shiftRight(1);
  680. v2 = v.add(d.multiply(u)).mod(n);
  681. if (v2.testBit(0)) {
  682. v2 = n.subtract(v2);
  683. v2.signum = - v2.signum;
  684. }
  685. v2 = v2.shiftRight(1);
  686. u = u2; v = v2;
  687. }
  688. }
  689. return u;
  690. }
  691. /**
  692. * Returns true iff this BigInteger passes the specified number of
  693. * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
  694. * 186-2).
  695. *
  696. * The following assumptions are made:
  697. * This BigInteger is a positive, odd number greater than 2.
  698. * iterations<=50.
  699. */
  700. private boolean passesMillerRabin(int iterations) {
  701. // Find a and m such that m is odd and this == 1 + 2**a * m
  702. BigInteger thisMinusOne = this.subtract(ONE);
  703. BigInteger m = thisMinusOne;
  704. int a = m.getLowestSetBit();
  705. m = m.shiftRight(a);
  706. // Do the tests
  707. Random rnd = new Random();
  708. for (int i=0; i<iterations; i++) {
  709. // Generate a uniform random on (1, this)
  710. BigInteger b;
  711. do {
  712. b = new BigInteger(this.bitLength(), rnd);
  713. } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);
  714. int j = 0;
  715. BigInteger z = b.modPow(m, this);
  716. while(!((j==0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
  717. if (j>0 && z.equals(ONE) || ++j==a)
  718. return false;
  719. z = z.modPow(TWO, this);
  720. }
  721. }
  722. return true;
  723. }
  724. /**
  725. * This private constructor differs from its public cousin
  726. * with the arguments reversed in two ways: it assumes that its
  727. * arguments are correct, and it doesn't copy the magnitude array.
  728. */
  729. private BigInteger(int[] magnitude, int signum) {
  730. this.signum = (magnitude.length==0 ? 0 : signum);
  731. this.mag = magnitude;
  732. }
  733. /**
  734. * This private constructor is for internal use and assumes that its
  735. * arguments are correct.
  736. */
  737. private BigInteger(byte[] magnitude, int signum) {
  738. this.signum = (magnitude.length==0 ? 0 : signum);
  739. this.mag = stripLeadingZeroBytes(magnitude);
  740. }
  741. /**
  742. * This private constructor is for internal use in converting
  743. * from a MutableBigInteger object into a BigInteger.
  744. */
  745. BigInteger(MutableBigInteger val, int sign) {
  746. if (val.offset > 0 || val.value.length != val.intLen) {
  747. mag = new int[val.intLen];
  748. for(int i=0; i<val.intLen; i++)
  749. mag[i] = val.value[val.offset+i];
  750. } else {
  751. mag = val.value;
  752. }
  753. this.signum = (val.intLen == 0) ? 0 : sign;
  754. }
  755. //Static Factory Methods
  756. /**
  757. * Returns a BigInteger whose value is equal to that of the
  758. * specified <code>long</code>. This "static factory method" is
  759. * provided in preference to a (<code>long</code>) constructor
  760. * because it allows for reuse of frequently used BigIntegers.
  761. *
  762. * @param val value of the BigInteger to return.
  763. * @return a BigInteger with the specified value.
  764. */
  765. public static BigInteger valueOf(long val) {
  766. // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
  767. if (val == 0)
  768. return ZERO;
  769. if (val > 0 && val <= MAX_CONSTANT)
  770. return posConst[(int) val];
  771. else if (val < 0 && val >= -MAX_CONSTANT)
  772. return negConst[(int) -val];
  773. return new BigInteger(val);
  774. }
  775. /**
  776. * Constructs a BigInteger with the specified value, which may not be zero.
  777. */
  778. private BigInteger(long val) {
  779. if (val < 0) {
  780. signum = -1;
  781. val = -val;
  782. } else {
  783. signum = 1;
  784. }
  785. int highWord = (int)(val >>> 32);
  786. if (highWord==0) {
  787. mag = new int[1];
  788. mag[0] = (int)val;
  789. } else {
  790. mag = new int[2];
  791. mag[0] = highWord;
  792. mag[1] = (int)val;
  793. }
  794. }
  795. /**
  796. * Returns a BigInteger with the given two's complement representation.
  797. * Assumes that the input array will not be modified (the returned
  798. * BigInteger will reference the input array if feasible).
  799. */
  800. private static BigInteger valueOf(int val[]) {
  801. return (val[0]>0 ? new BigInteger(val, 1) : new BigInteger(val));
  802. }
  803. // Constants
  804. /**
  805. * Initialize static constant array when class is loaded.
  806. */
  807. private final static int MAX_CONSTANT = 16;
  808. private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
  809. private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
  810. static {
  811. for (int i = 1; i <= MAX_CONSTANT; i++) {
  812. int[] magnitude = new int[1];
  813. magnitude[0] = (int) i;
  814. posConst[i] = new BigInteger(magnitude, 1);
  815. negConst[i] = new BigInteger(magnitude, -1);
  816. }
  817. }
  818. /**
  819. * The BigInteger constant zero.
  820. *
  821. * @since 1.2
  822. */
  823. public static final BigInteger ZERO = new BigInteger(new int[0], 0);
  824. /**
  825. * The BigInteger constant one.
  826. *
  827. * @since 1.2
  828. */
  829. public static final BigInteger ONE = valueOf(1);
  830. /**
  831. * The BigInteger constant two. (Not exported.)
  832. */
  833. private static final BigInteger TWO = valueOf(2);
  834. // Arithmetic Operations
  835. /**
  836. * Returns a BigInteger whose value is <tt>(this + val)</tt>.
  837. *
  838. * @param val value to be added to this BigInteger.
  839. * @return <tt>this + val</tt>
  840. */
  841. public BigInteger add(BigInteger val) {
  842. int[] resultMag;
  843. if (val.signum == 0)
  844. return this;
  845. if (signum == 0)
  846. return val;
  847. if (val.signum == signum)
  848. return new BigInteger(add(mag, val.mag), signum);
  849. int cmp = intArrayCmp(mag, val.mag);
  850. if (cmp==0)
  851. return ZERO;
  852. resultMag = (cmp>0 ? subtract(mag, val.mag)
  853. : subtract(val.mag, mag));
  854. resultMag = trustedStripLeadingZeroInts(resultMag);
  855. return new BigInteger(resultMag, cmp*signum);
  856. }
  857. /**
  858. * Adds the contents of the int arrays x and y. This method allocates
  859. * a new int array to hold the answer and returns a reference to that
  860. * array.
  861. */
  862. private static int[] add(int[] x, int[] y) {
  863. // If x is shorter, swap the two arrays
  864. if (x.length < y.length) {
  865. int[] tmp = x;
  866. x = y;
  867. y = tmp;
  868. }
  869. int xIndex = x.length;
  870. int yIndex = y.length;
  871. int result[] = new int[xIndex];
  872. long sum = 0;
  873. // Add common parts of both numbers
  874. while(yIndex > 0) {
  875. sum = (x[--xIndex] & LONG_MASK) +
  876. (y[--yIndex] & LONG_MASK) + (sum >>> 32);
  877. result[xIndex] = (int)sum;
  878. }
  879. // Copy remainder of longer number while carry propagation is required
  880. boolean carry = (sum >>> 32 != 0);
  881. while (xIndex > 0 && carry)
  882. carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
  883. // Copy remainder of longer number
  884. while (xIndex > 0)
  885. result[--xIndex] = x[xIndex];
  886. // Grow result if necessary
  887. if (carry) {
  888. int newLen = result.length + 1;
  889. int temp[] = new int[newLen];
  890. for (int i = 1; i<newLen; i++)
  891. temp[i] = result[i-1];
  892. temp[0] = 0x01;
  893. result = temp;
  894. }
  895. return result;
  896. }
  897. /**
  898. * Returns a BigInteger whose value is <tt>(this - val)</tt>.
  899. *
  900. * @param val value to be subtracted from this BigInteger.
  901. * @return <tt>this - val</tt>
  902. */
  903. public BigInteger subtract(BigInteger val) {
  904. int[] resultMag;
  905. if (val.signum == 0)
  906. return this;
  907. if (signum == 0)
  908. return val.negate();
  909. if (val.signum != signum)
  910. return new BigInteger(add(mag, val.mag), signum);
  911. int cmp = intArrayCmp(mag, val.mag);
  912. if (cmp==0)
  913. return ZERO;
  914. resultMag = (cmp>0 ? subtract(mag, val.mag)
  915. : subtract(val.mag, mag));
  916. resultMag = trustedStripLeadingZeroInts(resultMag);
  917. return new BigInteger(resultMag, cmp*signum);
  918. }
  919. /**
  920. * Subtracts the contents of the second int arrays (little) from the
  921. * first (big). The first int array (big) must represent a larger number
  922. * than the second. This method allocates the space necessary to hold the
  923. * answer.
  924. */
  925. private static int[] subtract(int[] big, int[] little) {
  926. int bigIndex = big.length;
  927. int result[] = new int[bigIndex];
  928. int littleIndex = little.length;
  929. long difference = 0;
  930. // Subtract common parts of both numbers
  931. while(littleIndex > 0) {
  932. difference = (big[--bigIndex] & LONG_MASK) -
  933. (little[--littleIndex] & LONG_MASK) +
  934. (difference >> 32);
  935. result[bigIndex] = (int)difference;
  936. }
  937. // Subtract remainder of longer number while borrow propagates
  938. boolean borrow = (difference >> 32 != 0);
  939. while (bigIndex > 0 && borrow)
  940. borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
  941. // Copy remainder of longer number
  942. while (bigIndex > 0)
  943. result[--bigIndex] = big[bigIndex];
  944. return result;
  945. }
  946. /**
  947. * Returns a BigInteger whose value is <tt>(this * val)</tt>.
  948. *
  949. * @param val value to be multiplied by this BigInteger.
  950. * @return <tt>this * val</tt>
  951. */
  952. public BigInteger multiply(BigInteger val) {
  953. if (signum == 0 || val.signum==0)
  954. return ZERO;
  955. int[] result = multiplyToLen(mag, mag.length,
  956. val.mag, val.mag.length, null);
  957. result = trustedStripLeadingZeroInts(result);
  958. return new BigInteger(result, signum*val.signum);
  959. }
  960. /**
  961. * Multiplies int arrays x and y to the specified lengths and places
  962. * the result into z.
  963. */
  964. private int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
  965. int xstart = xlen - 1;
  966. int ystart = ylen - 1;
  967. if (z == null || z.length < (xlen+ ylen))
  968. z = new int[xlen+ylen];
  969. long carry = 0;
  970. for (int j=ystart, k=ystart+1+xstart; j>=0; j--, k--) {
  971. long product = (y[j] & LONG_MASK) *
  972. (x[xstart] & LONG_MASK) + carry;
  973. z[k] = (int)product;
  974. carry = product >>> 32;
  975. }
  976. z[xstart] = (int)carry;
  977. for (int i = xstart-1; i >= 0; i--) {
  978. carry = 0;
  979. for (int j=ystart, k=ystart+1+i; j>=0; j--, k--) {
  980. long product = (y[j] & LONG_MASK) *
  981. (x[i] & LONG_MASK) +
  982. (z[k] & LONG_MASK) + carry;
  983. z[k] = (int)product;
  984. carry = product >>> 32;
  985. }
  986. z[i] = (int)carry;
  987. }
  988. return z;
  989. }
  990. /**
  991. * Returns a BigInteger whose value is <tt>(this<sup>2</sup>)</tt>.
  992. *
  993. * @return <tt>this<sup>2</sup></tt>
  994. */
  995. private BigInteger square() {
  996. if (signum == 0)
  997. return ZERO;
  998. int[] z = squareToLen(mag, mag.length, null);
  999. return new BigInteger(trustedStripLeadingZeroInts(z), 1);
  1000. }
  1001. /**
  1002. * Squares the contents of the int array x. The result is placed into the
  1003. * int array z. The contents of x are not changed.
  1004. */
  1005. private static final int[] squareToLen(int[] x, int len, int[] z) {
  1006. /*
  1007. * The algorithm used here is adapted from Colin Plumb's C library.
  1008. * Technique: Consider the partial products in the multiplication
  1009. * of "abcde" by itself:
  1010. *
  1011. * a b c d e
  1012. * * a b c d e
  1013. * ==================
  1014. * ae be ce de ee
  1015. * ad bd cd dd de
  1016. * ac bc cc cd ce
  1017. * ab bb bc bd be
  1018. * aa ab ac ad ae
  1019. *
  1020. * Note that everything above the main diagonal:
  1021. * ae be ce de = (abcd) * e
  1022. * ad bd cd = (abc) * d
  1023. * ac bc = (ab) * c
  1024. * ab = (a) * b
  1025. *
  1026. * is a copy of everything below the main diagonal:
  1027. * de
  1028. * cd ce
  1029. * bc bd be
  1030. * ab ac ad ae
  1031. *
  1032. * Thus, the sum is 2 * (off the diagonal) + diagonal.
  1033. *
  1034. * This is accumulated beginning with the diagonal (which
  1035. * consist of the squares of the digits of the input), which is then
  1036. * divided by two, the off-diagonal added, and multiplied by two
  1037. * again. The low bit is simply a copy of the low bit of the
  1038. * input, so it doesn't need special care.
  1039. */
  1040. int zlen = len << 1;
  1041. if (z == null || z.length < zlen)
  1042. z = new int[zlen];
  1043. // Store the squares, right shifted one bit (i.e., divided by 2)
  1044. int lastProductLowWord = 0;
  1045. for (int j=0, i=0; j<len; j++) {
  1046. long piece = (x[j] & LONG_MASK);
  1047. long product = piece * piece;
  1048. z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);
  1049. z[i++] = (int)(product >>> 1);
  1050. lastProductLowWord = (int)product;
  1051. }
  1052. // Add in off-diagonal sums
  1053. for (int i=len, offset=1; i>0; i--, offset+=2) {
  1054. int t = x[i-1];
  1055. t = mulAdd(z, x, offset, i-1, t);
  1056. addOne(z, offset-1, i, t);
  1057. }
  1058. // Shift back up and set low bit
  1059. primitiveLeftShift(z, zlen, 1);
  1060. z[zlen-1] |= x[len-1] & 1;
  1061. return z;
  1062. }
  1063. /**
  1064. * Returns a BigInteger whose value is <tt>(this / val)</tt>.
  1065. *
  1066. * @param val value by which this BigInteger is to be divided.
  1067. * @return <tt>this / val</tt>
  1068. * @throws ArithmeticException <tt>val==0</tt>
  1069. */
  1070. public BigInteger divide(BigInteger val) {
  1071. MutableBigInteger q = new MutableBigInteger(),
  1072. r = new MutableBigInteger(),
  1073. a = new MutableBigInteger(this.mag),
  1074. b = new MutableBigInteger(val.mag);
  1075. a.divide(b, q, r);
  1076. return new BigInteger(q, this.signum * val.signum);
  1077. }
  1078. /**
  1079. * Returns an array of two BigIntegers containing <tt>(this / val)</tt>
  1080. * followed by <tt>(this % val)</tt>.
  1081. *
  1082. * @param val value by which this BigInteger is to be divided, and the
  1083. * remainder computed.
  1084. * @return an array of two BigIntegers: the quotient <tt>(this / val)</tt>
  1085. * is the initial element, and the remainder <tt>(this % val)</tt>
  1086. * is the final element.
  1087. * @throws ArithmeticException <tt>val==0</tt>
  1088. */
  1089. public BigInteger[] divideAndRemainder(BigInteger val) {
  1090. BigInteger[] result = new BigInteger[2];
  1091. MutableBigInteger q = new MutableBigInteger(),
  1092. r = new MutableBigInteger(),
  1093. a = new MutableBigInteger(this.mag),
  1094. b = new MutableBigInteger(val.mag);
  1095. a.divide(b, q, r);
  1096. result[0] = new BigInteger(q, this.signum * val.signum);
  1097. result[1] = new BigInteger(r, this.signum);
  1098. return result;
  1099. }
  1100. /**
  1101. * Returns a BigInteger whose value is <tt>(this % val)</tt>.
  1102. *
  1103. * @param val value by which this BigInteger is to be divided, and the
  1104. * remainder computed.
  1105. * @return <tt>this % val</tt>
  1106. * @throws ArithmeticException <tt>val==0</tt>
  1107. */
  1108. public BigInteger remainder(BigInteger val) {
  1109. MutableBigInteger q = new MutableBigInteger(),
  1110. r = new MutableBigInteger(),
  1111. a = new MutableBigInteger(this.mag),
  1112. b = new MutableBigInteger(val.mag);
  1113. a.divide(b, q, r);
  1114. return new BigInteger(r, this.signum);
  1115. }
  1116. /**
  1117. * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>.
  1118. * Note that <tt>exponent</tt> is an integer rather than a BigInteger.
  1119. *
  1120. * @param exponent exponent to which this BigInteger is to be raised.
  1121. * @return <tt>this<sup>exponent</sup></tt>
  1122. * @throws ArithmeticException <tt>exponent</tt> is negative. (This would
  1123. * cause the operation to yield a non-integer value.)
  1124. */
  1125. public BigInteger pow(int exponent) {
  1126. if (exponent < 0)
  1127. throw new ArithmeticException("Negative exponent");
  1128. if (signum==0)
  1129. return (exponent==0 ? ONE : this);
  1130. // Perform exponentiation using repeated squaring trick
  1131. int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
  1132. int[] baseToPow2 = this.mag;
  1133. int[] result = {1};
  1134. while (exponent != 0) {
  1135. if ((exponent & 1)==1) {
  1136. result = multiplyToLen(result, result.length,
  1137. baseToPow2, baseToPow2.length, null);
  1138. result = trustedStripLeadingZeroInts(result);
  1139. }
  1140. if ((exponent >>>= 1) != 0) {
  1141. baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null);
  1142. baseToPow2 = trustedStripLeadingZeroInts(baseToPow2);
  1143. }
  1144. }
  1145. return new BigInteger(result, newSign);
  1146. }
  1147. /**
  1148. * Returns a BigInteger whose value is the greatest common divisor of
  1149. * <tt>abs(this)</tt> and <tt>abs(val)</tt>. Returns 0 if
  1150. * <tt>this==0 && val==0</tt>.
  1151. *
  1152. * @param val value with with the GCD is to be computed.
  1153. * @return <tt>GCD(abs(this), abs(val))</tt>
  1154. */
  1155. public BigInteger gcd(BigInteger val) {
  1156. if (val.signum == 0)
  1157. return this.abs();
  1158. else if (this.signum == 0)
  1159. return val.abs();
  1160. MutableBigInteger a = new MutableBigInteger(this);
  1161. MutableBigInteger b = new MutableBigInteger(val);
  1162. MutableBigInteger result = a.hybridGCD(b);
  1163. return new BigInteger(result, 1);
  1164. }
  1165. /**
  1166. * Left shift int array a up to len by n bits. Returns the array that
  1167. * results from the shift since space may have to be reallocated.
  1168. */
  1169. private static int[] leftShift(int[] a, int len, int n) {
  1170. int nInts = n >>> 5;
  1171. int nBits = n&0x1F;
  1172. int bitsInHighWord = bitLen(a[0]);
  1173. // If shift can be done without recopy, do so
  1174. if (n <= (32-bitsInHighWord)) {
  1175. primitiveLeftShift(a, len, nBits);
  1176. return a;
  1177. } else { // Array must be resized
  1178. if (nBits <= (32-bitsInHighWord)) {
  1179. int result[] = new int[nInts+len];
  1180. for (int i=0; i<len; i++)
  1181. result[i] = a[i];
  1182. primitiveLeftShift(result, result.length, nBits);
  1183. return result;
  1184. } else {
  1185. int result[] = new int[nInts+len+1];
  1186. for (int i=0; i<len; i++)
  1187. result[i] = a[i];
  1188. primitiveRightShift(result, result.length, 32 - nBits);
  1189. return result;
  1190. }
  1191. }
  1192. }
  1193. // shifts a up to len right n bits assumes no leading zeros, 0<n<32
  1194. static void primitiveRightShift(int[] a, int len, int n) {
  1195. int n2 = 32 - n;
  1196. for (int i=len-1, c=a[i]; i>0; i--) {
  1197. int b = c;
  1198. c = a[i-1];
  1199. a[i] = (c << n2) | (b >>> n);
  1200. }
  1201. a[0] >>>= n;
  1202. }
  1203. // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
  1204. static void primitiveLeftShift(int[] a, int len, int n) {
  1205. if (len == 0 || n == 0)
  1206. return;
  1207. int n2 = 32 - n;
  1208. for (int i=0, c=a[i], m=i+len-1; i<m; i++) {
  1209. int b = c;
  1210. c = a[i+1];
  1211. a[i] = (b << n) | (c >>> n2);
  1212. }
  1213. a[len-1] <<= n;
  1214. }
  1215. /**
  1216. * Calculate bitlength of contents of the first len elements an int array,
  1217. * assuming there are no leading zero ints.
  1218. */
  1219. private static int bitLength(int[] val, int len) {
  1220. if (len==0)
  1221. return 0;
  1222. return ((len-1)<<5) + bitLen(val[0]);
  1223. }
  1224. /**
  1225. * Returns a BigInteger whose value is the absolute value of this
  1226. * BigInteger.
  1227. *
  1228. * @return <tt>abs(this)</tt>
  1229. */
  1230. public BigInteger abs() {
  1231. return (signum >= 0 ? this : this.negate());
  1232. }
  1233. /**
  1234. * Returns a BigInteger whose value is <tt>(-this)</tt>.
  1235. *
  1236. * @return <tt>-this</tt>
  1237. */
  1238. public BigInteger negate() {
  1239. return new BigInteger(this.mag, -this.signum);
  1240. }
  1241. /**
  1242. * Returns the signum function of this BigInteger.
  1243. *
  1244. * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or
  1245. * positive.
  1246. */
  1247. public int signum() {
  1248. return this.signum;
  1249. }
  1250. // Modular Arithmetic Operations
  1251. /**
  1252. * Returns a BigInteger whose value is <tt>(this mod m</tt>). This method
  1253. * differs from <tt>remainder</tt> in that it always returns a
  1254. * <i>non-negative</i> BigInteger.
  1255. *
  1256. * @param m the modulus.
  1257. * @return <tt>this mod m</tt>
  1258. * @throws ArithmeticException <tt>m <= 0</tt>
  1259. * @see #remainder
  1260. */
  1261. public BigInteger mod(BigInteger m) {
  1262. if (m.signum <= 0)
  1263. throw new ArithmeticException("BigInteger: modulus not positive");
  1264. BigInteger result = this.remainder(m);
  1265. return (result.signum >= 0 ? result : result.add(m));
  1266. }
  1267. /**
  1268. * Returns a BigInteger whose value is
  1269. * <tt>(this<sup>exponent</sup> mod m)</tt>. (Unlike <tt>pow</tt>, this
  1270. * method permits negative exponents.)
  1271. *
  1272. * @param exponent the exponent.
  1273. * @param m the modulus.
  1274. * @return <tt>this<sup>exponent</sup> mod m</tt>
  1275. * @throws ArithmeticException <tt>m <= 0</tt>
  1276. * @see #modInverse
  1277. */
  1278. public BigInteger modPow(BigInteger exponent, BigInteger m) {
  1279. if (m.signum <= 0)
  1280. throw new ArithmeticException("BigInteger: modulus not positive");
  1281. // Trivial cases
  1282. if (exponent.signum == 0)
  1283. return (m.equals(ONE) ? ZERO : ONE);
  1284. if (this.equals(ONE))
  1285. return (m.equals(ONE) ? ZERO : ONE);
  1286. if (this.equals(ZERO) && exponent.signum >= 0)
  1287. return ZERO;
  1288. if (this.equals(negConst[1]) && (!exponent.testBit(0)))
  1289. return (m.equals(ONE) ? ZERO : ONE);
  1290. boolean invertResult;
  1291. if ((invertResult = (exponent.signum < 0)))
  1292. exponent = exponent.negate();
  1293. BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
  1294. ? this.mod(m) : this);
  1295. BigInteger result;
  1296. if (m.testBit(0)) { // odd modulus
  1297. result = base.oddModPow(exponent, m);
  1298. } else {
  1299. /*
  1300. * Even modulus. Tear it into an "odd part" (m1) and power of two
  1301. * (m2), exponentiate mod m1, manually exponentiate mod m2, and
  1302. * use Chinese Remainder Theorem to combine results.
  1303. */
  1304. // Tear m apart into odd part (m1) and power of 2 (m2)
  1305. int p = m.getLowestSetBit(); // Max pow of 2 that divides m
  1306. BigInteger m1 = m.shiftRight(p); // m/2**p
  1307. BigInteger m2 = ONE.shiftLeft(p); // 2**p
  1308. // Calculate new base from m1
  1309. BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0
  1310. ? this.mod(m1) : this);
  1311. // Caculate (base ** exponent) mod m1.
  1312. BigInteger a1 = (m1.equals(ONE) ? ZERO :
  1313. base2.oddModPow(exponent, m1));
  1314. // Calculate (this ** exponent) mod m2
  1315. BigInteger a2 = base.modPow2(exponent, p);
  1316. // Combine results using Chinese Remainder Theorem
  1317. BigInteger y1 = m2.modInverse(m1);
  1318. BigInteger y2 = m1.modInverse(m2);
  1319. result = a1.multiply(m2).multiply(y1).add
  1320. (a2.multiply(m1).multiply(y2)).mod(m);
  1321. }
  1322. return (invertResult ? result.modInverse(m) : result);
  1323. }
  1324. static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,
  1325. Integer.MAX_VALUE}; // Sentinel
  1326. /**
  1327. * Returns a BigInteger whose value is x to the power of y mod z.
  1328. * Assumes: z is odd && x < z.
  1329. */
  1330. private BigInteger oddModPow(BigInteger y, BigInteger z) {
  1331. /*
  1332. * The algorithm is adapted from Colin Plumb's C library.
  1333. *
  1334. * The window algorithm:
  1335. * The idea is to keep a running product of b1 = n^(high-order bits of exp)
  1336. * and then keep appending exponent bits to it. The following patterns
  1337. * apply to a 3-bit window (k = 3):
  1338. * To append 0: square
  1339. * To append 1: square, multiply by n^1
  1340. * To append 10: square, multiply by n^1, square
  1341. * To append 11: square, square, multiply by n^3
  1342. * To append 100: square, multiply by n^1, square, square
  1343. * To append 101: square, square, square, multiply by n^5
  1344. * To append 110: square, square, multiply by n^3, square
  1345. * To append 111: square, square, square, multiply by n^7
  1346. *
  1347. * Since each pattern involves only one multiply, the longer the pattern
  1348. * the better, except that a 0 (no multiplies) can be appended directly.
  1349. * We precompute a table of odd powers of n, up to 2^k, and can then
  1350. * multiply k bits of exponent at a time. Actually, assuming random
  1351. * exponents, there is on average one zero bit between needs to
  1352. * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
  1353. * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so
  1354. * you have to do one multiply per k+1 bits of exponent.
  1355. *
  1356. * The loop walks down the exponent, squaring the result buffer as
  1357. * it goes. There is a wbits+1 bit lookahead buffer, buf, that is
  1358. * filled with the upcoming exponent bits. (What is read after the
  1359. * end of the exponent is unimportant, but it is filled with zero here.)
  1360. * When the most-significant bit of this buffer becomes set, i.e.
  1361. * (buf & tblmask) != 0, we have to decide what pattern to multiply
  1362. * by, and when to do it. We decide, remember to do it in future
  1363. * after a suitable number of squarings have passed (e.g. a pattern
  1364. * of "100" in the buffer requires that we multiply by n^1 immediately;
  1365. * a pattern of "110" calls for multiplying by n^3 after one more
  1366. * squaring), clear the buffer, and continue.
  1367. *
  1368. * When we start, there is one more optimization: the result buffer
  1369. * is implcitly one, so squaring it or multiplying by it can be
  1370. * optimized away. Further, if we start with a pattern like "100"
  1371. * in the lookahead window, rather than placing n into the buffer
  1372. * and then starting to square it, we have already computed n^2
  1373. * to compute the odd-powers table, so we can place that into
  1374. * the buffer and save a squaring.
  1375. *
  1376. * This means that if you have a k-bit window, to compute n^z,
  1377. * where z is the high k bits of the exponent, 1/2 of the time
  1378. * it requires no squarings. 1/4 of the time, it requires 1
  1379. * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.
  1380. * And the remaining 1/2^(k-1) of the time, the top k bits are a
  1381. * 1 followed by k-1 0 bits, so it again only requires k-2
  1382. * squarings, not k-1. The average of these is 1. Add that
  1383. * to the one squaring we have to do to compute the table,
  1384. * and you'll see that a k-bit window saves k-2 squarings
  1385. * as well as reducing the multiplies. (It actually doesn't
  1386. * hurt in the case k = 1, either.)
  1387. */
  1388. // Special case for exponent of one
  1389. if (y.equals(ONE))
  1390. return this;
  1391. // Special case for base of zero
  1392. if (signum==0)
  1393. return ZERO;
  1394. int[] base = (int[])mag.clone();
  1395. int[] exp = y.mag;
  1396. int[] mod = z.mag;
  1397. int modLen = mod.length;
  1398. // Select an appropriate window size
  1399. int wbits = 0;
  1400. int ebits = bitLength(exp, exp.length);
  1401. while (ebits > bnExpModThreshTable[wbits])
  1402. wbits++;
  1403. // Calculate appropriate table size
  1404. int tblmask = 1 << wbits;
  1405. // Allocate table for precomputed odd powers of base in Montgomery form
  1406. int[][] table = new int[tblmask][];
  1407. for (int i=0; i<tblmask; i++)
  1408. table[i] = new int[modLen];
  1409. // Compute the modular inverse
  1410. int inv = -MutableBigInteger.inverseMod32(mod[modLen-1]);
  1411. // Convert base to Montgomery form
  1412. int[] a = leftShift(base, base.length, modLen << 5);
  1413. MutableBigInteger q = new MutableBigInteger(),
  1414. r = new MutableBigInteger(),
  1415. a2 = new MutableBigInteger(a),
  1416. b2 = new MutableBigInteger(mod);
  1417. a2.divide(b2, q, r);
  1418. table[0] = r.toIntArray();
  1419. // Pad table[0] with leading zeros so its length is at least modLen
  1420. if (table[0].length < modLen) {
  1421. int offset = modLen - table[0].length;
  1422. int[] t2 = new int[modLen];
  1423. for (int i=0; i<table[0].length; i++)
  1424. t2[i+offset] = table[0][i];
  1425. table[0] = t2;
  1426. }
  1427. // Set b to the square of the base
  1428. int[] b = squareToLen(table[0], modLen, null);
  1429. b = montReduce(b, mod, modLen, inv);
  1430. // Set t to high half of b
  1431. int[] t = new int[modLen];
  1432. for(int i=0; i<modLen; i++)
  1433. t[i] = b[i];
  1434. // Fill in the table with odd powers of the base
  1435. for (int i=1; i<tblmask; i++) {
  1436. int[] prod = multiplyToLen(t, modLen, table[i-1], modLen, null);
  1437. table[i] = montReduce(prod, mod, modLen, inv);
  1438. }
  1439. // Pre load the window that slides over the exponent
  1440. int bitpos = 1 << ((ebits-1) & (32-1));
  1441. int buf = 0;
  1442. int elen = exp.length;
  1443. int eIndex = 0;
  1444. for (int i = 0; i <= wbits; i++) {
  1445. buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);
  1446. bitpos >>>= 1;
  1447. if (bitpos == 0) {
  1448. eIndex++;
  1449. bitpos = 1 << (32-1);
  1450. elen--;
  1451. }
  1452. }
  1453. int multpos = ebits;
  1454. // The first iteration, which is hoisted out of the main loop
  1455. ebits--;
  1456. boolean isone = true;
  1457. multpos = ebits - wbits;
  1458. while ((buf & 1) == 0) {
  1459. buf >>>= 1;
  1460. multpos++;
  1461. }
  1462. int[] mult = table[buf >>> 1];
  1463. buf = 0;
  1464. if (multpos == ebits)
  1465. isone = false;
  1466. // The main loop
  1467. while(true) {
  1468. ebits--;
  1469. // Advance the window
  1470. buf <<= 1;
  1471. if (elen != 0) {
  1472. buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
  1473. bitpos >>>= 1;
  1474. if (bitpos == 0) {
  1475. eIndex++;
  1476. bitpos = 1 << (32-1);
  1477. elen--;
  1478. }
  1479. }
  1480. // Examine the window for pending multiplies
  1481. if ((buf & tblmask) != 0) {
  1482. multpos = ebits - wbits;
  1483. while ((buf & 1) == 0) {
  1484. buf >>>= 1;
  1485. multpos++;
  1486. }
  1487. mult = table[buf >>> 1];
  1488. buf = 0;
  1489. }
  1490. // Perform multiply
  1491. if (ebits == multpos) {
  1492. if (isone) {
  1493. b = (int[])mult.clone();
  1494. isone = false;
  1495. } else {
  1496. t = b;
  1497. a = multiplyToLen(t, modLen, mult, modLen, a);
  1498. a = montReduce(a, mod, modLen, inv);
  1499. t = a; a = b; b = t;
  1500. }
  1501. }
  1502. // Check if done
  1503. if (ebits == 0)
  1504. break;
  1505. // Square the input
  1506. if (!isone) {
  1507. t = b;
  1508. a = squareToLen(t, modLen, a);
  1509. a = montReduce(a, mod, modLen, inv);
  1510. t = a; a = b; b = t;
  1511. }
  1512. }
  1513. // Convert result out of Montgomery form and return
  1514. int[] t2 = new int[2*modLen];
  1515. for(int i=0; i<modLen; i++)
  1516. t2[i+modLen] = b[i];
  1517. b = montReduce(t2, mod, modLen, inv);
  1518. t2 = new int[modLen];
  1519. for(int i=0; i<modLen; i++)
  1520. t2[i] = b[i];
  1521. return new BigInteger(1, t2);
  1522. }
  1523. /**
  1524. * Montgomery reduce n, modulo mod. This reduces modulo mod and divides
  1525. * by 2^(32*mlen). Adapted from Colin Plumb's C library.
  1526. */
  1527. private static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {
  1528. int c=0;
  1529. int len = mlen;
  1530. int offset=0;
  1531. do {
  1532. int nEnd = n[n.length-1-offset];
  1533. int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
  1534. c += addOne(n, offset, mlen, carry);
  1535. offset++;
  1536. } while(--len > 0);
  1537. while(c>0)
  1538. c += subN(n, mod, mlen);
  1539. while (intArrayCmpToLen(n, mod, mlen) >= 0)
  1540. subN(n, mod, mlen);
  1541. return n;
  1542. }
  1543. /*
  1544. * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,
  1545. * equal to, or greater than arg2 up to length len.
  1546. */
  1547. private static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
  1548. for (int i=0; i<len; i++) {
  1549. long b1 = arg1[i] & LONG_MASK;
  1550. long b2 = arg2[i] & LONG_MASK;
  1551. if (b1 < b2)
  1552. return -1;
  1553. if (b1 > b2)
  1554. return 1;
  1555. }
  1556. return 0;
  1557. }
  1558. /**
  1559. * Subtracts two numbers of same length, returning borrow.
  1560. */
  1561. private static int subN(int[] a, int[] b, int len) {
  1562. long sum = 0;
  1563. while(--len >= 0) {
  1564. sum = (a[len] & LONG_MASK) -
  1565. (b[len] & LONG_MASK) + (sum >> 32);
  1566. a[len] = (int)sum;
  1567. }
  1568. return (int)(sum >> 32);
  1569. }
  1570. /**
  1571. * Multiply an array by one word k and add to result, return the carry
  1572. */
  1573. static int mulAdd(int[] out, int[] in, int offset, int len, int k) {
  1574. long kLong = k & LONG_MASK;
  1575. long carry = 0;
  1576. offset = out.length-offset - 1;
  1577. for (int j=len-1; j >= 0; j--) {
  1578. long product = (in[j] & LONG_MASK) * kLong +
  1579. (out[offset] & LONG_MASK) + carry;
  1580. out[offset--] = (int)product;
  1581. carry = product >>> 32;
  1582. }
  1583. return (int)carry;
  1584. }
  1585. /**
  1586. * Add one word to the number a mlen words into a. Return the resulting
  1587. * carry.
  1588. */
  1589. static int addOne(int[] a, int offset, int mlen, int carry) {
  1590. offset = a.length-1-mlen-offset;
  1591. long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);
  1592. a[offset] = (int)t;
  1593. if ((t >>> 32) == 0)
  1594. return 0;
  1595. while (--mlen >= 0) {
  1596. if (--offset < 0) { // Carry out of number
  1597. return 1;
  1598. } else {
  1599. a[offset]++;
  1600. if (a[offset] != 0)
  1601. return 0;
  1602. }
  1603. }
  1604. return 1;
  1605. }
  1606. /**
  1607. * Returns a BigInteger whose value is (this ** exponent) mod (2**p)
  1608. */
  1609. private BigInteger modPow2(BigInteger exponent, int p) {
  1610. /*
  1611. * Perform exponentiation using repeated squaring trick, chopping off
  1612. * high order bits as indicated by modulus.
  1613. */
  1614. BigInteger result = valueOf(1);
  1615. BigInteger baseToPow2 = this.mod2(p);
  1616. int expOffset = 0;
  1617. int limit = exponent.bitLength();
  1618. if (this.testBit(0))
  1619. limit = (p-1) < limit ? (p-1) : limit;
  1620. while (expOffset < limit) {
  1621. if (exponent.testBit(expOffset))
  1622. result = result.multiply(baseToPow2).mod2(p);
  1623. expOffset++;
  1624. if (expOffset < limit)
  1625. baseToPow2 = baseToPow2.square().mod2(p);
  1626. }
  1627. return result;
  1628. }
  1629. /**
  1630. * Returns a BigInteger whose value is this mod(2**p).
  1631. * Assumes that this BigInteger >= 0 and p > 0.
  1632. */
  1633. private BigInteger mod2(int p) {
  1634. if (bitLength() <= p)
  1635. return this;
  1636. // Copy remaining ints of mag
  1637. int numInts = (p+31)/32;
  1638. int[] mag = new int[numInts];
  1639. for (int i=0; i<numInts; i++)
  1640. mag[i] = this.mag[i + (this.mag.length - numInts)];
  1641. // Mask out any excess bits
  1642. int excessBits = (numInts << 5) - p;
  1643. mag[0] &= (1L << (32-excessBits)) - 1;
  1644. return (mag[0]==0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
  1645. }
  1646. /**
  1647. * Returns a BigInteger whose value is <tt>(this<sup>-1</sup> mod m)</tt>.
  1648. *
  1649. * @param m the modulus.
  1650. * @return <tt>this<sup>-1</sup> mod m</tt>.
  1651. * @throws ArithmeticException <tt> m <= 0</tt>, or this BigInteger
  1652. * has no multiplicative inverse mod m (that is, this BigInteger
  1653. * is not <i>relatively prime</i> to m).
  1654. */
  1655. public BigInteger modInverse(BigInteger m) {
  1656. if (m.signum != 1)
  1657. throw new ArithmeticException("BigInteger: modulus not positive");
  1658. if (m.equals(ONE))
  1659. return ZERO;
  1660. // Calculate (this mod m)
  1661. BigInteger modVal = this;
  1662. if (signum < 0 || (intArrayCmp(mag, m.mag) >= 0))
  1663. modVal = this.mod(m);
  1664. if (modVal.equals(ONE))
  1665. return ONE;
  1666. MutableBigInteger a = new MutableBigInteger(modVal);
  1667. MutableBigInteger b = new MutableBigInteger(m);
  1668. MutableBigInteger result = a.mutableModInverse(b);
  1669. return new BigInteger(result, 1);
  1670. }
  1671. // Shift Operations
  1672. /**
  1673. * Returns a BigInteger whose value is <tt>(this << n)</tt>.
  1674. * The shift distance, <tt>n</tt>, may be negative, in which case
  1675. * this method performs a right shift.
  1676. * (Computes <tt>floor(this * 2<sup>n</sup>)</tt>.)
  1677. *
  1678. * @param n shift distance, in bits.
  1679. * @return <tt>this << n</tt>
  1680. * @see #shiftRight
  1681. */
  1682. public BigInteger shiftLeft(int n) {
  1683. if (signum == 0)
  1684. return ZERO;
  1685. if (n==0)
  1686. return this;
  1687. if (n<0)
  1688. return shiftRight(-n);
  1689. int nInts = n >>> 5;
  1690. int nBits = n & 0x1f;
  1691. int magLen = mag.length;
  1692. int newMag[] = null;
  1693. if (nBits == 0) {
  1694. newMag = new int[magLen + nInts];
  1695. for (int i=0; i<magLen; i++)
  1696. newMag[i] = mag[i];
  1697. } else {
  1698. int i = 0;
  1699. int nBits2 = 32 - nBits;
  1700. int highBits = mag[0] >>> nBits2;
  1701. if (highBits != 0) {
  1702. newMag = new int[magLen + nInts + 1];
  1703. newMag[i++] = highBits;
  1704. } else {
  1705. newMag = new int[magLen + nInts];
  1706. }
  1707. int j=0;
  1708. while (j < magLen-1)
  1709. newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2;
  1710. newMag[i] = mag[j] << nBits;
  1711. }
  1712. return new BigInteger(newMag, signum);
  1713. }
  1714. /**
  1715. * Returns a BigInteger whose value is <tt>(this >> n)</tt>. Sign
  1716. * extension is performed. The shift distance, <tt>n</tt>, may be
  1717. * negative, in which case this method performs a left shift.
  1718. * (Computes <tt>floor(this / 2<sup>n</sup>)</tt>.)
  1719. *
  1720. * @param n shift distance, in bits.
  1721. * @return <tt>this >> n</tt>
  1722. * @see #shiftLeft
  1723. */
  1724. public BigInteger shiftRight(int n) {
  1725. if (n==0)
  1726. return this;
  1727. if (n<0)
  1728. return shiftLeft(-n);
  1729. int nInts = n >>> 5;
  1730. int nBits = n & 0x1f;
  1731. int magLen = mag.length;
  1732. int newMag[] = null;
  1733. // Special case: entire contents shifted off the end
  1734. if (nInts >= magLen)
  1735. return (signum >= 0 ? ZERO : negConst[1]);
  1736. if (nBits == 0) {
  1737. int newMagLen = magLen - nInts;
  1738. newMag = new int[newMagLen];
  1739. for (int i=0; i<newMagLen; i++)
  1740. newMag[i] = mag[i];
  1741. } else {
  1742. int i = 0;
  1743. int highBits = mag[0] >>> nBits;
  1744. if (highBits != 0) {
  1745. newMag = new int[magLen - nInts];
  1746. newMag[i++] = highBits;
  1747. } else {
  1748. newMag = new int[magLen - nInts -1];
  1749. }
  1750. int nBits2 = 32 - nBits;
  1751. int j=0;
  1752. while (j < magLen - nInts - 1)
  1753. newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits);
  1754. }
  1755. if (signum < 0) {
  1756. // Find out whether any one-bits were shifted off the end.
  1757. boolean onesLost = false;
  1758. for (int i=magLen-1, j=magLen-nInts; i>=j && !onesLost; i--)
  1759. onesLost = (mag[i] != 0);
  1760. if (!onesLost && nBits != 0)
  1761. onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
  1762. if (onesLost)
  1763. newMag = javaIncrement(newMag);
  1764. }
  1765. return new BigInteger(newMag, signum);
  1766. }
  1767. int[] javaIncrement(int[] val) {
  1768. boolean done = false;
  1769. int lastSum = 0;
  1770. for (int i=val.length-1; i >= 0 && lastSum == 0; i--)
  1771. lastSum = (val[i] += 1);
  1772. if (lastSum == 0) {
  1773. val = new int[val.length+1];
  1774. val[0] = 1;
  1775. }
  1776. return val;
  1777. }
  1778. // Bitwise Operations
  1779. /**
  1780. * Returns a BigInteger whose value is <tt>(this & val)</tt>. (This
  1781. * method returns a negative BigInteger if and only if this and val are
  1782. * both negative.)
  1783. *
  1784. * @param val value to be AND'ed with this BigInteger.
  1785. * @return <tt>this & val</tt>
  1786. */
  1787. public BigInteger and(BigInteger val) {
  1788. int[] result = new int[Math.max(intLength(), val.intLength())];
  1789. for (int i=0; i<result.length; i++)
  1790. result[i] = (int) (getInt(result.length-i-1)
  1791. & val.getInt(result.length-i-1));
  1792. return valueOf(result);
  1793. }
  1794. /**
  1795. * Returns a BigInteger whose value is <tt>(this | val)</tt>. (This method
  1796. * returns a negative BigInteger if and only if either this or val is
  1797. * negative.)
  1798. *
  1799. * @param val value to be OR'ed with this BigInteger.
  1800. * @return <tt>this | val</tt>
  1801. */
  1802. public BigInteger or(BigInteger val) {
  1803. int[] result = new int[Math.max(intLength(), val.intLength())];
  1804. for (int i=0; i<result.length; i++)
  1805. result[i] = (int) (getInt(result.length-i-1)
  1806. | val.getInt(result.length-i-1));
  1807. return valueOf(result);
  1808. }
  1809. /**
  1810. * Returns a BigInteger whose value is <tt>(this ^ val)</tt>. (This method
  1811. * returns a negative BigInteger if and only if exactly one of this and
  1812. * val are negative.)
  1813. *
  1814. * @param val value to be XOR'ed with this BigInteger.
  1815. * @return <tt>this ^ val</tt>
  1816. */
  1817. public BigInteger xor(BigInteger val) {
  1818. int[] result = new int[Math.max(intLength(), val.intLength())];
  1819. for (int i=0; i<result.length; i++)
  1820. result[i] = (int) (getInt(result.length-i-1)
  1821. ^ val.getInt(result.length-i-1));
  1822. return valueOf(result);
  1823. }
  1824. /**
  1825. * Returns a BigInteger whose value is <tt>(~this)</tt>. (This method
  1826. * returns a negative value if and only if this BigInteger is
  1827. * non-negative.)
  1828. *
  1829. * @return <tt>~this</tt>
  1830. */
  1831. public BigInteger not() {
  1832. int[] result = new int[intLength()];
  1833. for (int i=0; i<result.length; i++)
  1834. result[i] = (int) ~getInt(result.length-i-1);
  1835. return valueOf(result);
  1836. }
  1837. /**
  1838. * Returns a BigInteger whose value is <tt>(this & ~val)</tt>. This
  1839. * method, which is equivalent to <tt>and(val.not())</tt>, is provided as
  1840. * a convenience for masking operations. (This method returns a negative
  1841. * BigInteger if and only if <tt>this</tt> is negative and <tt>val</tt> is
  1842. * positive.)
  1843. *
  1844. * @param val value to be complemented and AND'ed with this BigInteger.
  1845. * @return <tt>this & ~val</tt>
  1846. */
  1847. public BigInteger andNot(BigInteger val) {
  1848. int[] result = new int[Math.max(intLength(), val.intLength())];
  1849. for (int i=0; i<result.length; i++)
  1850. result[i] = (int) (getInt(result.length-i-1)
  1851. & ~val.getInt(result.length-i-1));
  1852. return valueOf(result);
  1853. }
  1854. // Single Bit Operations
  1855. /**
  1856. * Returns <tt>true</tt> if and only if the designated bit is set.
  1857. * (Computes <tt>((this & (1<<n)) != 0)</tt>.)
  1858. *
  1859. * @param n index of bit to test.
  1860. * @return <tt>true</tt> if and only if the designated bit is set.
  1861. * @throws ArithmeticException <tt>n</tt> is negative.
  1862. */
  1863. public boolean testBit(int n) {
  1864. if (n<0)
  1865. throw new ArithmeticException("Negative bit address");
  1866. return (getInt(n32) & (1 << (n%32))) != 0;
  1867. }
  1868. /**
  1869. * Returns a BigInteger whose value is equivalent to this BigInteger
  1870. * with the designated bit set. (Computes <tt>(this | (1<<n))</tt>.)
  1871. *
  1872. * @param n index of bit to set.
  1873. * @return <tt>this | (1<<n)</tt>
  1874. * @throws ArithmeticException <tt>n</tt> is negative.
  1875. */
  1876. public BigInteger setBit(int n) {
  1877. if (n<0)
  1878. throw new ArithmeticException("Negative bit address");
  1879. int intNum = n32;
  1880. int[] result = new int[Math.max(intLength(), intNum+2)];
  1881. for (int i=0; i<result.length; i++)
  1882. result[result.length-i-1] = getInt(i);
  1883. result[result.length-intNum-1] |= (1 << (n%32));
  1884. return valueOf(result);
  1885. }
  1886. /**
  1887. * Returns a BigInteger whose value is equivalent to this BigInteger
  1888. * with the designated bit cleared.
  1889. * (Computes <tt>(this & ~(1<<n))</tt>.)
  1890. *
  1891. * @param n index of bit to clear.
  1892. * @return <tt>this & ~(1<<n)</tt>
  1893. * @throws ArithmeticException <tt>n</tt> is negative.
  1894. */
  1895. public BigInteger clearBit(int n) {
  1896. if (n<0)
  1897. throw new ArithmeticException("Negative bit address");
  1898. int intNum = n32;
  1899. int[] result = new int[Math.max(intLength(), (n+1)/32+1)];
  1900. for (int i=0; i<result.length; i++)
  1901. result[result.length-i-1] = getInt(i);
  1902. result[result.length-intNum-1] &= ~(1 << (n%32));
  1903. return valueOf(result);
  1904. }
  1905. /**
  1906. * Returns a BigInteger whose value is equivalent to this BigInteger
  1907. * with the designated bit flipped.
  1908. * (Computes <tt>(this ^ (1<<n))</tt>.)
  1909. *
  1910. * @param n index of bit to flip.
  1911. * @return <tt>this ^ (1<<n)</tt>
  1912. * @throws ArithmeticException <tt>n</tt> is negative.
  1913. */
  1914. public BigInteger flipBit(int n) {
  1915. if (n<0)
  1916. throw new ArithmeticException("Negative bit address");
  1917. int intNum = n32;
  1918. int[] result = new int[Math.max(intLength(), intNum+2)];
  1919. for (int i=0; i<result.length; i++)
  1920. result[result.length-i-1] = getInt(i);
  1921. result[result.length-intNum-1] ^= (1 << (n%32));
  1922. return valueOf(result);
  1923. }
  1924. /**
  1925. * Returns the index of the rightmost (lowest-order) one bit in this
  1926. * BigInteger (the number of zero bits to the right of the rightmost
  1927. * one bit). Returns -1 if this BigInteger contains no one bits.
  1928. * (Computes <tt>(this==0? -1 : log<sub>2</sub>(this & -this))</tt>.)
  1929. *
  1930. * @return index of the rightmost one bit in this BigInteger.
  1931. */
  1932. public int getLowestSetBit() {
  1933. /*
  1934. * Initialize lowestSetBit field the first time this method is
  1935. * executed. This method depends on the atomicity of int modifies;
  1936. * without this guarantee, it would have to be synchronized.
  1937. */
  1938. if (lowestSetBit == -2) {
  1939. if (signum == 0) {
  1940. lowestSetBit = -1;
  1941. } else {
  1942. // Search for lowest order nonzero int
  1943. int i,b;
  1944. for (i=0; (b = getInt(i))==0; i++)
  1945. ;
  1946. lowestSetBit = (i << 5) + trailingZeroCnt(b);
  1947. }
  1948. }
  1949. return lowestSetBit;
  1950. }
  1951. // Miscellaneous Bit Operations
  1952. /**
  1953. * Returns the number of bits in the minimal two's-complement
  1954. * representation of this BigInteger, <i>excluding</i> a sign bit.
  1955. * For positive BigIntegers, this is equivalent to the number of bits in
  1956. * the ordinary binary representation. (Computes
  1957. * <tt>(ceil(log<sub>2</sub>(this < 0 ? -this : this+1)))</tt>.)
  1958. *
  1959. * @return number of bits in the minimal two's-complement
  1960. * representation of this BigInteger, <i>excluding</i> a sign bit.
  1961. */
  1962. public int bitLength() {
  1963. /*
  1964. * Initialize bitLength field the first time this method is executed.
  1965. * This method depends on the atomicity of int modifies; without
  1966. * this guarantee, it would have to be synchronized.
  1967. */
  1968. if (bitLength == -1) {
  1969. if (signum == 0) {
  1970. bitLength = 0;
  1971. } else {
  1972. // Calculate the bit length of the magnitude
  1973. int magBitLength = ((mag.length-1) << 5) + bitLen(mag[0]);
  1974. if (signum < 0) {
  1975. // Check if magnitude is a power of two
  1976. boolean pow2 = (bitCnt(mag[0]) == 1);
  1977. for(int i=1; i<mag.length && pow2; i++)
  1978. pow2 = (mag[i]==0);
  1979. bitLength = (pow2 ? magBitLength-1 : magBitLength);
  1980. } else {
  1981. bitLength = magBitLength;
  1982. }
  1983. }
  1984. }
  1985. return bitLength;
  1986. }
  1987. /**
  1988. * bitLen(val) is the number of bits in val.
  1989. */
  1990. static int bitLen(int w) {
  1991. // Binary search - decision tree (5 tests, rarely 6)
  1992. return
  1993. (w < 1<<15 ?
  1994. (w < 1<<7 ?
  1995. (w < 1<<3 ?
  1996. (w < 1<<1 ? (w < 1<<0 ? (w<0 ? 32 : 0) : 1) : (w < 1<<2 ? 2 : 3)) :
  1997. (w < 1<<5 ? (w < 1<<4 ? 4 : 5) : (w < 1<<6 ? 6 : 7))) :
  1998. (w < 1<<11 ?
  1999. (w < 1<<9 ? (w < 1<<8 ? 8 : 9) : (w < 1<<10 ? 10 : 11)) :
  2000. (w < 1<<13 ? (w < 1<<12 ? 12 : 13) : (w < 1<<14 ? 14 : 15)))) :
  2001. (w < 1<<23 ?
  2002. (w < 1<<19 ?
  2003. (w < 1<<17 ? (w < 1<<16 ? 16 : 17) : (w < 1<<18 ? 18 : 19)) :
  2004. (w < 1<<21 ? (w < 1<<20 ? 20 : 21) : (w < 1<<22 ? 22 : 23))) :
  2005. (w < 1<<27 ?
  2006. (w < 1<<25 ? (w < 1<<24 ? 24 : 25) : (w < 1<<26 ? 26 : 27)) :
  2007. (w < 1<<29 ? (w < 1<<28 ? 28 : 29) : (w < 1<<30 ? 30 : 31)))));
  2008. }
  2009. /*
  2010. * trailingZeroTable[i] is the number of trailing zero bits in the binary
  2011. * representaion of i.
  2012. */
  2013. final static byte trailingZeroTable[] = {
  2014. -25, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2015. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2016. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2017. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2018. 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2019. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2020. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2021. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2022. 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2023. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2024. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2025. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2026. 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2027. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2028. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  2029. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
  2030. /**
  2031. * Returns the number of bits in the two's complement representation
  2032. * of this BigInteger that differ from its sign bit. This method is
  2033. * useful when implementing bit-vector style sets atop BigIntegers.
  2034. *
  2035. * @return number of bits in the two's complement representation
  2036. * of this BigInteger that differ from its sign bit.
  2037. */
  2038. public int bitCount() {
  2039. /*
  2040. * Initialize bitCount field the first time this method is executed.
  2041. * This method depends on the atomicity of int modifies; without
  2042. * this guarantee, it would have to be synchronized.
  2043. */
  2044. if (bitCount == -1) {
  2045. // Count the bits in the magnitude
  2046. int magBitCount = 0;
  2047. for (int i=0; i<mag.length; i++)
  2048. magBitCount += bitCnt(mag[i]);
  2049. if (signum < 0) {
  2050. // Count the trailing zeros in the magnitude
  2051. int magTrailingZeroCount = 0, j;
  2052. for (j=mag.length-1; mag[j]==0; j--)
  2053. magTrailingZeroCount += 32;
  2054. magTrailingZeroCount +=
  2055. trailingZeroCnt(mag[j]);
  2056. bitCount = magBitCount + magTrailingZeroCount - 1;
  2057. } else {
  2058. bitCount = magBitCount;
  2059. }
  2060. }
  2061. return bitCount;
  2062. }
  2063. static int bitCnt(int val) {
  2064. val -= (0xaaaaaaaa & val) >>> 1;
  2065. val = (val & 0x33333333) + ((val >>> 2) & 0x33333333);
  2066. val = val + (val >>> 4) & 0x0f0f0f0f;
  2067. val += val >>> 8;
  2068. val += val >>> 16;
  2069. return val & 0xff;
  2070. }
  2071. static int trailingZeroCnt(int val) {
  2072. // Loop unrolled for performance
  2073. int byteVal = val & 0xff;
  2074. if (byteVal != 0)
  2075. return trailingZeroTable[byteVal];
  2076. byteVal = (val >>> 8) & 0xff;
  2077. if (byteVal != 0)
  2078. return trailingZeroTable[byteVal] + 8;
  2079. byteVal = (val >>> 16) & 0xff;
  2080. if (byteVal != 0)
  2081. return trailingZeroTable[byteVal] + 16;
  2082. byteVal = (val >>> 24) & 0xff;
  2083. return trailingZeroTable[byteVal] + 24;
  2084. }
  2085. // Primality Testing
  2086. /**
  2087. * Returns <tt>true</tt> if this BigInteger is probably prime,
  2088. * <tt>false</tt> if it's definitely composite. If
  2089. * <tt>certainty</tt> is <tt> <= 0</tt>, <tt>true</tt> is
  2090. * returned.
  2091. *
  2092. * @param certainty a measure of the uncertainty that the caller is
  2093. * willing to tolerate: if the call returns <tt>true</tt>
  2094. * the probability that this BigInteger is prime exceeds
  2095. * <tt>(1 - 1/2<sup>certainty</sup>)</tt>. The execution time of
  2096. * this method is proportional to the value of this parameter.
  2097. * @return <tt>true</tt> if this BigInteger is probably prime,
  2098. * <tt>false</tt> if it's definitely composite.
  2099. */
  2100. public boolean isProbablePrime(int certainty) {
  2101. if (certainty <= 0)
  2102. return true;
  2103. BigInteger w = this.abs();
  2104. if (w.equals(TWO))
  2105. return true;
  2106. if (!w.testBit(0) || w.equals(ONE))
  2107. return false;
  2108. return w.primeToCertainty(certainty);
  2109. }
  2110. // Comparison Operations
  2111. /**
  2112. * Compares this BigInteger with the specified BigInteger. This method is
  2113. * provided in preference to individual methods for each of the six
  2114. * boolean comparison operators (<, ==, >, >=, !=, <=). The
  2115. * suggested idiom for performing these comparisons is:
  2116. * <tt>(x.compareTo(y)</tt> <<i>op</i>> <tt>0)</tt>,
  2117. * where <<i>op</i>> is one of the six comparison operators.
  2118. *
  2119. * @param val BigInteger to which this BigInteger is to be compared.
  2120. * @return -1, 0 or 1 as this BigInteger is numerically less than, equal
  2121. * to, or greater than <tt>val</tt>.
  2122. */
  2123. public int compareTo(BigInteger val) {
  2124. return (signum==val.signum
  2125. ? signum*intArrayCmp(mag, val.mag)
  2126. : (signum>val.signum ? 1 : -1));
  2127. }
  2128. /**
  2129. * Compares this BigInteger with the specified Object. If the Object is a
  2130. * BigInteger, this method behaves like <tt>compareTo(BigInteger)</tt>.
  2131. * Otherwise, it throws a <tt>ClassCastException</tt> (as BigIntegers are
  2132. * comparable only to other BigIntegers).
  2133. *
  2134. * @param o Object to which this BigInteger is to be compared.
  2135. * @return a negative number, zero, or a positive number as this
  2136. * BigInteger is numerically less than, equal to, or greater
  2137. * than <tt>o</tt>, which must be a BigInteger.
  2138. * @throws ClassCastException <tt>o</tt> is not a BigInteger.
  2139. * @see #compareTo(java.math.BigInteger)
  2140. * @see Comparable
  2141. * @since 1.2
  2142. */
  2143. public int compareTo(Object o) {
  2144. return compareTo((BigInteger)o);
  2145. }
  2146. /*
  2147. * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is
  2148. * less than, equal to, or greater than arg2.
  2149. */
  2150. private static int intArrayCmp(int[] arg1, int[] arg2) {
  2151. if (arg1.length < arg2.length)
  2152. return -1;
  2153. if (arg1.length > arg2.length)
  2154. return 1;
  2155. // Argument lengths are equal; compare the values
  2156. for (int i=0; i<arg1.length; i++) {
  2157. long b1 = arg1[i] & LONG_MASK;
  2158. long b2 = arg2[i] & LONG_MASK;
  2159. if (b1 < b2)
  2160. return -1;
  2161. if (b1 > b2)
  2162. return 1;
  2163. }
  2164. return 0;
  2165. }
  2166. /**
  2167. * Compares this BigInteger with the specified Object for equality.
  2168. *
  2169. * @param x Object to which this BigInteger is to be compared.
  2170. * @return <tt>true</tt> if and only if the specified Object is a
  2171. * BigInteger whose value is numerically equal to this BigInteger.
  2172. */
  2173. public boolean equals(Object x) {
  2174. // This test is just an optimization, which may or may not help
  2175. if (x == this)
  2176. return true;
  2177. if (!(x instanceof BigInteger))
  2178. return false;
  2179. BigInteger xInt = (BigInteger) x;
  2180. if (xInt.signum != signum || xInt.mag.length != mag.length)
  2181. return false;
  2182. for (int i=0; i<mag.length; i++)
  2183. if (xInt.mag[i] != mag[i])
  2184. return false;
  2185. return true;
  2186. }
  2187. /**
  2188. * Returns the minimum of this BigInteger and <tt>val</tt>.
  2189. *
  2190. * @param val value with with the minimum is to be computed.
  2191. * @return the BigInteger whose value is the lesser of this BigInteger and
  2192. * <tt>val</tt>. If they are equal, either may be returned.
  2193. */
  2194. public BigInteger min(BigInteger val) {
  2195. return (compareTo(val)<0 ? this : val);
  2196. }
  2197. /**
  2198. * Returns the maximum of this BigInteger and <tt>val</tt>.
  2199. *
  2200. * @param val value with with the maximum is to be computed.
  2201. * @return the BigInteger whose value is the greater of this and
  2202. * <tt>val</tt>. If they are equal, either may be returned.
  2203. */
  2204. public BigInteger max(BigInteger val) {
  2205. return (compareTo(val)>0 ? this : val);
  2206. }
  2207. // Hash Function
  2208. /**
  2209. * Returns the hash code for this BigInteger.
  2210. *
  2211. * @return hash code for this BigInteger.
  2212. */
  2213. public int hashCode() {
  2214. int hashCode = 0;
  2215. for (int i=0; i<mag.length; i++)
  2216. hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));
  2217. return hashCode * signum;
  2218. }
  2219. /**
  2220. * Returns the String representation of this BigInteger in the
  2221. * given radix. If the radix is outside the range from {@link
  2222. * Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive,
  2223. * it will default to 10 (as is the case for
  2224. * <tt>Integer.toString</tt>). The digit-to-character mapping
  2225. * provided by <tt>Character.forDigit</tt> is used, and a minus
  2226. * sign is prepended if appropriate. (This representation is
  2227. * compatible with the {@link #BigInteger(String, int) (String,
  2228. * <code>int</code>)} constructor.)
  2229. *
  2230. * @param radix radix of the String representation.
  2231. * @return String representation of this BigInteger in the given radix.
  2232. * @see Integer#toString
  2233. * @see Character#forDigit
  2234. * @see #BigInteger(java.lang.String, int)
  2235. */
  2236. public String toString(int radix) {
  2237. if (signum == 0)
  2238. return "0";
  2239. if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  2240. radix = 10;
  2241. // Compute upper bound on number of digit groups and allocate space
  2242. int maxNumDigitGroups = (4*mag.length + 6)/7;
  2243. String digitGroup[] = new String[maxNumDigitGroups];
  2244. // Translate number to string, a digit group at a time
  2245. BigInteger tmp = this.abs();
  2246. int numGroups = 0;
  2247. while (tmp.signum != 0) {
  2248. BigInteger d = longRadix[radix];
  2249. MutableBigInteger q = new MutableBigInteger(),
  2250. r = new MutableBigInteger(),
  2251. a = new MutableBigInteger(tmp.mag),
  2252. b = new MutableBigInteger(d.mag);
  2253. a.divide(b, q, r);
  2254. BigInteger q2 = new BigInteger(q, tmp.signum * d.signum);
  2255. BigInteger r2 = new BigInteger(r, tmp.signum * d.signum);
  2256. digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
  2257. tmp = q2;
  2258. }
  2259. // Put sign (if any) and first digit group into result buffer
  2260. StringBuffer buf = new StringBuffer(numGroups*digitsPerLong[radix]+1);
  2261. if (signum<0)
  2262. buf.append('-');
  2263. buf.append(digitGroup[numGroups-1]);
  2264. // Append remaining digit groups padded with leading zeros
  2265. for (int i=numGroups-2; i>=0; i--) {
  2266. // Prepend (any) leading zeros for this digit group
  2267. int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
  2268. if (numLeadingZeros != 0)
  2269. buf.append(zeros[numLeadingZeros]);
  2270. buf.append(digitGroup[i]);
  2271. }
  2272. return buf.toString();
  2273. }
  2274. /* zero[i] is a string of i consecutive zeros. */
  2275. private static String zeros[] = new String[64];
  2276. static {
  2277. zeros[63] =
  2278. "000000000000000000000000000000000000000000000000000000000000000";
  2279. for (int i=0; i<63; i++)
  2280. zeros[i] = zeros[63].substring(0, i);
  2281. }
  2282. /**
  2283. * Returns the decimal String representation of this BigInteger.
  2284. * The digit-to-character mapping provided by
  2285. * <tt>Character.forDigit</tt> is used, and a minus sign is
  2286. * prepended if appropriate. (This representation is compatible
  2287. * with the {@link #BigInteger(String) (String)} constructor, and
  2288. * allows for String concatenation with Java's + operator.)
  2289. *
  2290. * @return decimal String representation of this BigInteger.
  2291. * @see Character#forDigit
  2292. * @see #BigInteger(java.lang.String)
  2293. */
  2294. public String toString() {
  2295. return toString(10);
  2296. }
  2297. /**
  2298. * Returns a byte array containing the two's-complement
  2299. * representation of this BigInteger. The byte array will be in
  2300. * <i>big-endian</i> byte-order: the most significant byte is in
  2301. * the zeroth element. The array will contain the minimum number
  2302. * of bytes required to represent this BigInteger, including at
  2303. * least one sign bit, which is <tt>(ceil((this.bitLength() +
  2304. * 1)/8))</tt>. (This representation is compatible with the
  2305. * {@link #BigInteger(byte[]) (byte[])} constructor.)
  2306. *
  2307. * @return a byte array containing the two's-complement representation of
  2308. * this BigInteger.
  2309. * @see #BigInteger(byte[])
  2310. */
  2311. public byte[] toByteArray() {
  2312. int byteLen = bitLength()/8 + 1;
  2313. byte[] byteArray = new byte[byteLen];
  2314. for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i>=0; i--) {
  2315. if (bytesCopied == 4) {
  2316. nextInt = getInt(intIndex++);
  2317. bytesCopied = 1;
  2318. } else {
  2319. nextInt >>>= 8;
  2320. bytesCopied++;
  2321. }
  2322. byteArray[i] = (byte)nextInt;
  2323. }
  2324. return byteArray;
  2325. }
  2326. /**
  2327. * Converts this BigInteger to an <code>int</code>. This
  2328. * conversion is analogous to a <a
  2329. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  2330. * primitive conversion</i></a> from <code>long</code> to
  2331. * <code>int</code> as defined in the <a
  2332. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  2333. * Specification</a>: if this BigInteger is too big to fit in an
  2334. * <code>int</code>, only the low-order 32 bits are returned.
  2335. * Note that this conversion can lose information about the
  2336. * overall magnitude of the BigInteger value as well as return a
  2337. * result with the opposite sign.
  2338. *
  2339. * @return this BigInteger converted to an <code>int</code>.
  2340. */
  2341. public int intValue() {
  2342. int result = 0;
  2343. result = getInt(0);
  2344. return result;
  2345. }
  2346. /**
  2347. * Converts this BigInteger to a <code>long</code>. This
  2348. * conversion is analogous to a <a
  2349. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  2350. * primitive conversion</i></a> from <code>long</code> to
  2351. * <code>int</code> as defined in the <a
  2352. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  2353. * Specification</a>: if this BigInteger is too big to fit in a
  2354. * <code>long</code>, only the low-order 64 bits are returned.
  2355. * Note that this conversion can lose information about the
  2356. * overall magnitude of the BigInteger value as well as return a
  2357. * result with the opposite sign.
  2358. *
  2359. * @return this BigInteger converted to a <code>long</code>.
  2360. */
  2361. public long longValue() {
  2362. long result = 0;
  2363. for (int i=1; i>=0; i--)
  2364. result = (result << 32) + (getInt(i) & LONG_MASK);
  2365. return result;
  2366. }
  2367. /**
  2368. * Converts this BigInteger to a <code>float</code>. This
  2369. * conversion is similar to the <a
  2370. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  2371. * primitive conversion</i></a> from <code>double</code> to
  2372. * <code>float</code> defined in the <a
  2373. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  2374. * Specification</a>: if this BigInteger has too great a magnitude
  2375. * to represent as a <code>float</code>, it will be converted to
  2376. * {@link Float#NEGATIVE_INFINITY} or {@link
  2377. * Float#POSITIVE_INFINITY} as appropriate. Note that even when
  2378. * the return value is finite, this conversion can lose
  2379. * information about the precision of the BigInteger value.
  2380. *
  2381. * @return this BigInteger converted to a <code>float</code>.
  2382. */
  2383. public float floatValue() {
  2384. // Somewhat inefficient, but guaranteed to work.
  2385. return Float.valueOf(this.toString()).floatValue();
  2386. }
  2387. /**
  2388. * Converts this BigInteger to a <code>double</code>. This
  2389. * conversion is similar to the <a
  2390. * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
  2391. * primitive conversion</i></a> from <code>double</code> to
  2392. * <code>float</code> defined in the <a
  2393. * href="http://java.sun.com/docs/books/jls/html/">Java Language
  2394. * Specification</a>: if this BigInteger has too great a magnitude
  2395. * to represent as a <code>double</code>, it will be converted to
  2396. * {@link Double#NEGATIVE_INFINITY} or {@link
  2397. * Double#POSITIVE_INFINITY} as appropriate. Note that even when
  2398. * the return value is finite, this conversion can lose
  2399. * information about the precision of the BigInteger value.
  2400. *
  2401. * @return this BigInteger converted to a <code>double</code>.
  2402. */
  2403. public double doubleValue() {
  2404. // Somewhat inefficient, but guaranteed to work.
  2405. return Double.valueOf(this.toString()).doubleValue();
  2406. }
  2407. /**
  2408. * Returns a copy of the input array stripped of any leading zero bytes.
  2409. */
  2410. private static int[] stripLeadingZeroInts(int val[]) {
  2411. int byteLength = val.length;
  2412. int keep;
  2413. // Find first nonzero byte
  2414. for (keep=0; keep<val.length && val[keep]==0; keep++)
  2415. ;
  2416. int result[] = new int[val.length - keep];
  2417. for(int i=0; i<val.length - keep; i++)
  2418. result[i] = val[keep+i];
  2419. return result;
  2420. }
  2421. /**
  2422. * Returns the input array stripped of any leading zero bytes.
  2423. * Since the source is trusted the copying may be skipped.
  2424. */
  2425. private static int[] trustedStripLeadingZeroInts(int val[]) {
  2426. int byteLength = val.length;
  2427. int keep;
  2428. // Find first nonzero byte
  2429. for (keep=0; keep<val.length && val[keep]==0; keep++)
  2430. ;
  2431. // Only perform copy if necessary
  2432. if (keep > 0) {
  2433. int result[] = new int[val.length - keep];
  2434. for(int i=0; i<val.length - keep; i++)
  2435. result[i] = val[keep+i];
  2436. return result;
  2437. }
  2438. return val;
  2439. }
  2440. /**
  2441. * Returns a copy of the input array stripped of any leading zero bytes.
  2442. */
  2443. private static int[] stripLeadingZeroBytes(byte a[]) {
  2444. int byteLength = a.length;
  2445. int keep;
  2446. // Find first nonzero byte
  2447. for (keep=0; keep<a.length && a[keep]==0; keep++)
  2448. ;
  2449. // Allocate new array and copy relevant part of input array
  2450. int intLength = ((byteLength - keep) + 3)/4;
  2451. int[] result = new int[intLength];
  2452. int b = byteLength - 1;
  2453. for (int i = intLength-1; i >= 0; i--) {
  2454. result[i] = a[b--] & 0xff;
  2455. int bytesRemaining = b - keep + 1;
  2456. int bytesToTransfer = Math.min(3, bytesRemaining);
  2457. for (int j=8; j <= 8*bytesToTransfer; j += 8)
  2458. result[i] |= ((a[b--] & 0xff) << j);
  2459. }
  2460. return result;
  2461. }
  2462. /**
  2463. * Takes an array a representing a negative 2's-complement number and
  2464. * returns the minimal (no leading zero bytes) unsigned whose value is -a.
  2465. */
  2466. private static int[] makePositive(byte a[]) {
  2467. int keep, k;
  2468. int byteLength = a.length;
  2469. // Find first non-sign (0xff) byte of input
  2470. for (keep=0; keep<byteLength && a[keep]==-1; keep++)
  2471. ;
  2472. /* Allocate output array. If all non-sign bytes are 0x00, we must
  2473. * allocate space for one extra output byte. */
  2474. for (k=keep; k<byteLength && a[k]==0; k++)
  2475. ;
  2476. int extraByte = (k==byteLength) ? 1 : 0;
  2477. int intLength = ((byteLength - keep + extraByte) + 3)/4;
  2478. int result[] = new int[intLength];
  2479. /* Copy one's complement of input into into output, leaving extra
  2480. * byte (if it exists) == 0x00 */
  2481. int b = byteLength - 1;
  2482. for (int i = intLength-1; i >= 0; i--) {
  2483. result[i] = a[b--] & 0xff;
  2484. int numBytesToTransfer = Math.min(3, b-keep+1);
  2485. if (numBytesToTransfer < 0)
  2486. numBytesToTransfer = 0;
  2487. for (int j=8; j <= 8*numBytesToTransfer; j += 8)
  2488. result[i] |= ((a[b--] & 0xff) << j);
  2489. // Mask indicates which bits must be complemented
  2490. int mask = -1 >>> (8*(3-numBytesToTransfer));
  2491. result[i] = ~result[i] & mask;
  2492. }
  2493. // Add one to one's complement to generate two's complement
  2494. for (int i=result.length-1; i>=0; i--) {
  2495. result[i] = (int)((result[i] & LONG_MASK) + 1);
  2496. if (result[i] != 0)
  2497. break;
  2498. }
  2499. return result;
  2500. }
  2501. /**
  2502. * Takes an array a representing a negative 2's-complement number and
  2503. * returns the minimal (no leading zero ints) unsigned whose value is -a.
  2504. */
  2505. private static int[] makePositive(int a[]) {
  2506. int keep, j;
  2507. // Find first non-sign (0xffffffff) int of input
  2508. for (keep=0; keep<a.length && a[keep]==-1; keep++)
  2509. ;
  2510. /* Allocate output array. If all non-sign ints are 0x00, we must
  2511. * allocate space for one extra output int. */
  2512. for (j=keep; j<a.length && a[j]==0; j++)
  2513. ;
  2514. int extraInt = (j==a.length ? 1 : 0);
  2515. int result[] = new int[a.length - keep + extraInt];
  2516. /* Copy one's complement of input into into output, leaving extra
  2517. * int (if it exists) == 0x00 */
  2518. for (int i = keep; i<a.length; i++)
  2519. result[i - keep + extraInt] = ~a[i];
  2520. // Add one to one's complement to generate two's complement
  2521. for (int i=result.length-1; ++result[i]==0; i--)
  2522. ;
  2523. return result;
  2524. }
  2525. /*
  2526. * The following two arrays are used for fast String conversions. Both
  2527. * are indexed by radix. The first is the number of digits of the given
  2528. * radix that can fit in a Java long without "going negative", i.e., the
  2529. * highest integer n such that radix**n < 2**63. The second is the
  2530. * "long radix" that tears each number into "long digits", each of which
  2531. * consists of the number of digits in the corresponding element in
  2532. * digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have
  2533. * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
  2534. * used.
  2535. */
  2536. private static int digitsPerLong[] = {0, 0,
  2537. 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
  2538. 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
  2539. private static BigInteger longRadix[] = {null, null,
  2540. valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
  2541. valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
  2542. valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
  2543. valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
  2544. valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
  2545. valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
  2546. valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
  2547. valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
  2548. valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
  2549. valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
  2550. valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
  2551. valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
  2552. valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
  2553. valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
  2554. valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
  2555. valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
  2556. valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
  2557. valueOf(0x41c21cb8e1000000L)};
  2558. /*
  2559. * These two arrays are the integer analogue of above.
  2560. */
  2561. private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11,
  2562. 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  2563. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};
  2564. private static int intRadix[] = {0, 0,
  2565. 0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
  2566. 0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
  2567. 0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000,
  2568. 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
  2569. 0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40,
  2570. 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
  2571. 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
  2572. };
  2573. /**
  2574. * These routines provide access to the two's complement representation
  2575. * of BigIntegers.
  2576. */
  2577. /**
  2578. * Returns the length of the two's complement representation in ints,
  2579. * including space for at least one sign bit.
  2580. */
  2581. private int intLength() {
  2582. return bitLength()/32 + 1;
  2583. }
  2584. /* Returns sign bit */
  2585. private int signBit() {
  2586. return (signum < 0 ? 1 : 0);
  2587. }
  2588. /* Returns an int of sign bits */
  2589. private int signInt() {
  2590. return (int) (signum < 0 ? -1 : 0);
  2591. }
  2592. /**
  2593. * Returns the specified int of the little-endian two's complement
  2594. * representation (int 0 is the least significant). The int number can
  2595. * be arbitrarily high (values are logically preceded by infinitely many
  2596. * sign ints).
  2597. */
  2598. private int getInt(int n) {
  2599. if (n < 0)
  2600. return 0;
  2601. if (n >= mag.length)
  2602. return signInt();
  2603. int magInt = mag[mag.length-n-1];
  2604. return (int) (signum >= 0 ? magInt :
  2605. (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
  2606. }
  2607. /**
  2608. * Returns the index of the int that contains the first nonzero int in the
  2609. * little-endian binary representation of the magnitude (int 0 is the
  2610. * least significant). If the magnitude is zero, return value is undefined.
  2611. */
  2612. private int firstNonzeroIntNum() {
  2613. /*
  2614. * Initialize firstNonzeroIntNum field the first time this method is
  2615. * executed. This method depends on the atomicity of int modifies;
  2616. * without this guarantee, it would have to be synchronized.
  2617. */
  2618. if (firstNonzeroIntNum == -2) {
  2619. // Search for the first nonzero int
  2620. int i;
  2621. for (i=mag.length-1; i>=0 && mag[i]==0; i--)
  2622. ;
  2623. firstNonzeroIntNum = mag.length-i-1;
  2624. }
  2625. return firstNonzeroIntNum;
  2626. }
  2627. /** use serialVersionUID from JDK 1.1. for interoperability */
  2628. private static final long serialVersionUID = -8287574255936472291L;
  2629. /**
  2630. * Serializable fields for BigInteger.
  2631. *
  2632. * @serialField signum int
  2633. * signum of this BigInteger.
  2634. * @serialField magnitude int[]
  2635. * magnitude array of this BigInteger.
  2636. * @serialField bitCount int
  2637. * number of bits in this BigInteger
  2638. * @serialField bitLength int
  2639. * the number of bits in the minimal two's-complement
  2640. * representation of this BigInteger
  2641. * @serialField lowestSetBit int
  2642. * lowest set bit in the twos complement representation
  2643. */
  2644. private static final ObjectStreamField[] serialPersistentFields = {
  2645. new ObjectStreamField("signum", Integer.TYPE),
  2646. new ObjectStreamField("magnitude", byte[].class),
  2647. new ObjectStreamField("bitCount", Integer.TYPE),
  2648. new ObjectStreamField("bitLength", Integer.TYPE),
  2649. new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
  2650. new ObjectStreamField("lowestSetBit", Integer.TYPE)
  2651. };
  2652. /**
  2653. * Reconstitute the <tt>BigInteger</tt> instance from a stream (that is,
  2654. * deserialize it). The magnitude is read in as an array of bytes
  2655. * for historical reasons, but it is converted to an array of ints
  2656. * and the byte array is discarded.
  2657. */
  2658. private void readObject(java.io.ObjectInputStream s)
  2659. throws java.io.IOException, ClassNotFoundException {
  2660. /*
  2661. * In order to maintain compatibility with previous serialized forms,
  2662. * the magnitude of a BigInteger is serialized as an array of bytes.
  2663. * The magnitude field is used as a temporary store for the byte array
  2664. * that is deserialized. The cached computation fields should be
  2665. * transient but are serialized for compatibility reasons.
  2666. */
  2667. // prepare to read the alternate persistent fields
  2668. ObjectInputStream.GetField fields = s.readFields();
  2669. // Read the alternate persistent fields that we care about
  2670. signum = (int)fields.get("signum", -2);
  2671. byte[] magnitude = (byte[])fields.get("magnitude", null);
  2672. // Validate signum
  2673. if (signum < -1 || signum > 1) {
  2674. String message = "BigInteger: Invalid signum value";
  2675. if (fields.defaulted("signum"))
  2676. message = "BigInteger: Signum not present in stream";
  2677. throw new java.io.StreamCorruptedException(message);
  2678. }
  2679. if ((magnitude.length==0) != (signum==0)) {
  2680. String message = "BigInteger: signum-magnitude mismatch";
  2681. if (fields.defaulted("magnitude"))
  2682. message = "BigInteger: Magnitude not present in stream";
  2683. throw new java.io.StreamCorruptedException(message);
  2684. }
  2685. // Set "cached computation" fields to their initial values
  2686. bitCount = bitLength = -1;
  2687. lowestSetBit = -2;
  2688. // Calculate mag field from magnitude and discard magnitude
  2689. mag = stripLeadingZeroBytes(magnitude);
  2690. }
  2691. /**
  2692. * Save the <tt>BigInteger</tt> instance to a stream.
  2693. * The magnitude of a BigInteger is serialized as a byte array for
  2694. * historical reasons.
  2695. *
  2696. * @serialData two necessary fields are written as well as obsolete
  2697. * fields for compatibility with older versions.
  2698. */
  2699. private void writeObject(ObjectOutputStream s) throws IOException {
  2700. // set the values of the Serializable fields
  2701. ObjectOutputStream.PutField fields = s.putFields();
  2702. fields.put("signum", signum);
  2703. fields.put("magnitude", magSerializedForm());
  2704. fields.put("bitCount", -1);
  2705. fields.put("bitLength", -1);
  2706. fields.put("lowestSetBit", -2);
  2707. fields.put("firstNonzeroByteNum", -2);
  2708. // save them
  2709. s.writeFields();
  2710. }
  2711. /**
  2712. * Returns the mag array as an array of bytes.
  2713. */
  2714. private byte[] magSerializedForm() {
  2715. int bitLen = (mag.length == 0 ? 0 :
  2716. ((mag.length - 1) << 5) + bitLen(mag[0]));
  2717. int byteLen = (bitLen + 7)/8;
  2718. byte[] result = new byte[byteLen];
  2719. for (int i=byteLen-1, bytesCopied=4, intIndex=mag.length-1, nextInt=0;
  2720. i>=0; i--) {
  2721. if (bytesCopied == 4) {
  2722. nextInt = mag[intIndex--];
  2723. bytesCopied = 1;
  2724. } else {
  2725. nextInt >>>= 8;
  2726. bytesCopied++;
  2727. }
  2728. result[i] = (byte)nextInt;
  2729. }
  2730. return result;
  2731. }
  2732. }