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