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