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 t