1. /*
  2. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  3. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. */
  5. /*
  6. * @(#)BigInteger.java 1.55 03/01/29
  7. */
  8. package java.math;
  9. import java.util.Random;
  10. import java.io.*;
  11. /**
  12. * Immutable arbitrary-precision integers. All operations behave as if
  13. * BigIntegers were represented in two's-complement notation (like Java's
  14. * primitive integer types). BigInteger provides analogues to all of Java's
  15. * primitive integer operators, and all relevant methods from java.lang.Math.
  16. * Additionally, BigInteger provides operations for modular arithmetic, GCD
  17. * calculation, primality testing, prime generation, bit manipulation,
  18. * and a few other miscellaneous operations.
  19. * <p>
  20. * Semantics of arithmetic operations exactly mimic those of Java's integer
  21. * arithmetic operators, as defined in <i>The Java Language Specification</i>.
  22. * For example, division by zero throws an <tt>ArithmeticException</tt>, and
  23. * division of a negative by a positive yields a negative (or zero) remainder.
  24. * All of the details in the Spec concerning overflow are ignored, as
  25. * BigIntegers are made as large as necessary to accommodate the results of an
  26. * operation.
  27. * <p>
  28. * Semantics of shift operations extend those of Java's shift operators
  29. * to allow for negative shift distances. A right-shift with a negative
  30. * shift distance results in a left shift, and vice-versa. The unsigned
  31. * right shift operator (>>>) is omitted, as this operation makes
  32. * little sense in combination with the "infinite word size" abstraction
  33. * provided by this class.
  34. * <p>
  35. * Semantics of bitwise logical operations exactly mimic those of Java's
  36. * bitwise integer operators. The binary operators (<tt>and</tt>,
  37. * <tt>or</tt>, <tt>xor</tt>) implicitly perform sign extension on the shorter
  38. * of the two operands prior to performing the operation.
  39. * <p>
  40. * Comparison operations perform signed integer comparisons, analogous to
  41. * those performed by Java's relational and equality operators.
  42. * <p>
  43. * Modular arithmetic operations are provided to compute residues, perform
  44. * exponentiation, and compute multiplicative inverses. These methods always
  45. * return a non-negative result, between <tt>0</tt> and <tt>(modulus - 1)</tt>,
  46. * inclusive.
  47. * <p>
  48. * Bit operations operate on a single bit of the two's-complement
  49. * representation of their operand. If necessary, the operand is sign-
  50. * extended so that it contains the designated bit. None of the single-bit
  51. * operations can produce a BigInteger with a different sign from the
  52. * BigInteger being operated on, as they affect only a single bit, and the
  53. * "infinite word size" abstraction provided by this class ensures that there
  54. * are infinitely many "virtual sign bits" preceding each BigInteger.
  55. * <p>
  56. * For the sake of brevity and clarity, pseudo-code is used throughout the
  57. * descriptions of BigInteger methods. The pseudo-code expression
  58. * <tt>(i + j)</tt> is shorthand for "a BigInteger whose value is
  59. * that of the BigInteger <tt>i</tt> plus that of the BigInteger <tt>j</tt>."
  60. * The pseudo-code expression <tt>(i == j)</tt> is shorthand for
  61. * "<tt>true</tt> if and only if the BigInteger <tt>i</tt> represents the same
  62. * value as the the BigInteger <tt>j</tt>." Other pseudo-code expressions are
  63. * interpreted similarly.
  64. * <p>
  65. * All methods and constructors in this class throw
  66. * <CODE>NullPointerException</CODE> when passed
  67. * a null object reference for any input parameter.
  68. *
  69. * @see BigDecimal
  70. * @version 1.55, 01/29/03
  71. * @author Josh Bloch
  72. * @author Michael McCloskey
  73. * @since JDK1.1
  74. */
  75. public class BigInteger extends Number implements Comparable {
  76. /**
  77. * The signum of this BigInteger: -1 for negative, 0 for zero, or
  78. * 1 for positive. Note that the BigInteger zero <i>must</i> have
  79. * a signum of 0. This is necessary to ensures that there is exactly one
  80. * representation for each BigInteger value.
  81. *
  82. * @serial
  83. */
  84. int signum;
  85. /**
  86. * The magnitude of this BigInteger, in <i>big-endian</i> order: the
  87. * zeroth element of this array is the most-significant int of the
  88. * magnitude. The magnitude must be "minimal" in that the most-significant
  89. * int (<tt>mag[0]</tt>) must be non-zero. This is necessary to
  90. * ensure that there is exactly one representation for each BigInteger
  91. * value. Note that this implies that the BigInteger zero has a
  92. * zero-length mag array.
  93. */
  94. int[] mag;
  95. // These "redundant fields" are initialized with recognizable nonsense
  96. // values, and cached the first time they are needed (or never, if they
  97. // aren't needed).
  98. /**
  99. * The bitCount of this BigInteger, as returned by bitCount(), or -1
  100. * (either value is acceptable).
  101. *
  102. * @serial
  103. * @see #bitCount
  104. */
  105. private int bitCount = -1;
  106. /**
  107. * The bitLength of this BigInteger, as returned by bitLength(), or -1
  108. * (either value is acceptable).
  109. *
  110. * @serial
  111. * @see #bitLength
  112. */
  113. private int bitLength = -1;
  114. /**
  115. * The lowest set bit of this BigInteger, as returned by getLowestSetBit(),
  116. * or -2 (either value is acceptable).
  117. *
  118. * @serial
  119. * @see #getLowestSetBit
  120. */
  121. private int lowestSetBit = -2;
  122. /**
  123. * The index of the lowest-order byte in the magnitude of this BigInteger
  124. * that contains a nonzero byte, or -2 (either value is acceptable). The
  125. * least significant byte has int-number 0, the next byte in order of
  126. * increasing significance has byte-number 1, and so forth.
  127. *
  128. * @serial
  129. */
  130. private int firstNonzeroByteNum = -2;
  131. /**
  132. * The index of the lowest-order int in the magnitude of this BigInteger
  133. * that contains a nonzero int, or -2 (either value is acceptable). The
  134. * least significant int has int-number 0, the next int in order of
  135. * increasing significance has int-number 1, and so forth.
  136. */
  137. private int firstNonzeroIntNum = -2;
  138. /**
  139. * This mask is used to obtain the value of an int as if it were unsigned.
  140. */
  141. private final static long LONG_MASK = 0xffffffffL;
  142. //Constructors
  143. /**
  144. * Translates a byte array containing the two's-complement binary
  145. * representation of a BigInteger into a BigInteger. The input array is
  146. * assumed to be in <i>big-endian</i> byte-order: the most significant
  147. * byte is in the zeroth element.
  148. *
  149. * @param val big-endian two's-complement binary representation of
  150. * BigInteger.
  151. * @throws NumberFormatException <tt>val</tt> is zero bytes long.
  152. */
  153. public BigInteger(byte[] val) {
  154. if (val.length == 0)
  155. throw new NumberFormatException("Zero length BigInteger");
  156. if (val[0] < 0) {
  157. mag = makePositive(val);
  158. signum = -1;
  159. } else {
  160. mag = stripLeadingZeroBytes(val);
  161. signum = (mag.length == 0 ? 0 : 1);
  162. }
  163. }
  164. /**
  165. * This private constructor translates an int array containing the
  166. * two's-complement binary representation of a BigInteger into a
  167. * BigInteger. The input array is assumed to be in <i>big-endian</i>
  168. * int-order: the most significant int is in the zeroth element.
  169. */
  170. private BigInteger(int[] val) {
  171. if (val.length == 0)
  172. throw new NumberFormatException("Zero length BigInteger");
  173. if (val[0] < 0) {
  174. mag = makePositive(val);
  175. signum = -1;
  176. } else {
  177. mag = trustedStripLeadingZeroInts(val);
  178. signum = (mag.length == 0 ? 0 : 1);
  179. }
  180. }
  181. /**
  182. * Translates the sign-magnitude representation of a BigInteger into a
  183. * BigInteger. The sign is represented as an integer signum value: -1 for
  184. * negative, 0 for zero, or 1 for positive. The magnitude is a byte array
  185. * in <i>big-endian</i> byte-order: the most significant byte is in the
  186. * zeroth element. A zero-length magnitude array is permissible, and will
  187. * result in in a BigInteger value of 0, whether signum is -1, 0 or 1.
  188. *
  189. * @param signum signum of the number (-1 for negative, 0 for zero, 1
  190. * for positive).
  191. * @param magnitude big-endian binary representation of the magnitude of
  192. * the number.
  193. * @throws NumberFormatException <tt>signum</tt> is not one of the three
  194. * legal values (-1, 0, and 1), or <tt>signum</tt> is 0 and
  195. * <tt>magnitude</tt> contains one or more non-zero bytes.
  196. */
  197. public BigInteger(int signum, byte[] magnitude) {
  198. this.mag = stripLeadingZeroBytes(magnitude);
  199. if (signum < -1 || signum > 1)
  200. throw(new NumberFormatException("Invalid signum value"));
  201. if (this.mag.length==0) {
  202. this.signum = 0;
  203. } else {
  204. if (signum == 0)
  205. throw(new NumberFormatException("signum-magnitude mismatch"));
  206. this.signum = signum;
  207. }
  208. }
  209. /**
  210. * A constructor for internal use that translates the sign-magnitude
  211. * representation of a BigInteger into a BigInteger. It checks the
  212. * arguments and copies the magnitude so this constructor would be
  213. * safe for external use.
  214. */
  215. private BigInteger(int signum, int[] magnitude) {
  216. this.mag = stripLeadingZeroInts(magnitude);
  217. if (signum < -1 || signum > 1)
  218. throw(new NumberFormatException("Invalid signum value"));
  219. if (this.mag.length==0) {
  220. this.signum = 0;
  221. } else {
  222. if (signum == 0)
  223. throw(new NumberFormatException("signum-magnitude mismatch"));
  224. this.signum = signum;
  225. }
  226. }
  227. /**
  228. * Translates the String representation of a BigInteger in the specified
  229. * radix into a BigInteger. The String representation consists of an
  230. * optional minus sign followed by a sequence of one or more digits in the
  231. * specified radix. The character-to-digit mapping is provided by
  232. * <tt>Character.digit</tt>. The String may not contain any extraneous
  233. * characters (whitespace, for example).
  234. *
  235. * @param val String representation of BigInteger.
  236. * @param radix radix to be used in interpreting <tt>val</tt>.
  237. * @throws NumberFormatException <tt>val</tt> is not a valid representation
  238. * of a BigInteger in the specified radix, or <tt>radix</tt> is
  239. * outside the range from {@link Character#MIN_RADIX} to
  240. * {@link Character#MAX_RADIX}, inclusive.
  241. * @see Character#digit
  242. */
  243. public BigInteger(String val, int radix) {
  244. int cursor = 0, numDigits;
  245. int len = val.length();
  246. if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  247. throw new NumberFormatException("Radix out of range");
  248. if (val.length() == 0)
  249. throw new NumberFormatException("Zero length BigInteger");
  250. // Check for minus sign
  251. signum = 1;
  252. int index = val.indexOf('-');
  253. if (index != -1) {
  254. if (index == 0) {
  255. if (val.length() == 1)
  256. throw new NumberFormatException("Zero length BigInteger");
  257. signum = -1;
  258. cursor = 1;
  259. } else {
  260. throw new NumberFormatException("Illegal embedded minus sign");
  261. }
  262. }
  263. // Skip leading zeros and compute number of digits in magnitude
  264. while (cursor < len &&
  265. Character.digit(val.charAt(cursor),radix) == 0)
  266. cursor++;
  267. if (cursor == len) {
  268. signum = 0;
  269. mag = ZERO.mag;
  270. return;
  271. } else {
  272. numDigits = len - cursor;
  273. }
  274. // Pre-allocate array of expected size. May be too large but can
  275. // never be too small. Typically exact.
  276. int numBits = (int)(((numDigits * bitsPerDigit[radix]) >>> 10) + 1);
  277. int numWords = (numBits + 31) /32;
  278. mag = new int[numWords];
  279. // Process first (potentially short) digit group
  280. int firstGroupLen = numDigits % digitsPerInt[radix];
  281. if (firstGroupLen == 0)
  282. firstGroupLen = digitsPerInt[radix];
  283. String group = val.substring(cursor, cursor += firstGroupLen);
  284. mag[mag.length - 1] = Integer.parseInt(group, radix);
  285. if (mag[mag.length - 1] < 0)
  286. throw new NumberFormatException("Illegal digit");
  287. // Process remaining digit groups
  288. int superRadix = intRadix[radix];
  289. int groupVal = 0;
  290. while (cursor < val.length()) {
  291. group = val.substring(cursor, cursor += digitsPerInt[radix]);
  292. groupVal = Integer.parseInt(group, radix);
  293. if (groupVal < 0)
  294. throw new NumberFormatException("Illegal digit");
  295. destructiveMulAdd(mag, superRadix, groupVal);
  296. }
  297. // Required for cases where the array was overallocated.
  298. mag = trustedStripLeadingZeroInts(mag);
  299. }
  300. // Constructs a new BigInteger using a char array with radix=10
  301. BigInteger(char[] val) {
  302. int cursor = 0, numDigits;
  303. int len = val.length;
  304. // Check for leading minus sign
  305. signum = 1;
  306. if (val[0] == '-') {
  307. if (len == 1)
  308. throw new NumberFormatException("Zero length BigInteger");
  309. signum = -1;
  310. cursor = 1;
  311. }
  312. // Skip leading zeros and compute number of digits in magnitude
  313. while (cursor < len && Character.digit(val[cursor], 10) == 0)
  314. cursor++;
  315. if (cursor == len) {
  316. signum = 0;
  317. mag = ZERO.mag;
  318. return;
  319. } else {
  320. numDigits = len - cursor;
  321. }
  322. // Pre-allocate array of expected size
  323. int numWords;
  324. if (len < 10) {
  325. numWords = 1;
  326. } else {
  327. int numBits = (int)(((numDigits * bitsPerDigit[10]) >>> 10) + 1);
  328. numWords = (numBits + 31) /32;
  329. }
  330. mag = new int[numWords];
  331. // Process first (potentially short) digit group
  332. int firstGroupLen = numDigits % digitsPerInt[10];
  333. if (firstGroupLen == 0)
  334. firstGroupLen = digitsPerInt[10];
  335. mag[mag.length-1] = parseInt(val, cursor, cursor += firstGroupLen);
  336. // Process remaining digit groups
  337. while (cursor < len) {
  338. int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
  339. destructiveMulAdd(mag, intRadix[10], groupVal);
  340. }
  341. mag = trustedStripLeadingZeroInts(mag);
  342. }
  343. // Create an integer with the digits between the two indexes
  344. // Assumes start < end. The result may be negative, but it
  345. // is to be treated as an unsigned value.
  346. private int parseInt(char[] source, int start, int end) {
  347. int result = Character.digit(source[start++], 10);
  348. if (result == -1)
  349. throw new NumberFormatException(new String(source));
  350. for (int index = start; index<end; index++) {
  351. int nextVal = Character.digit(source[index], 10);
  352. if (nextVal == -1)
  353. throw new NumberFormatException(new String(source));
  354. result = 10*result + nextVal;
  355. }
  356. return result;
  357. }
  358. // bitsPerDigit in the given radix times 1024
  359. // Rounded up to avoid underallocation.
  360. private static long bitsPerDigit[] = { 0, 0,
  361. 1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
  362. 3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
  363. 4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
  364. 5253, 5295};
  365. // Multiply x array times word y in place, and add word z
  366. private static void destructiveMulAdd(int[] x, int y, int z) {
  367. // Perform the multiplication word by word
  368. long ylong = y & LONG_MASK;
  369. long zlong = z & LONG_MASK;
  370. int len = x.length;
  371. long product = 0;
  372. long carry = 0;
  373. for (int i = len-1; i >= 0; i--) {
  374. product = ylong * (x[i] & LONG_MASK) + carry;
  375. x[i] = (int)product;
  376. carry = product >>> 32;
  377. }
  378. // Perform the addition
  379. long sum = (x[len-1] & LONG_MASK) + zlong;
  380. x[len-1] = (int)sum;
  381. carry = sum >>> 32;
  382. for (int i = len-2; i >= 0; i--) {
  383. sum = (x[i] & LONG_MASK) + carry;
  384. x[i] = (int)sum;
  385. carry = sum >>> 32;
  386. }
  387. }
  388. /**
  389. * Translates the decimal String representation of a BigInteger into a
  390. * BigInteger. The String representation consists of an optional minus
  391. * sign followed by a sequence of one or more decimal digits. The
  392. * character-to-digit mapping is provided by <tt>Character.digit</tt>.
  393. * The String may not contain any extraneous characters (whitespace, for
  394. * example).
  395. *
  396. * @param val decimal String representation of BigInteger.
  397. * @throws NumberFormatException <tt>val</tt> is not a valid representation
  398. * of a BigInteger.
  399. * @see Character#digit
  400. */
  401. public BigInteger(String val) {
  402. this(val, 10);
  403. }
  404. /**
  405. * Constructs a randomly generated BigInteger, uniformly distributed over
  406. * the range <tt>0</tt> to <tt>(2<sup>numBits</sup> - 1)</tt>, inclusive.
  407. * The uniformity of the distribution assumes that a fair source of random
  408. * bits is provided in <tt>rnd</tt>. Note that this constructor always
  409. * constructs a non-negative BigInteger.
  410. *
  411. * @param numBits maximum bitLength of the new BigInteger.
  412. * @param rnd source of randomness to be used in computing the new
  413. * BigInteger.
  414. * @throws IllegalArgumentException <tt>numBits</tt> is negative.
  415. * @see #bitLength
  416. */
  417. public BigInteger(int numBits, Random rnd) {
  418. this(1, randomBits(numBits, rnd));
  419. }
  420. private static byte[] randomBits(int numBits, Random rnd) {
  421. if (numBits < 0)
  422. throw new IllegalArgumentException("numBits must be non-negative");
  423. int numBytes = (numBits+7)/8;
  424. byte[] randomBits = new byte[numBytes];
  425. // Generate random bytes and mask out any excess bits
  426. if (numBytes > 0) {
  427. rnd.nextBytes(randomBits);
  428. int excessBits = 8*numBytes - numBits;
  429. randomBits[0] &= (1 << (8-excessBits)) - 1;
  430. }
  431. return randomBits;
  432. }
  433. /**
  434. * Constructs a randomly generated positive BigInteger that is probably
  435. * prime, with the specified bitLength.<p>
  436. *
  437. * It is recommended that the {@link #probablePrime probablePrime}
  438. * method be used in preference to this constructor unless there
  439. * is a compelling need to specify a certainty.
  440. *
  441. * @param bitLength bitLength of the returned BigInteger.
  442. * @param certainty a measure of the uncertainty that the caller is
  443. * willing to tolerate. The probability that the new BigInteger
  444. * represents a prime number will exceed
  445. * <tt>(1 - 1/2<sup>certainty</sup></tt>). The execution time of
  446. * this constructor is proportional to the value of this parameter.
  447. * @param rnd source of random bits used to select candidates to be
  448. * tested for primality.
  449. * @throws ArithmeticException <tt>bitLength < 2</tt>.
  450. * @see #bitLength
  451. */
  452. public BigInteger(int bitLength, int certainty, Random rnd) {
  453. BigInteger prime;
  454. if (bitLength < 2)
  455. throw new ArithmeticException("bitLength < 2");
  456. // The cutoff of 95 was chosen empirically for best performance
  457. prime = (bitLength < 95 ? smallPrime(bitLength, certainty, rnd)
  458. : largePrime(bitLength, certainty, rnd));
  459. signum = 1;
  460. mag = prime.mag;
  461. }
  462. // Minimum size in bits that the requested prime number has
  463. // before we use the large prime number generating algorithms
  464. private static final int SMALL_PRIME_THRESHOLD = 95;
  465. /**
  466. * Returns a positive BigInteger that is probably prime, with the
  467. * specified bitLength. The probability that a BigInteger returned
  468. * by this method is composite does not exceed 2<sup>-100</sup>.
  469. *
  470. * @param bitLength bitLength of the returned BigInteger.
  471. * @param rnd source of random bits used to select candidates to be
  472. * tested for primality.
  473. * @return a BigInteger of <tt>bitLength</tt> bits that is probably prime
  474. * @throws ArithmeticException <tt>bitLength < 2</tt>.
  475. * @see #bitLength
  476. */
  477. public static BigInteger probablePrime(int bitLength, Random rnd) {
  478. if (bitLength < 2)
  479. throw new ArithmeticException("bitLength < 2");
  480. // The cutoff of 95 was chosen empirically for best performance
  481. return (bitLength < SMALL_PRIME_THRESHOLD ?
  482. smallPrime(bitLength, 100, rnd) :
  483. largePrime(bitLength, 100, rnd));
  484. }
  485. /**
  486. * Find a random number of the specified bitLength that is probably prime.
  487. * This method is used for smaller primes, its performance degrades on
  488. * larger bitlengths.
  489. *
  490. * This method assumes bitLength > 1.
  491. */
  492. private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
  493. int magLen = (bitLength + 31) >>> 5;
  494. int temp[] = new int[magLen];
  495. int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int
  496. int highMask = (highBit << 1) - 1; // Bits to keep in high int
  497. while(true) {
  498. // Construct a candidate
  499. for (int i=0; i<magLen; i++)
  500. temp[i] = rnd.nextInt();
  501. temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length
  502. if (bitLength > 2)
  503. temp[magLen-1] |= 1; // Make odd if bitlen > 2
  504. BigInteger p = new BigInteger(temp, 1);
  505. // Do cheap "pre-test" if applicable
  506. if (bitLength > 6) {
  507. long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
  508. if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
  509. (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
  510. (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
  511. continue; // Candidate is composite; try another
  512. }
  513. // All candidates of bitLength 2 and 3 are prime by this point
  514. if (bitLength < 4)
  515. return p;
  516. // Do expensive test if we survive pre-test (or it's inapplicable)
  517. if (p.primeToCertainty(certainty))
  518. return p;
  519. }
  520. }
  521. private static final BigInteger SMALL_PRIME_PRODUCT
  522. = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
  523. /**
  524. * Find a random number of the specified bitLength that is probably prime.
  525. * This method is more appropriate for larger bitlengths since it uses
  526. * a sieve to eliminate most composites before using a more expensive
  527. * test.
  528. */
  529. private static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
  530. BigInteger p;
  531. p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
  532. p.mag[p.mag.length-1] &= 0xfffffffe;
  533. // Use a sieve length likely to contain the next prime number
  534. int searchLen = (bitLength / 20) * 64;
  535. BitSieve searchSieve = new BitSieve(p, searchLen);
  536. BigInteger candidate = searchSieve.retrieve(p, certainty);
  537. while ((candidate == null) || (candidate.bitLength() != bitLength)) {
  538. p = p.add(BigInteger.valueOf(2*searchLen));
  539. if (p.bitLength() != bitLength)
  540. p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
  541. p.mag[p.mag.length-1] &= 0xfffffffe;
  542. searchSieve = new BitSieve(p, searchLen);
  543. candidate = searchSieve.retrieve(p, certainty);
  544. }
  545. return candidate;
  546. }
  547. /**
  548. * Returns <tt>true</tt> if this BigInteger is probably prime,
  549. * <tt>false</tt> if it's definitely composite.
  550. *
  551. * This method assumes bitLength > 2.
  552. *
  553. * @param certainty a measure of the uncertainty that the caller is
  554. * willing to tolerate: if the call returns <tt>true</tt>
  555. * the probability that this BigInteger is prime exceeds
  556. * <tt>(1 - 1/2<sup>certainty</sup>)</tt>. The execution time of
  557. * this method is proportional to the value of this parameter.
  558. * @return <tt>true</tt> if this BigInteger is probably prime,
  559. * <tt>false</tt> if it's definitely composite.
  560. */
  561. boolean primeToCertainty(int certainty) {
  562. int rounds = 0;
  563. int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2;
  564. // The relationship between the certainty and the number of rounds
  565. // we perform is given in the draft standard ANSI X9.80, "PRIME
  566. // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
  567. int sizeInBits = this.bitLength();
  568. if (sizeInBits < 100) {
  569. rounds = 50;
  570. rounds = n < rounds ? n : rounds;
  571. return passesMillerRabin(rounds);
  572. }
  573. if (sizeInBits < 256) {
  574. rounds = 27;
  575. } else if (sizeInBits < 512) {
  576. rounds = 15;
  577. } else if (sizeInBits < 768) {
  578. rounds = 8;
  579. } else if (sizeInBits < 1024) {
  580. rounds = 4;
  581. } else {
  582. rounds = 2;
  583. }
  584. rounds = n < rounds ? n : rounds;
  585. return passesMillerRabin(rounds) && passesLucasLehmer();
  586. }
  587. /**
  588. * Returns true iff this BigInteger is a Lucas-Lehmer probable prime.
  589. *
  590. * The following assumptions are made:
  591. * This BigInteger is a positive, odd number.
  592. */
  593. private boolean passesLucasLehmer() {
  594. BigInteger thisPlusOne = this.add(ONE);
  595. // Step 1
  596. int d = 5;
  597. while (jacobiSymbol(d, this) != -1) {
  598. // 5, -7, 9, -11, ...
  599. d = (d<0) ? Math.abs(d)+2 : -(d+2);
  600. }
  601. // Step 2
  602. BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);
  603. // Step 3
  604. return u.mod(this).equals(ZERO);
  605. }
  606. /**
  607. * Computes Jacobi(p,n).
  608. * Assumes n is positive, odd.
  609. */
  610. int jacobiSymbol(int p, BigInteger n) {
  611. if (p == 0)
  612. return 0;
  613. // Algorithm and comments adapted from Colin Plumb's C library.
  614. int j = 1;
  615. int u = n.mag[n.mag.length-1];
  616. // Make p positive
  617. if (p < 0) {
  618. p = -p;
  619. int n8 = u & 7;
  620. if ((n8 == 3) || (n8 == 7))
  621. j = -j; // 3 (011) or 7 (111) mod 8
  622. }
  623. // Get rid of factors of 2 in p
  624. while ((p & 3) == 0)
  625. p >>= 2;
  626. if ((p & 1) == 0) {
  627. p >>= 1;
  628. if (((u ^ u>>1) & 2) != 0)
  629. j = -j; // 3 (011) or 5 (101) mod 8
  630. }
  631. if (p == 1)
  632. return j;
  633. // Then, apply quadratic reciprocity
  634. if ((p & u & 2) != 0) // p = u = 3 (mod 4)?
  635. j = -j;
  636. // And reduce u mod p
  637. u = n.mod(BigInteger.valueOf(p)).intValue();
  638. // Now compute Jacobi(u,p), u < p
  639. while (u != 0) {
  640. while ((u & 3) == 0)
  641. u >>= 2;
  642. if ((u & 1) == 0) {
  643. u >>= 1;
  644. if (((p ^ p>>1) & 2) != 0)
  645. j = -j; // 3 (011) or 5 (101) mod 8
  646. }
  647. if (u == 1)
  648. return j;
  649. // Now both u and p are odd, so use quadratic reciprocity
  650. if (u < p) {
  651. int t = u; u = p; p = t;
  652. if ((u & p & 2) != 0)// u = p = 3 (mod 4)?
  653. j = -j;
  654. }
  655. // Now u >= p, so it can be reduced
  656. u %= p;
  657. }
  658. return 0;
  659. }
  660. private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
  661. BigInteger d = BigInteger.valueOf(z);
  662. BigInteger u = ONE; BigInteger u2;
  663. BigInteger v = ONE; BigInteger v2;
  664. for (int i=k.bitLength()-2; i>=0; i--) {
  665. u2 = u.multiply(v).mod(n);
  666. v2 = v.square().add(d.multiply(u.square())).mod(n);
  667. if (v2.testBit(0)) {
  668. v2 = n.subtract(v2);
  669. v2.signum = - v2.signum;
  670. }
  671. v2 = v2.shiftRight(1);
  672. u = u2; v = v2;
  673. if (k.testBit(i)) {
  674. u2 = u.add(v).mod(n);
  675. if (u2.testBit(0)) {
  676. u2 = n.subtract(u2);
  677. u2.signum = - u2.signum;
  678. }
  679. u2 = u2.shiftRight(1);
  680. v2 = v.add(d.multiply(u)).mod(n);
  681. if (v2.testBit(0)) {
  682. v2 = n.subtract(v2);
  683. v2.signum = - v2.signum;
  684. }
  685. v2 = v2.shiftRight(1);
  686. u = u2; v = v2;
  687. }
  688. }
  689. return u;
  690. }
  691. /**
  692. * Returns true iff this BigInteger passes the specified number of
  693. * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS
  694. * 186-2).
  695. *
  696. * The following assumptions are made:
  697. * This BigInteger is a positive, odd number greater than 2.
  698. * iterations<=50.
  699. */
  700. private boolean passesMillerRabin(int iterations) {
  701. // Find a and m such that m is odd and this == 1 + 2**a * m
  702. BigInteger thisMinusOne = this.subtract(ONE);
  703. BigInteger m = thisMinusOne;
  704. int a = m.getLowestSetBit();
  705. m = m.shiftRight(a);
  706. // Do the tests
  707. Random rnd = new Random();
  708. for (int i=0; i<iterations; i++) {
  709. // Generate a uniform random on (1, this)
  710. BigInteger b;
  711. do {
  712. b = new BigInteger(this.bitLength(), rnd);
  713. } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);
  714. int j = 0;
  715. BigInteger z = b.modPow(m, this);
  716. while(!((j==0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
  717. if (j>0 && z.equals(ONE) || ++j==a)
  718. return false;
  719. z = z.modPow(TWO, this);
  720. }
  721. }
  722. return true;
  723. }
  724. /**
  725. * This private constructor differs from its public cousin
  726. * with the arguments reversed in two ways: it assumes that its
  727. * arguments are correct, and it doesn't copy the magnitude array.
  728. */
  729. private BigInteger(int[] magnitude, int signum) {
  730. this.signum = (magnitude.length==0 ? 0 : signum);
  731. this.mag = magnitude;
  732. }
  733. /**
  734. * This private constructor is for internal use and assumes that its
  735. * arguments are correct.
  736. */
  737. private BigInteger(byte[] magnitude, int signum) {
  738. this.signum = (magnitude.length==0 ? 0 : signum);
  739. this.mag = stripLeadingZeroBytes(magnitude);
  740. }
  741. /**
  742. * This private constructor is for internal use in converting
  743. * from a MutableBigInteger object into a BigInteger.
  744. */
  745. BigInteger(MutableBigInteger val, int sign) {
  746. if (val.offset > 0 || val.value.length != val.intLen) {
  747. mag = new int[val.intLen];
  748. for(int i=0; i<val.intLen; i++)
  749. mag[i] = val.value[val.offset+i];
  750. } else {
  751. mag = val.value;
  752. }
  753. this.signum = (val.intLen == 0) ? 0 : sign;
  754. }
  755. //Static Factory Methods
  756. /**
  757. * Returns a BigInteger whose value is equal to that of the
  758. * specified <code>long</code>. This "static factory method" is
  759. * provided in preference to a (<code>long</code>) constructor
  760. * because it allows for reuse of frequently used BigIntegers.
  761. *
  762. * @param val value of the BigInteger to return.
  763. * @return a BigInteger with the specified value.
  764. */
  765. public static BigInteger valueOf(long val) {
  766. // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
  767. if (val == 0)
  768. return ZERO;
  769. if (val > 0 && val <= MAX_CONSTANT)
  770. return posConst[(int) val];
  771. else if (val < 0 && val >= -MAX_CONSTANT)
  772. return negConst[(int) -val];
  773. return new BigInteger(val);
  774. }
  775. /**
  776. * Constructs a BigInteger with the specified value, which may not be zero.
  777. */
  778. private BigInteger(long val) {
  779. if (val < 0) {
  780. signum = -1;
  781. val = -val;
  782. } else {
  783. signum = 1;
  784. }
  785. int highWord = (int)(val >>> 32);
  786. if (highWord==0) {
  787. mag = new int[1];
  788. mag[0] = (int)val;
  789. } else {
  790. mag = new int[2];
  791. mag[0] = highWord;
  792. mag[1] = (int)val;
  793. }
  794. }
  795. /**
  796. * Returns a BigInteger with the given two's complement representation.
  797. * Assumes that the input array will not be modified (the returned
  798. * BigInteger will reference the input array if feasible).
  799. */
  800. private static BigInteger valueOf(int val[]) {
  801. return (val[0]>0 ? new BigInteger(val, 1) : new BigInteger(val));
  802. }
  803. // Constants
  804. /**
  805. * Initialize static constant array when class is loaded.
  806. */
  807. private final static int MAX_CONSTANT = 16;
  808. private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
  809. private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
  810. static {
  811. for (int i = 1; i <= MAX_CONSTANT; i++) {
  812. int[] magnitude = new int[1];
  813. magnitude[0] = (int) i;
  814. posConst[i] = new BigInteger(magnitude, 1);
  815. negConst[i] = new BigInteger(magnitude, -1);
  816. }
  817. }
  818. /**
  819. * The BigInteger constant zero.
  820. *
  821. * @since 1.2
  822. */
  823. public static final BigInteger ZERO = new BigInteger(new int[0], 0);
  824. /**
  825. * The BigInteger constant one.
  826. *
  827. * @since 1.2
  828. */
  829. public static final BigInteger ONE = valueOf(1);
  830. /**
  831. * The BigInteger constant two. (Not exported.)
  832. */
  833. private static final BigInteger TWO = valueOf(2);
  834. // Arithmetic Operations
  835. /**
  836. * Returns a BigInteger whose value is <tt>(this + val)</tt>.
  837. *
  838. * @param val value to be added to this BigInteger.
  839. * @return <tt>this + val</tt>
  840. */
  841. public BigInteger add(BigInteger val) {
  842. int[] resultMag;
  843. if (val.signum == 0)
  844. return this;
  845. if (signum == 0)
  846. return val;
  847. if (val.signum == signum)
  848. return new BigInteger(add(mag, val.mag), signum);
  849. int cmp = intArrayCmp(mag, val.mag);
  850. if (cmp==0)
  851. return ZERO;
  852. resultMag = (cmp>0 ? subtract(mag, val.mag)
  853. : subtract(val.mag, mag));
  854. resultMag = trustedStripLeadingZeroInts(resultMag);
  855. return new BigInteger(resultMag, cmp*signum);
  856. }
  857. /**
  858. * Adds the contents of the int arrays x and y. This method allocates
  859. * a new int array to hold the answer and returns a reference to that
  860. * array.
  861. */
  862. private static int[] add(int[] x, int[] y) {
  863. // If x is shorter, swap the two arrays
  864. if (x.length < y.length) {
  865. int[] tmp = x;
  866. x = y;
  867. y = tmp;
  868. }
  869. int xIndex = x.length;
  870. int yIndex = y.length;
  871. int result[] = new int[xIndex];
  872. long sum = 0;
  873. // Add common parts of both numbers
  874. while(yIndex > 0) {
  875. sum = (x[--xIndex] & LONG_MASK) +
  876. (y[--yIndex] & LONG_MASK) + (sum >>> 32);
  877. result[xIndex] = (int)sum;
  878. }
  879. // Copy remainder of longer number while carry propagation is required
  880. boolean carry = (sum >>> 32 != 0);
  881. while (xIndex > 0 && carry)
  882. carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
  883. // Copy remainder of longer number
  884. while (xIndex > 0)
  885. result[--xIndex] = x[xIndex];
  886. // Grow result if necessary
  887. if (carry) {
  888. int newLen = result.length + 1;
  889. int temp[] = new int[newLen];
  890. for (int i = 1; i<newLen; i++)
  891. temp[i] = result[i-1];
  892. temp[0] = 0x01;
  893. result = temp;
  894. }
  895. return result;
  896. }
  897. /**
  898. * Returns a BigInteger whose value is <tt>(this - val)</tt>.
  899. *
  900. * @param val value to be subtracted from this BigInteger.
  901. * @return <tt>this - val</tt>
  902. */
  903. public BigInteger subtract(BigInteger val) {
  904. int[] resultMag;
  905. if (val.signum == 0)
  906. return this;
  907. if (signum == 0)
  908. return val.negate();
  909. if (val.signum != signum)
  910. return new BigInteger(add(mag, val.mag), signum);
  911. int cmp = intArrayCmp(mag, val.mag);
  912. if (cmp==0)
  913. return ZERO;
  914. resultMag = (cmp>0 ? subtract(mag, val.mag)
  915. : subtract(val.mag, mag));
  916. resultMag = trustedStripLeadingZeroInts(resultMag);
  917. return new BigInteger(resultMag, cmp*signum);
  918. }
  919. /**
  920. * Subtracts the contents of the second int arrays (little) from the
  921. * first (big). The first int array (big) must represent a larger number
  922. * than the second. This method allocates the space necessary to hold the
  923. * answer.
  924. */
  925. private static int[] subtract(int[] big, int[] little) {
  926. int bigIndex = big.length;
  927. int result[] = new int[bigIndex];
  928. int littleIndex = little.length;
  929. long difference = 0;
  930. // Subtract common parts of both numbers
  931. while(littleIndex > 0) {
  932. difference = (big[--bigIndex] & LONG_MASK) -
  933. (little[--littleIndex] & LONG_MASK) +
  934. (difference >> 32);
  935. result[bigIndex] = (int)difference;
  936. }
  937. // Subtract remainder of longer number while borrow propagates
  938. boolean borrow = (difference >> 32 != 0);
  939. while (bigIndex > 0 && borrow)
  940. borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
  941. // Copy remainder of longer number
  942. while (bigIndex > 0)
  943. result[--bigIndex] = big[bigIndex];
  944. return result;
  945. }
  946. /**
  947. * Returns a BigInteger whose value is <tt>(this * val)</tt>.
  948. *
  949. * @param val value to be multiplied by this BigInteger.
  950. * @return <tt>this * val</tt>
  951. */
  952. public BigInteger multiply(BigInteger val) {
  953. if (signum == 0 || val.signum==0)
  954. return ZERO;
  955. int[] result = multiplyToLen(mag, mag.length,
  956. val.mag, val.mag.length, null);
  957. result = trustedStripLeadingZeroInts(result);
  958. return new BigInteger(result, signum*val.signum);
  959. }
  960. /**
  961. * Multiplies int arrays x and y to the specified lengths and places
  962. * the result into z.
  963. */
  964. private int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
  965. int xstart = xlen - 1;
  966. int ystart = ylen - 1;
  967. if (z == null || z.length < (xlen+ ylen))
  968. z = new int[xlen+ylen];
  969. long carry = 0;
  970. for (int j=ystart, k=ystart+1+xstart; j>=0; j--, k--) {
  971. long product = (y[j] & LONG_MASK) *
  972. (x[xstart] & LONG_MASK) + carry;
  973. z[k] = (int)product;
  974. carry = product >>> 32;
  975. }
  976. z[xstart] = (int)carry;
  977. for (int i = xstart-1; i >= 0; i--) {
  978. carry = 0;
  979. for (int j=ystart, k=ystart+1+i; j>=0; j--, k--) {
  980. long product = (y[j] & LONG_MASK) *
  981. (x[i] & LONG_MASK) +
  982. (z[k] & LONG_MASK) + carry;
  983. z[k] = (int)product;
  984. carry = product >>> 32;
  985. }
  986. z[i] = (int)carry;
  987. }
  988. return z;
  989. }
  990. /**
  991. * Returns a BigInteger whose value is <tt>(this<sup>2</sup>)</tt>.
  992. *
  993. * @return <tt>this<sup>2</sup></tt>
  994. */
  995. private BigInteger square() {
  996. if (signum == 0)
  997. return ZERO;
  998. int[] z = squareToLen(mag, mag.length, null);
  999. return new BigInteger(trustedStripLeadingZeroInts(z), 1);
  1000. }
  1001. /**
  1002. * Squares the contents of the int array x. The result is placed into the
  1003. * int array z. The contents of x are not changed.
  1004. */
  1005. private static final int[] squareToLen(int[] x, int len, int[] z) {
  1006. /*
  1007. * The algorithm used here is adapted from Colin Plumb's C library.
  1008. * Technique: Consider the partial products in the multiplication
  1009. * of "abcde" by itself:
  1010. *
  1011. * a b c d e
  1012. * * a b c d e
  1013. * ==================
  1014. * ae be ce de ee
  1015. * ad bd cd dd de
  1016. * ac bc cc cd ce
  1017. * ab bb bc bd be
  1018. * aa ab ac ad ae
  1019. *
  1020. * Note that everything above the main diagonal:
  1021. * ae be ce de = (abcd) * e
  1022. * ad bd cd = (abc) * d
  1023. * ac bc = (ab) * c
  1024. * ab = (a) * b
  1025. *
  1026. * is a copy of everything below the main diagonal:
  1027. * de
  1028. * cd ce
  1029. * bc bd be
  1030. * ab ac ad ae
  1031. *
  1032. * Thus, the sum is 2 * (off the diagonal) + diagonal.
  1033. *
  1034. * This is accumulated beginning with the diagonal (which
  1035. * consist of the squares of the digits of the input), which is then
  1036. * divided by two, the off-diagonal added, and multiplied by two
  1037. * again. The low bit is simply a copy of the low bit of the
  1038. * input, so it doesn't need special care.
  1039. */
  1040. int zlen = len << 1;
  1041. if (z == null || z.length < zlen)
  1042. z = new int[zlen];
  1043. // Store the squares, right shifted one bit (i.e., divided by 2)
  1044. int lastProductLowWord = 0;
  1045. for (int j=0, i=0; j<len; j++) {
  1046. long piece = (x[j] & LONG_MASK);
  1047. long product = piece * piece;
  1048. z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);
  1049. z[i++] = (int)(product >>> 1);
  1050. lastProductLowWord = (int)product;
  1051. }
  1052. // Add in off-diagonal sums
  1053. for (int i=len, offset=1; i>0; i--, offset+=2) {
  1054. int t = x[i-1];
  1055. t = mulAdd(z, x, offset, i-1, t);
  1056. addOne(z, offset-1, i, t);
  1057. }
  1058. // Shift back up and set low bit
  1059. primitiveLeftShift(z, zlen, 1);
  1060. z[zlen-1] |= x[len-1] & 1;
  1061. return z;
  1062. }
  1063. /**
  1064. * Returns a BigInteger whose value is <tt>(this / val)</tt>.
  1065. *
  1066. * @param val value by which this BigInteger is to be divided.
  1067. * @return <tt>this / val</tt>
  1068. * @throws ArithmeticException <tt>val==0</tt>
  1069. */
  1070. public BigInteger divide(BigInteger val) {
  1071. MutableBigInteger q = new MutableBigInteger(),
  1072. r = new MutableBigInteger(),
  1073. a = new MutableBigInteger(this.mag),
  1074. b = new MutableBigInteger(val.mag);
  1075. a.divide(b, q, r);
  1076. return new BigInteger(q, this.signum * val.signum);
  1077. }
  1078. /**
  1079. * Returns an array of two BigIntegers containing <tt>(this / val)</tt>
  1080. * followed by <tt>(this % val)</tt>.
  1081. *
  1082. * @param val value by which this BigInteger is to be divided, and the
  1083. * remainder computed.
  1084. * @return an array of two BigIntegers: the quotient <tt>(this / val)</tt>
  1085. * is the initial element, and the remainder <tt>(this % val)</tt>
  1086. * is the final element.
  1087. * @throws ArithmeticException <tt>val==0</tt>
  1088. */
  1089. public BigInteger[] divideAndRemainder(BigInteger val) {
  1090. BigInteger[] result = new BigInteger[2];
  1091. MutableBigInteger q = new MutableBigInteger(),
  1092. r = new MutableBigInteger(),
  1093. a = new MutableBigInteger(this.mag),
  1094. b = new MutableBigInteger(val.mag);
  1095. a.divide(b, q, r);
  1096. result[0] = new BigInteger(q, this.signum * val.signum);
  1097. result[1] = new BigInteger(r, this.signum);
  1098. return result;
  1099. }
  1100. /**
  1101. * Returns a BigInteger whose value is <tt>(this % val)</tt>.
  1102. *
  1103. * @param val value by which this BigInteger is to be divided, and the
  1104. * remainder computed.
  1105. * @return <tt>this % val</tt>
  1106. * @throws ArithmeticException <tt>val==0</tt>
  1107. */
  1108. public BigInteger remainder(BigInteger val) {
  1109. MutableBigInteger q = new MutableBigInteger(),
  1110. r = new MutableBigInteger(),
  1111. a = new MutableBigInteger(this.mag),
  1112. b = new MutableBigInteger(val.mag);
  1113. a.divide(b, q, r);
  1114. return new BigInteger(r, this.signum);
  1115. }
  1116. /**
  1117. * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>.
  1118. * Note that <tt>exponent</tt> is an integer rather than a BigInteger.
  1119. *
  1120. * @param exponent exponent to which this BigInteger is to be raised.
  1121. * @return <tt>this<sup>exponent</sup></tt>
  1122. * @throws ArithmeticException <tt>exponent</tt> is negative. (This would
  1123. * cause the operation to yield a non-integer value.)
  1124. */
  1125. public BigInteger pow(int exponent) {
  1126. if (exponent < 0)
  1127. throw new ArithmeticException("Negative exponent");
  1128. if (signum==0)
  1129. return (exponent==0 ? ONE : this);
  1130. // Perform exponentiation using repeated squaring trick
  1131. int newSign = (signum<0 && (exponent&1)==1 ? -1 : 1);
  1132. int[] baseToPow2 = this.mag;
  1133. int[] result = {1};
  1134. while (exponent != 0) {
  1135. if ((exponent & 1)==1) {
  1136. result = multiplyToLen(result, result.length,
  1137. baseToPow2, baseToPow2.length, null);
  1138. result = trustedStripLeadingZeroInts(result);
  1139. }
  1140. if ((exponent >>>= 1) != 0) {
  1141. baseToPow2 = squareToLen(baseToPow2, baseToPow2.length, null);
  1142. baseToPow2 = trustedStripLeadingZeroInts(baseToPow2);
  1143. }
  1144. }
  1145. return new BigInteger(result, newSign);
  1146. }
  1147. /**
  1148. * Returns a BigInteger whose value is the greatest common divisor of
  1149. * <tt>abs(this)</tt> and <tt>abs(val)</tt>. Returns 0 if
  1150. * <tt>this==0 && val==0</tt>.
  1151. *
  1152. * @param val value with with the GCD is to be computed.
  1153. * @return <tt>GCD(abs(this), abs(val))</tt>
  1154. */
  1155. public BigInteger gcd(BigInteger val) {
  1156. if (val.signum == 0)
  1157. return this.abs();
  1158. else if (this.signum == 0)
  1159. return val.abs();
  1160. MutableBigInteger a = new MutableBigInteger(this);
  1161. MutableBigInteger b = new MutableBigInteger(val);
  1162. MutableBigInteger result = a.hybridGCD(b);
  1163. return new BigInteger(result, 1);
  1164. }
  1165. /**
  1166. * Left shift int array a up to len by n bits. Returns the array that
  1167. * results from the shift since space may have to be reallocated.
  1168. */
  1169. private static int[] leftShift(int[] a, int len, int n) {
  1170. int nInts = n >>> 5;
  1171. int nBits = n&0x1F;
  1172. int bitsInHighWord = bitLen(a[0]);
  1173. // If shift can be done without recopy, do so
  1174. if (n <= (32-bitsInHighWord)) {
  1175. primitiveLeftShift(a, len, nBits);
  1176. return a;
  1177. } else { // Array must be resized
  1178. if (nBits <= (32-bitsInHighWord)) {
  1179. int result[] = new int[nInts+len];
  1180. for (int i=0; i<len; i++)
  1181. result[i] = a[i];
  1182. primitiveLeftShift(result, result.length, nBits);
  1183. return result;
  1184. } else {
  1185. int result[] = new int[nInts+len+1];
  1186. for (int i=0; i<len; i++)
  1187. result[i] = a[i];
  1188. primitiveRightShift(result, result.length, 32 - nBits);
  1189. return result;
  1190. }
  1191. }
  1192. }
  1193. // shifts a up to len right n bits assumes no leading zeros, 0<n<32
  1194. static void primitiveRightShift(int[] a, int len, int n) {
  1195. int n2 = 32 - n;
  1196. for (int i=len-1, c=a[i]; i>0; i--) {
  1197. int b = c;
  1198. c = a[i-1];
  1199. a[i] = (c << n2) | (b >>> n);
  1200. }
  1201. a[0] >>>= n;
  1202. }
  1203. // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
  1204. static void primitiveLeftShift(int[] a, int len, int n) {
  1205. if (len == 0 || n == 0)
  1206. return;
  1207. int n2 = 32 - n;
  1208. for (int i=0, c=a[i], m=i+len-1; i<m; i++) {
  1209. int b = c;
  1210. c = a[i+1];
  1211. a[i] = (b << n) | (c >>> n2);
  1212. }
  1213. a[len-1] <<= n;
  1214. }
  1215. /**
  1216. * Calculate bitlength of contents of the first len elements an int array,
  1217. * assuming there are no leading zero ints.
  1218. */
  1219. private static int bitLength(int[] val, int len) {
  1220. if (len==0)
  1221. return 0;
  1222. return ((len-1)<<5) + bitLen(val[0]);
  1223. }
  1224. /**
  1225. * Returns a BigInteger whose value is the absolute value of this
  1226. * BigInteger.
  1227. *
  1228. * @return <tt>abs(this)</tt>
  1229. */
  1230. public BigInteger abs() {
  1231. return (signum >= 0 ? this : this.negate());
  1232. }
  1233. /**
  1234. * Returns a BigInteger whose value is <tt>(-this)</tt>.
  1235. *
  1236. * @return <tt>-this</tt>
  1237. */
  1238. public BigInteger negate() {
  1239. return new BigInteger(this.mag, -this.signum);
  1240. }
  1241. /**
  1242. * Returns the signum function of this BigInteger.
  1243. *
  1244. * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or
  1245. * positive.
  1246. */
  1247. public int signum() {
  1248. return this.signum;
  1249. }
  1250. // Modular Arithmetic Operations
  1251. /**
  1252. * Returns a BigInteger whose value is <tt>(this mod m</tt>). This method
  1253. * differs from <tt>remainder</tt> in that it always returns a
  1254. * <i>non-negative</i> BigInteger.
  1255. *
  1256. * @param m the modulus.
  1257. * @return <tt>this mod m</tt>
  1258. * @throws ArithmeticException <tt>m <= 0</tt>
  1259. * @see #remainder
  1260. */
  1261. public BigInteger mod(BigInteger m) {
  1262. if (m.signum <= 0)
  1263. throw new ArithmeticException("BigInteger: modulus not positive");
  1264. BigInteger result = this.remainder(m);
  1265. return (result.signum >= 0 ? result : result.add(m));
  1266. }
  1267. /**
  1268. * Returns a BigInteger whose value is
  1269. * <tt>(this<sup>exponent</sup> mod m)</tt>. (Unlike <tt>pow</tt>, this
  1270. * method permits negative exponents.)
  1271. *
  1272. * @param exponent the exponent.
  1273. * @param m the modulus.
  1274. * @return <tt>this<sup>exponent</sup> mod m</tt>
  1275. * @throws ArithmeticException <tt>m <= 0</tt>
  1276. * @see #modInverse
  1277. */
  1278. public BigInteger modPow(BigInteger exponent, BigInteger m) {
  1279. if (m.signum <= 0)
  1280. throw new ArithmeticException("BigInteger: modulus not positive");
  1281. // Trivial cases
  1282. if (exponent.signum == 0)
  1283. return (m.equals(ONE) ? ZERO : ONE);
  1284. if (this.equals(ONE))
  1285. return (m.equals(ONE) ? ZERO : ONE);
  1286. if (this.equals(ZERO) && exponent.signum >= 0)
  1287. return ZERO;
  1288. if (this.equals(negConst[1]) && (!exponent.testBit(0)))
  1289. return (m.equals(ONE) ? ZERO : ONE);
  1290. boolean invertResult;
  1291. if ((invertResult = (exponent.signum < 0)))
  1292. exponent = exponent.negate();
  1293. BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
  1294. ? this.mod(m) : this);
  1295. BigInteger result;
  1296. if (m.testBit(0)) { // odd modulus
  1297. result = base.oddModPow(exponent, m);
  1298. } else {
  1299. /*
  1300. * Even modulus. Tear it into an "odd part" (m1) and power of two
  1301. * (m2), exponentiate mod m1, manually exponentiate mod m2, and
  1302. * use Chinese Remainder Theorem to combine results.
  1303. */
  1304. // Tear m apart into odd part (m1) and power of 2 (m2)
  1305. int p = m.getLowestSetBit(); // Max pow of 2 that divides m
  1306. BigInteger m1 = m.shiftRight(p); // m/2**p
  1307. BigInteger m2 = ONE.shiftLeft(p); // 2**p
  1308. // Calculate new base from m1
  1309. BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0
  1310. ? this.mod(m1) : this);
  1311. // Caculate (base ** exponent) mod m1.
  1312. BigInteger a1 = (m1.equals(ONE) ? ZERO :
  1313. base2.oddModPow(exponent, m1));
  1314. // Calculate (this ** exponent) mod m2
  1315. BigInteger a2 = base.modPow2(exponent, p);
  1316. // Combine results using Chinese Remainder Theorem
  1317. BigInteger y1 = m2.modInverse(m1);
  1318. BigInteger y2 = m1.modInverse(m2);
  1319. result = a1.multiply(m2).multiply(y1).add
  1320. (a2.multiply(m1).multiply(y2)).mod(m);
  1321. }
  1322. return (invertResult ? result.modInverse(m) : result);
  1323. }
  1324. static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,
  1325. Integer.MAX_VALUE}; // Sentinel
  1326. /**
  1327. * Returns a BigInteger whose value is x to the power of y mod z.
  1328. * Assumes: z is odd && x < z.
  1329. */
  1330. private BigInteger oddModPow(BigInteger y, BigInteger z) {
  1331. /*
  1332. * The algorithm is adapted from Colin Plumb's C library.
  1333. *
  1334. * The window algorithm:
  1335. * The idea is to keep a running product of b1 = n^(high-order bits of exp)
  1336. * and then keep appending exponent bits to it. The following patterns
  1337. * apply to a 3-bit window (k = 3):
  1338. * To append 0: square
  1339. * To append 1: square, multiply by n^1
  1340. * To append 10: square, multiply by n^1, square
  1341. * To append 11: square, square, multiply by n^3
  1342. * To append 100: square, multiply by n^1, square, square
  1343. * To append 101: square, square, square, multiply by n^5
  1344. * To append 110: square, square, multiply by n^3, square
  1345. * To append 111: square, square, square, multiply by n^7
  1346. *
  1347. * Since each pattern involves only one multiply, the longer the pattern
  1348. * the better, except that a 0 (no multiplies) can be appended directly.
  1349. * We precompute a table of odd powers of n, up to 2^k, and can then
  1350. * multiply k bits of exponent at a time. Actually, assuming random
  1351. * exponents, there is on average one zero bit between needs to
  1352. * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
  1353. * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so
  1354. * you have to do one multiply per k+1 bits of exponent.
  1355. *
  1356. * The loop walks down the exponent, squaring the result buffer as
  1357. * it goes. There is a wbits+1 bit lookahead buffer, buf, that is
  1358. * filled with the upcoming exponent bits. (What is read after the
  1359. * end of the exponent is unimportant, but it is filled with zero here.)
  1360. * When the most-significant bit of this buffer becomes set, i.e.
  1361. * (buf & tblmask) != 0, we have to decide what pattern to multiply
  1362. * by, and when to do it. We decide, remember to do it in future
  1363. * after a suitable number of squari