1. /*
  2. * @(#)BigInteger.java 1.27 01/11/29
  3. *
  4. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.math;
  8. import java.util.Random;
  9. /**
  10. * Immutable arbitrary-precision integers. All operations behave as if
  11. * BigIntegers were represented in two's-complement notation (like Java's
  12. * primitive integer types). BigInteger provides analogues to all of Java's
  13. * primitive integer operators, and all relevant methods from java.lang.Math.
  14. * Additionally, BigInteger provides operations for modular arithmetic, GCD
  15. * calculation, primality testing, prime generation, bit manipulation,
  16. * and a few other miscellaneous operations.
  17. * <p>
  18. * Semantics of arithmetic operations exactly mimic those of Java's integer
  19. * arithmetic operators, as defined in <i>The Java Language Specification</i>.
  20. * For example, division by zero throws an <tt>ArithmeticException</tt>, and
  21. * division of a negative by a positive yields a negative (or zero) remainder.
  22. * All of the details in the Spec concerning overflow are ignored, as
  23. * BigIntegers are made as large as necessary to accommodate the results of an
  24. * operation.
  25. * <p>
  26. * Semantics of shift operations extend those of Java's shift operators
  27. * to allow for negative shift distances. A right-shift with a negative
  28. * shift distance results in a left shift, and vice-versa. The unsigned
  29. * right shift operator (>>>) is omitted, as this operation makes
  30. * little sense in combination with the "infinite word size" abstraction
  31. * provided by this class.
  32. * <p>
  33. * Semantics of bitwise logical operations exactly mimic those of Java's
  34. * bitwise integer operators. The binary operators (<tt>and</tt>,
  35. * <tt>or</tt>, <tt>xor</tt>) implicitly perform sign extension on the shorter
  36. * of the two operands prior to performing the operation.
  37. * <p>
  38. * Comparison operations perform signed integer comparisons, analogous to
  39. * those performed by Java's relational and equality operators.
  40. * <p>
  41. * Modular arithmetic operations are provided to compute residues, perform
  42. * exponentiation, and compute multiplicative inverses. These methods always
  43. * return a non-negative result, between <tt>0</tt> and <tt>(modulus - 1)</tt>,
  44. * inclusive.
  45. * <p>
  46. * Bit operations operate on a single bit of the two's-complement
  47. * representation of their operand. If necessary, the operand is sign-
  48. * extended so that it contains the designated bit. None of the single-bit
  49. * operations can produce a BigInteger with a different sign from the
  50. * BigInteger being operated on, as they affect only a single bit, and the
  51. * "infinite word size" abstraction provided by this class ensures that there
  52. * are infinitely many "virtual sign bits" preceding each BigInteger.
  53. * <p>
  54. * For the sake of brevity and clarity, pseudo-code is used throughout the
  55. * descriptions of BigInteger methods. The pseudo-code expression
  56. * <tt>(i + j)</tt> is shorthand for "a BigInteger whose value is
  57. * that of the BigInteger <tt>i</tt> plus that of the BigInteger <tt>j</tt>."
  58. * The pseudo-code expression <tt>(i == j)</tt> is shorthand for
  59. * "<tt>true</tt> if and only if the BigInteger <tt>i</tt> represents the same
  60. * value as the the BigInteger <tt>j</tt>." Other pseudo-code expressions are
  61. * interpreted similarly.
  62. *
  63. * @see BigDecimal
  64. * @version 1.27, 02/10/07
  65. * @author Josh Bloch
  66. * @since JDK1.1
  67. */
  68. public class BigInteger extends Number implements Comparable {
  69. /**
  70. * The signum of this BigInteger: -1 for negative, 0 for zero, or
  71. * 1 for positive. Note that the BigInteger zero <i>must</i> have
  72. * a signum of 0. This is necessary to ensures that there is exactly one
  73. * representation for each BigInteger value.
  74. *
  75. * @serial
  76. */
  77. private int signum;
  78. /**
  79. * The magnitude of this BigInteger, in <i>big-endian</i> byte-order: the
  80. * zeroth element of this array is the most-significant byte of the
  81. * magnitude. The magnitude must be "minimal" in that the most-significant
  82. * byte (<tt>magnitude[0]</tt>) must be non-zero. This is necessary to
  83. * ensure that there is exactly one representation for each BigInteger
  84. * value. Note that this implies that the BigInteger zero has a
  85. * zero-length magnitude array.
  86. *
  87. * @serial
  88. */
  89. private byte[] magnitude;
  90. // These "redundant fields" are initialized with recognizable nonsense
  91. // values, and cached the first time they are needed (or never, if they
  92. // aren't needed).
  93. /**
  94. * The bitCount of this BigInteger, as returned by bitCount(), or -1
  95. * (either value is acceptable).
  96. *
  97. * @serial
  98. * @see #bitCount
  99. */
  100. private int bitCount = -1;
  101. /**
  102. * The bitLength of this BigInteger, as returned by bitLength(), or -1
  103. * (either value is acceptable).
  104. *
  105. * @serial
  106. * @see #bitLength
  107. */
  108. private int bitLength = -1;
  109. /**
  110. * The lowest set bit of this BigInteger, as returned by getLowestSetBit(),
  111. * or -2 (either value is acceptable).
  112. *
  113. * @serial
  114. * @see #getLowestSetBit
  115. */
  116. private int lowestSetBit = -2;
  117. /**
  118. * The byte-number of the lowest-order nonzero byte in the magnitude of
  119. * this BigInteger, or -2 (either value is acceptable). The least
  120. * significant byte has byte-number 0, the next byte in order of
  121. * increasing significance has byte-number 1, and so forth.
  122. *
  123. * @serial
  124. */
  125. private int firstNonzeroByteNum = -2; // Only used for negative numbers
  126. //Constructors
  127. /**
  128. * Translates a byte array containing the two's-complement binary
  129. * representation of a BigInteger into a BigInteger. The input array is
  130. * assumed to be in <i>big-endian</i> byte-order: the most significant
  131. * byte is in the zeroth element.
  132. *
  133. * @param val big-endian two's-complement binary representation of
  134. * BigInteger.
  135. * @throws NumberFormatException <tt>val</tt> is zero bytes long.
  136. */
  137. public BigInteger(byte[] val) {
  138. if (val.length == 0)
  139. throw new NumberFormatException("Zero length BigInteger");
  140. if (val[0] < 0) {
  141. magnitude = makePositive(val);
  142. signum = -1;
  143. } else {
  144. magnitude = stripLeadingZeroBytes(val);
  145. signum = (magnitude.length == 0 ? 0 : 1);
  146. }
  147. }
  148. /**
  149. * Translates the sign-magnitude representation of a BigInteger into a
  150. * BigInteger. The sign is represented as an integer signum value: -1 for
  151. * negative, 0 for zero, or 1 for positive. The magnitude is a byte array
  152. * in <i>big-endian</i> byte-order: the most significant byte is in the
  153. * zeroth element. A zero-length magnitude array is permissible, and will
  154. * result in in a BigInteger value of 0, whether signum is -1, 0 or 1.
  155. *
  156. * @param signum signum of the number (-1 for negative, 0 for zero, 1
  157. * for positive).
  158. * @param magnitude big-endian binary representation of the magnitude of
  159. * the number.
  160. * @throws NumberFormatException <tt>signum</tt> is not one of the three
  161. * legal values (-1, 0, and 1), or <tt>signum</tt> is 0 and
  162. * <tt>magnitude</tt> contains one or more non-zero bytes.
  163. */
  164. public BigInteger(int signum, byte[] magnitude) {
  165. this.magnitude = stripLeadingZeroBytes(magnitude);
  166. if (signum < -1 || signum > 1)
  167. throw(new NumberFormatException("Invalid signum value"));
  168. if (this.magnitude.length==0) {
  169. this.signum = 0;
  170. } else {
  171. if (signum == 0)
  172. throw(new NumberFormatException("signum-magnitude mismatch"));
  173. this.signum = signum;
  174. }
  175. }
  176. /**
  177. * Translates the String representation of a BigInteger in the specified
  178. * radix into a BigInteger. The String representation consists of an
  179. * optional minus sign followed by a sequence of one or more digits in the
  180. * specified radix. The character-to-digit mapping is provided by
  181. * <tt>Character.digit</tt>. The String may not contain any extraneous
  182. * characters (whitespace, for example).
  183. *
  184. * @param val String representation of BigInteger.
  185. * @param radix radix to be used in interpreting <tt>val</tt>.
  186. * @throws NumberFormatException <tt>val</tt> is not a valid representation
  187. * of a BigInteger in the specified radix, or <tt>radix</tt> is
  188. * outside the range from <tt>Character.MIN_RADIX</tt> (2) to
  189. * <tt>Character.MAX_RADIX</tt> (36), inclusive.
  190. * @see Character#digit
  191. */
  192. public BigInteger(String val, int radix) {
  193. int cursor = 0, numDigits;
  194. if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  195. throw new NumberFormatException("Radix out of range");
  196. if (val.length() == 0)
  197. throw new NumberFormatException("Zero length BigInteger");
  198. // Check for leading minus sign
  199. signum = 1;
  200. if (val.charAt(0) == '-') {
  201. if (val.length() == 1)
  202. throw new NumberFormatException("Zero length BigInteger");
  203. signum = -1;
  204. cursor = 1;
  205. }
  206. // Skip leading zeros and compute number of digits in magnitude
  207. while (cursor<val.length() &&
  208. Character.digit(val.charAt(cursor),radix) == 0)
  209. cursor++;
  210. if (cursor==val.length()) {
  211. signum = 0;
  212. magnitude = new byte[0];
  213. return;
  214. } else {
  215. numDigits = val.length() - cursor;
  216. }
  217. // Process first (potentially short) digit group, if necessary
  218. int firstGroupLen = numDigits % digitsPerLong[radix];
  219. if (firstGroupLen == 0)
  220. firstGroupLen = digitsPerLong[radix];
  221. String group = val.substring(cursor, cursor += firstGroupLen);
  222. BigInteger tmp = valueOf(Long.parseLong(group, radix));
  223. // Process remaining digit groups
  224. while (cursor < val.length()) {
  225. group = val.substring(cursor, cursor += digitsPerLong[radix]);
  226. long groupVal = Long.parseLong(group, radix);
  227. if (groupVal <0)
  228. throw new NumberFormatException("Illegal digit");
  229. tmp = tmp.multiply(longRadix[radix]).add(valueOf(groupVal));
  230. }
  231. magnitude = tmp.magnitude;
  232. }
  233. /**
  234. * Translates the decimal String representation of a BigInteger into a
  235. * BigInteger. The String representation consists of an optional minus
  236. * sign followed by a sequence of one or more decimal digits. The
  237. * character-to-digit mapping is provided by <tt>Character.digit</tt>.
  238. * The String may not contain any extraneous characters (whitespace, for
  239. * example).
  240. *
  241. * @param val decimal String representation of BigInteger.
  242. * @throws NumberFormatException <tt>val</tt> is not a valid representation
  243. * of a BigInteger.
  244. * @see Character#digit
  245. */
  246. public BigInteger(String val) {
  247. this(val, 10);
  248. }
  249. /**
  250. * Constructs a randomly generated BigInteger, uniformly distributed over
  251. * the range <tt>0</tt> to <tt>(2<sup>numBits</sup> - 1)</tt>, inclusive.
  252. * The uniformity of the distribution assumes that a fair source of random
  253. * bits is provided in <tt>rnd</tt>. Note that this constructor always
  254. * constructs a non-negative BigInteger.
  255. *
  256. * @param numBits maximum bitLength of the new BigInteger.
  257. * @param rnd source of randomness to be used in computing the new
  258. * BigInteger.
  259. * @throws IllegalArgumentException <tt>numBits</tt> is negative.
  260. * @see #bitLength
  261. */
  262. public BigInteger(int numBits, Random rnd) {
  263. this(1, randomBits(numBits, rnd));
  264. }
  265. private static byte[] randomBits(int numBits, Random rnd) {
  266. if (numBits < 0)
  267. throw new IllegalArgumentException("numBits must be non-negative");
  268. int numBytes = (numBits+7)/8;
  269. byte[] randomBits = new byte[numBytes];
  270. // Generate random bytes and mask out any excess bits
  271. if (numBytes > 0) {
  272. rnd.nextBytes(randomBits);
  273. int excessBits = 8*numBytes - numBits;
  274. randomBits[0] &= (1 << (8-excessBits)) - 1;
  275. }
  276. return randomBits;
  277. }
  278. /**
  279. * Constructs a randomly generated positive BigInteger that is probably
  280. * prime, with the specified bitLength.
  281. *
  282. * @param bitLength bitLength of the returned BigInteger.
  283. * @param certainty a measure of the uncertainty that the caller is
  284. * willing to tolerate. The probability that the new BigInteger
  285. * represents a prime number will exceed
  286. * <tt>(1 - 1/2<sup>certainty</sup></tt>). The execution time of
  287. * this constructor is proportional to the value of this parameter.
  288. * @param rnd source of random bits used to select candidates to be
  289. * tested for primality.
  290. * @throws ArithmeticException <tt>bitLength < 2</tt>.
  291. * @see #bitLength
  292. */
  293. public BigInteger(int bitLength, int certainty, Random rnd) {
  294. if (bitLength < 2)
  295. throw new ArithmeticException("bitLength < 2");
  296. BigInteger p;
  297. do {
  298. // Select a candidate of exactly the right length. Note that
  299. // Plumb's generator doesn't handle bitLength<=16 properly.
  300. do {
  301. p = new BigInteger(bitLength-1, rnd).setBit(bitLength-1);
  302. p = (bitLength <= 16
  303. ? (bitLength > 2 ? p.setBit(0) : p)
  304. : new BigInteger(plumbGeneratePrime(p.magnitude), 1));
  305. } while (p.bitLength() != bitLength);
  306. } while (!p.isProbablePrime(certainty));
  307. signum = 1;
  308. magnitude = p.magnitude;
  309. }
  310. /**
  311. * This private constructor differs from its public cousin
  312. * with the arguments reversed in two ways: it assumes that its
  313. * arguments are correct, and it doesn't copy the magnitude array.
  314. */
  315. private BigInteger(byte[] magnitude, int signum) {
  316. this.signum = (magnitude.length==0 ? 0 : signum);
  317. this.magnitude = magnitude;
  318. }
  319. //Static Factory Methods
  320. /**
  321. * Returns a BigInteger whose value is equal to that of the specified
  322. * long. This "static factory method" is provided in preference to a
  323. * (long) constructor because it allows for reuse of frequently used
  324. * BigIntegers.
  325. *
  326. * @param val value of the BigInteger to return.
  327. * @return a BigInteger with the specified value.
  328. */
  329. public static BigInteger valueOf(long val) {
  330. // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
  331. if (val == 0)
  332. return ZERO;
  333. if (val > 0 && val <= MAX_CONSTANT)
  334. return posConst[(int) val];
  335. else if (val < 0 && val >= -MAX_CONSTANT)
  336. return negConst[(int) -val];
  337. // Dump two's complement binary into valArray
  338. byte valArray[] = new byte[8];
  339. for (int i=0; i<8; i++, val >>= 8)
  340. valArray[7-i] = (byte)val;
  341. return new BigInteger(valArray);
  342. }
  343. /**
  344. * Returns a BigInteger with the given two's complement representation.
  345. * Assumes that the input array will not be modified (the returned
  346. * BigInteger will reference the input array if feasible).
  347. */
  348. private static BigInteger valueOf(byte val[]) {
  349. return (val[0]>0 ? new BigInteger(val, 1) : new BigInteger(val));
  350. }
  351. // Constants
  352. /**
  353. * Initialize static constant array when class is loaded.
  354. */
  355. private final static int MAX_CONSTANT = 16;
  356. private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
  357. private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
  358. static {
  359. for (int i = 1; i <= MAX_CONSTANT; i++) {
  360. byte[] magnitude = new byte[1];
  361. magnitude[0] = (byte) i;
  362. posConst[i] = new BigInteger(magnitude, 1);
  363. negConst[i] = new BigInteger(magnitude, -1);
  364. }
  365. }
  366. /**
  367. * The BigInteger constant zero.
  368. *
  369. * @since JDK1.2
  370. */
  371. public static final BigInteger ZERO = new BigInteger(new byte[0], 0);
  372. /**
  373. * The BigInteger constant one.
  374. *
  375. * @since JDK1.2
  376. */
  377. public static final BigInteger ONE = valueOf(1);
  378. /**
  379. * The BigInteger constant two. (Not exported.)
  380. */
  381. private static final BigInteger TWO = valueOf(2);
  382. // Arithmetic Operations
  383. /**
  384. * Returns a BigInteger whose value is <tt>(this + val)</tt>.
  385. *
  386. * @param val value to be added to this BigInteger.
  387. * @return <tt>this + val</tt>
  388. */
  389. public BigInteger add(BigInteger val) {
  390. if (val.signum == 0)
  391. return this;
  392. else if (this.signum == 0)
  393. return val;
  394. else if (val.signum == signum)
  395. return new BigInteger(plumbAdd(magnitude, val.magnitude), signum);
  396. else if (this.signum < 0)
  397. return plumbSubtract(val.magnitude, magnitude);
  398. else // val.signum < 0
  399. return plumbSubtract(magnitude, val.magnitude);
  400. }
  401. /**
  402. * Returns a BigInteger whose value is <tt>(this - val)</tt>.
  403. *
  404. * @param val value to be subtracted from this BigInteger.
  405. * @return <tt>this - val</tt>
  406. */
  407. public BigInteger subtract(BigInteger val) {
  408. return add(new BigInteger(val.magnitude, -val.signum));
  409. }
  410. /**
  411. * Returns a BigInteger whose value is <tt>(this * val)</tt>.
  412. *
  413. * @param val value to be multiplied by this BigInteger.
  414. * @return <tt>this * val</tt>
  415. */
  416. public BigInteger multiply(BigInteger val) {
  417. if (val.signum == 0 || this.signum==0)
  418. return ZERO;
  419. else
  420. return new BigInteger(plumbMultiply(magnitude, val.magnitude),
  421. signum * val.signum);
  422. }
  423. /**
  424. * Returns a BigInteger whose value is <tt>(this / val)</tt>.
  425. *
  426. * @param val value by which this BigInteger is to be divided.
  427. * @return <tt>this / val</tt>
  428. * @throws ArithmeticException <tt>val==0</tt>
  429. */
  430. public BigInteger divide(BigInteger val) {
  431. if (val.signum == 0)
  432. throw new ArithmeticException("BigInteger divide by zero");
  433. else if (this.signum == 0)
  434. return ZERO;
  435. else
  436. return new BigInteger(plumbDivide(magnitude, val.magnitude),
  437. signum * val.signum);
  438. }
  439. /**
  440. * Returns a BigInteger whose value is <tt>(this % val)</tt>.
  441. *
  442. * @param val value by which this BigInteger is to be divided, and the
  443. * remainder computed.
  444. * @return <tt>this % val</tt>
  445. * @throws ArithmeticException <tt>val==0</tt>
  446. */
  447. public BigInteger remainder(BigInteger val) {
  448. if (val.signum == 0)
  449. throw new ArithmeticException("BigInteger divide by zero");
  450. else if (this.signum == 0)
  451. return ZERO;
  452. else if (this.magnitude.length < val.magnitude.length)
  453. return this; // *** WORKAROUND FOR BUG IN R1.1 OF PLUMB'S PKG ***
  454. else
  455. return new BigInteger(plumbRemainder(magnitude,val.magnitude),
  456. signum);
  457. }
  458. /**
  459. * Returns an array of two BigIntegers containing <tt>(this / val)</tt>
  460. * followed by <tt>(this % val)</tt>.
  461. *
  462. * @param val value by which this BigInteger is to be divided, and the
  463. * remainder computed.
  464. * @return an array of two BigIntegers: the quotient <tt>(this / val)</tt>
  465. * is the initial element, and the remainder <tt>(this % val)</tt>
  466. * is the final element.
  467. * @throws ArithmeticException <tt>val==0</tt>
  468. */
  469. public BigInteger[] divideAndRemainder(BigInteger val) {
  470. BigInteger result[] = new BigInteger[2];
  471. if (val.signum == 0) {
  472. throw new ArithmeticException("BigInteger divide by zero");
  473. } else if (this.signum == 0) {
  474. result[0] = result[1] = ZERO;
  475. } else if (this.magnitude.length < val.magnitude.length) {
  476. // *** WORKAROUND FOR A BUG IN R1.1 OF PLUMB'S PACKAGE ***
  477. result[0] = ZERO;
  478. result[1] = this;
  479. } else {
  480. byte resultMagnitude[][] =
  481. plumbDivideAndRemainder(magnitude, val.magnitude);
  482. result[0] = new BigInteger(resultMagnitude[0], signum*val.signum);
  483. result[1] = new BigInteger(resultMagnitude[1], signum);
  484. }
  485. return result;
  486. }
  487. /**
  488. * Returns a BigInteger whose value is <tt>(this<sup>exponent</sup>)</tt>.
  489. * Returns one if this BigInteger and <tt>exponent</tt> are both zero.
  490. * Note that <tt>exponent</tt> is an integer rather than a BigInteger.
  491. *
  492. * @param exponent exponent to which this BigInteger is to be raised.
  493. * @return <tt>this<sup>exponent</sup></tt>
  494. * @throws ArithmeticException <tt>exponent</tt> is negative. (This would
  495. * cause the operation to yield a non-integer value.)
  496. */
  497. public BigInteger pow(int exponent) {
  498. if (exponent < 0)
  499. throw new ArithmeticException("Negative exponent");
  500. if (signum==0)
  501. return (exponent==0 ? ONE : this);
  502. /* Perform exponentiation using repeated squaring trick */
  503. BigInteger result = valueOf(exponent<0 && (exponent&1)==1 ? -1 : 1);
  504. BigInteger baseToPow2 = this;
  505. while (exponent != 0) {
  506. if ((exponent & 1)==1)
  507. result = result.multiply(baseToPow2);
  508. if ((exponent >>= 1) != 0)
  509. baseToPow2 = new BigInteger(
  510. plumbSquare(baseToPow2.magnitude), 1);
  511. }
  512. return result;
  513. }
  514. /**
  515. * Returns a BigInteger whose value is the greatest common divisor of
  516. * <tt>abs(this)</tt> and <tt>abs(val)</tt>. Returns 0 if
  517. * <tt>this==0 && val==0</tt>.
  518. *
  519. * @param val value with with the GCD is to be computed.
  520. * @return <tt>GCD(abs(this), abs(val))</tt>
  521. */
  522. public BigInteger gcd(BigInteger val) {
  523. if (val.signum == 0)
  524. return this.abs();
  525. else if (this.signum == 0)
  526. return val.abs();
  527. else
  528. return new BigInteger(plumbGcd(magnitude, val.magnitude), 1);
  529. }
  530. /**
  531. * Returns a BigInteger whose value is the absolute value of this
  532. * BigInteger.
  533. *
  534. * @return <tt>abs(this)</tt>
  535. */
  536. public BigInteger abs() {
  537. return (signum >= 0 ? this : this.negate());
  538. }
  539. /**
  540. * Returns a BigInteger whose value is <tt>(-this)</tt>.
  541. *
  542. * @return <tt>-this</tt>
  543. */
  544. public BigInteger negate() {
  545. return new BigInteger(this.magnitude, -this.signum);
  546. }
  547. /**
  548. * Returns the signum function of this BigInteger.
  549. *
  550. * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or
  551. * positive.
  552. */
  553. public int signum() {
  554. return this.signum;
  555. }
  556. // Modular Arithmetic Operations
  557. /**
  558. * Returns a BigInteger whose value is <tt>(this mod m</tt>). This method
  559. * differs from <tt>remainder</tt> in that it always returns a
  560. * <i>positive</i> BigInteger.
  561. *
  562. * @param m the modulus.
  563. * @return <tt>this mod m</tt>
  564. * @throws ArithmeticException <tt>m <= 0</tt>
  565. * @see #remainder
  566. */
  567. public BigInteger mod(BigInteger m) {
  568. if (m.signum <= 0)
  569. throw new ArithmeticException("BigInteger: modulus not positive");
  570. BigInteger result = this.remainder(m);
  571. return (result.signum >= 0 ? result : result.add(m));
  572. }
  573. /**
  574. * Returns a BigInteger whose value is
  575. * <tt>(this<sup>exponent</sup> mod m)</tt>. (Unlike <tt>pow</tt>, this
  576. * method permits negative exponents.)
  577. *
  578. * @param exponent the exponent.
  579. * @param m the modulus.
  580. * @return <tt>this<sup>exponent</sup> mod m</tt>
  581. * @throws ArithmeticException <tt>m <= 0</tt>
  582. * @see #modInverse
  583. */
  584. public BigInteger modPow(BigInteger exponent, BigInteger m) {
  585. if (m.signum <= 0)
  586. throw new ArithmeticException("BigInteger: modulus not positive");
  587. /* Workaround for a bug in Plumb: x^0 (y) dumps core for x != 0 */
  588. if (exponent.signum == 0)
  589. return (m.equals(ONE) ? ZERO : ONE);
  590. boolean invertResult;
  591. if ((invertResult = (exponent.signum < 0)))
  592. exponent = exponent.negate();
  593. BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
  594. ? this.mod(m) : this);
  595. BigInteger result;
  596. if (m.testBit(0)) { /* Odd modulus: just pass it on to Plumb */
  597. result = new BigInteger
  598. (plumbModPow(base.magnitude, exponent.magnitude, m.magnitude), 1);
  599. } else {
  600. /*
  601. * Even modulus. Plumb only supports odd, so tear it into
  602. * "odd part" (m1) and power of two (m2), use Plumb to exponentiate
  603. * mod m1, manually exponentiate mod m2, and use Chinese Remainder
  604. * Theorem to combine results.
  605. */
  606. /* Tear m apart into odd part (m1) and power of 2 (m2) */
  607. int p = m.getLowestSetBit(); /* Max pow of 2 that divides m */
  608. BigInteger m1 = m.shiftRight(p); /* m/2**p */
  609. BigInteger m2 = ONE.shiftLeft(p); /* 2**p */
  610. /* Calculate new base from m1 */
  611. BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0
  612. ? this.mod(m1) : this);
  613. /* Caculate (base ** exponent) mod m1.*/
  614. BigInteger a1 = new BigInteger(plumbModPow(base2.magnitude,
  615. exponent.magnitude, m1.magnitude), 1);
  616. /* Caculate (this ** exponent) mod m2 */
  617. BigInteger a2 = base.modPow2(exponent, p);
  618. /* Combine results using Chinese Remainder Theorem */
  619. BigInteger y1 = m2.modInverse(m1);
  620. BigInteger y2 = m1.modInverse(m2);
  621. result = a1.multiply(m2).multiply(y1).add
  622. (a2.multiply(m1).multiply(y2)).mod(m);
  623. }
  624. return (invertResult ? result.modInverse(m) : result);
  625. }
  626. /**
  627. * Returns a BigInteger whose value is (this ** exponent) mod (2**p)
  628. */
  629. private BigInteger modPow2(BigInteger exponent, int p) {
  630. /*
  631. * Perform exponentiation using repeated squaring trick, chopping off
  632. * high order bits as indicated by modulus.
  633. */
  634. BigInteger result = valueOf(1);
  635. BigInteger baseToPow2 = this.mod2(p);
  636. while (exponent.signum != 0) {
  637. if (exponent.testBit(0))
  638. result = result.multiply(baseToPow2).mod2(p);
  639. exponent = exponent.shiftRight(1);
  640. if (exponent.signum != 0)
  641. baseToPow2 = new BigInteger(
  642. plumbSquare(baseToPow2.magnitude), 1).mod2(p);
  643. }
  644. return result;
  645. }
  646. /**
  647. * Returns a BigInteger whose value is this mod(2**p).
  648. * Assumes that this BigInteger >= 0 and p > 0.
  649. */
  650. private BigInteger mod2(int p) {
  651. if (bitLength() <= p)
  652. return this;
  653. /* Copy remaining bytes of magnitude */
  654. int numBytes = (p+7)/8;
  655. byte[] mag = new byte[numBytes];
  656. for (int i=0; i<numBytes; i++)
  657. mag[i] = magnitude[i + (magnitude.length - numBytes)];
  658. /* Mask out any excess bits */
  659. int excessBits = 8*numBytes - p;
  660. mag[0] &= (1 << (8-excessBits)) - 1;
  661. return (mag[0]==0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
  662. }
  663. /**
  664. * Returns a BigInteger whose value is <tt>(this<sup>-1</sup> mod m)</tt>.
  665. *
  666. * @param m the modulus.
  667. * @return <tt>this<sup>-1</sup> mod m</tt>.
  668. * @throws ArithmeticException <tt> m <= 0</tt>, or this BigInteger
  669. * has no multiplicative inverse mod m (that is, this BigInteger
  670. * is not <i>relatively prime</i> to m).
  671. */
  672. public BigInteger modInverse(BigInteger m) {
  673. if (m.signum != 1)
  674. throw new ArithmeticException("BigInteger: modulus not positive");
  675. /* Calculate (this mod m) */
  676. BigInteger modVal = this.remainder(m);
  677. if (modVal.signum < 0)
  678. modVal = modVal.add(m);
  679. if (!modVal.gcd(m).equals(ONE))
  680. throw new ArithmeticException("BigInteger not invertible");
  681. return new BigInteger(plumbModInverse(modVal.magnitude,m.magnitude),1);
  682. }
  683. // Shift Operations
  684. /**
  685. * Returns a BigInteger whose value is <tt>(this << n)</tt>.
  686. * The shift distance, <tt>n</tt>, may be negative, in which case
  687. * this method performs a right shift.
  688. * (Computes <tt>floor(this * 2<sup>n</sup>)</tt>.)
  689. *
  690. * @param n shift distance, in bits.
  691. * @return <tt>this << n</tt>
  692. * @see #shiftRight
  693. */
  694. public BigInteger shiftLeft(int n) {
  695. if (n==0)
  696. return this;
  697. if (n<0)
  698. return shiftRight(-n);
  699. int nBytes = n8;
  700. int nBits = n%8;
  701. byte result[] = new byte[(bitLength()+n)/8+1];
  702. if (nBits == 0) {
  703. for (int i=nBytes; i<result.length; i++)
  704. result[result.length-1-i] = getByte(i-nBytes);
  705. } else {
  706. for (int i=nBytes; i<result.length; i++)
  707. result[result.length-1-i] = (byte)
  708. ((getByte(i-nBytes) << nBits)
  709. | (i==nBytes ? 0
  710. : ((getByte(i-nBytes-1)&0xff) >> (8-nBits))));
  711. }
  712. return valueOf(result);
  713. }
  714. /**
  715. * Returns a BigInteger whose value is <tt>(this >> n)</tt>. Sign
  716. * extension is performed. The shift distance, <tt>n</tt>, may be
  717. * negative, in which case this method performs a left shift.
  718. * (Computes <tt>floor(this / 2<sup>n</sup>)</tt>.)
  719. *
  720. * @param n shift distance, in bits.
  721. * @return <tt>this >> n</tt>
  722. * @see #shiftLeft
  723. */
  724. public BigInteger shiftRight(int n) {
  725. if (n==0)
  726. return this;
  727. if (n<0)
  728. return shiftLeft(-n);
  729. if (n >= bitLength())
  730. return (signum<0 ? valueOf(-1) : ZERO);
  731. int nBytes = n8;
  732. int nBits = n%8;
  733. byte result[] = new byte[(bitLength-n)/8+1];
  734. if (nBits == 0) {
  735. for (int i=0; i<result.length; i++)
  736. result[result.length-1-i] = getByte(nBytes+i);
  737. } else {
  738. for (int i=0; i<result.length; i++)
  739. result[result.length-1-i] = (byte)
  740. ((getByte(nBytes+i+1)<<8 | (getByte(nBytes+i)&0xff)) >> nBits);
  741. }
  742. return valueOf(result);
  743. }
  744. // Bitwise Operations
  745. /**
  746. * Returns a BigInteger whose value is <tt>(this & val)</tt>. (This
  747. * method returns a negative BigInteger if and only if this and val are
  748. * both negative.)
  749. *
  750. * @param val value to be AND'ed with this BigInteger.
  751. * @return <tt>this & val</tt>
  752. */
  753. public BigInteger and(BigInteger val) {
  754. byte[] result = new byte[Math.max(byteLength(), val.byteLength())];
  755. for (int i=0; i<result.length; i++)
  756. result[i] = (byte) (getByte(result.length-i-1)
  757. & val.getByte(result.length-i-1));
  758. return valueOf(result);
  759. }
  760. /**
  761. * Returns a BigInteger whose value is <tt>(this | val)</tt>. (This method
  762. * returns a negative BigInteger if and only if either this or val is
  763. * negative.)
  764. *
  765. * @param val value to be OR'ed with this BigInteger.
  766. * @return <tt>this | val</tt>
  767. */
  768. public BigInteger or(BigInteger val) {
  769. byte[] result = new byte[Math.max(byteLength(), val.byteLength())];
  770. for (int i=0; i<result.length; i++)
  771. result[i] = (byte) (getByte(result.length-i-1)
  772. | val.getByte(result.length-i-1));
  773. return valueOf(result);
  774. }
  775. /**
  776. * Returns a BigInteger whose value is <tt>(this ^ val)</tt>. (This method
  777. * returns a negative BigInteger if and only if exactly one of this and
  778. * val are negative.)
  779. *
  780. * @param val value to be XOR'ed with this BigInteger.
  781. * @return <tt>this ^ val</tt>
  782. */
  783. public BigInteger xor(BigInteger val) {
  784. byte[] result = new byte[Math.max(byteLength(), val.byteLength())];
  785. for (int i=0; i<result.length; i++)
  786. result[i] = (byte) (getByte(result.length-i-1)
  787. ^ val.getByte(result.length-i-1));
  788. return valueOf(result);
  789. }
  790. /**
  791. * Returns a BigInteger whose value is <tt>(~this)</tt>. (This method
  792. * returns a negative value if and only if this BigInteger is
  793. * non-negative.)
  794. *
  795. * @return <tt>~this</tt>
  796. */
  797. public BigInteger not() {
  798. byte[] result = new byte[byteLength()];
  799. for (int i=0; i<result.length; i++)
  800. result[i] = (byte) ~getByte(result.length-i-1);
  801. return valueOf(result);
  802. }
  803. /**
  804. * Returns a BigInteger whose value is <tt>(this & ~val)</tt>. This
  805. * method, which is equivalent to <tt>and(val.not())</tt>, is provided as
  806. * a convenience for masking operations. (This method returns a negative
  807. * BigInteger if and only if <tt>this</tt> is negative and <tt>val</tt> is
  808. * positive.)
  809. *
  810. * @param val value to be complemented and AND'ed with this BigInteger.
  811. * @return <tt>this & ~val</tt>
  812. */
  813. public BigInteger andNot(BigInteger val) {
  814. byte[] result = new byte[Math.max(byteLength(), val.byteLength())];
  815. for (int i=0; i<result.length; i++)
  816. result[i] = (byte) (getByte(result.length-i-1)
  817. & ~val.getByte(result.length-i-1));
  818. return valueOf(result);
  819. }
  820. // Single Bit Operations
  821. /**
  822. * Returns <tt>true</tt> if and only if the designated bit is set.
  823. * (Computes <tt>((this & (1<<n)) != 0)</tt>.)
  824. *
  825. * @param n index of bit to test.
  826. * @return <tt>true</tt> if and only if the designated bit is set.
  827. * @throws ArithmeticException <tt>n</tt> is negative.
  828. */
  829. public boolean testBit(int n) {
  830. if (n<0)
  831. throw new ArithmeticException("Negative bit address");
  832. return (getByte(n8) & (1 << (n%8))) != 0;
  833. }
  834. /**
  835. * Returns a BigInteger whose value is equivalent to this BigInteger
  836. * with the designated bit set. (Computes <tt>(this | (1<<n))</tt>.)
  837. *
  838. * @param n index of bit to set.
  839. * @return <tt>this | (1<<n)</tt>
  840. * @throws ArithmeticException <tt>n</tt> is negative.
  841. */
  842. public BigInteger setBit(int n) {
  843. if (n<0)
  844. throw new ArithmeticException("Negative bit address");
  845. int byteNum = n8;
  846. byte[] result = new byte[Math.max(byteLength(), byteNum+2)];
  847. for (int i=0; i<result.length; i++)
  848. result[result.length-i-1] = getByte(i);
  849. result[result.length-byteNum-1] |= (1 << (n%8));
  850. return valueOf(result);
  851. }
  852. /**
  853. * Returns a BigInteger whose value is equivalent to this BigInteger
  854. * with the designated bit cleared.
  855. * (Computes <tt>(this & ~(1<<n))</tt>.)
  856. *
  857. * @param n index of bit to clear.
  858. * @return <tt>this & ~(1<<n)</tt>
  859. * @throws ArithmeticException <tt>n</tt> is negative.
  860. */
  861. public BigInteger clearBit(int n) {
  862. if (n<0)
  863. throw new ArithmeticException("Negative bit address");
  864. int byteNum = n8;
  865. byte[] result = new byte[Math.max(byteLength(), (n+1)/8+1)];
  866. for (int i=0; i<result.length; i++)
  867. result[result.length-i-1] = getByte(i);
  868. result[result.length-byteNum-1] &= ~(1 << (n%8));
  869. return valueOf(result);
  870. }
  871. /**
  872. * Returns a BigInteger whose value is equivalent to this BigInteger
  873. * with the designated bit flipped.
  874. * (Computes <tt>(this ^ (1<<n))</tt>.)
  875. *
  876. * @param n index of bit to flip.
  877. * @return <tt>this ^ (1<<n)</tt>
  878. * @throws ArithmeticException <tt>n</tt> is negative.
  879. */
  880. public BigInteger flipBit(int n) {
  881. if (n<0)
  882. throw new ArithmeticException("Negative bit address");
  883. int byteNum = n8;
  884. byte[] result = new byte[Math.max(byteLength(), byteNum+2)];
  885. for (int i=0; i<result.length; i++)
  886. result[result.length-i-1] = getByte(i);
  887. result[result.length-byteNum-1] ^= (1 << (n%8));
  888. return valueOf(result);
  889. }
  890. /**
  891. * Returns the index of the rightmost (lowest-order) one bit in this
  892. * BigInteger (the number of zero bits to the right of the rightmost
  893. * one bit). Returns -1 if this BigInteger contains no one bits.
  894. * (Computes <tt>(this==0? -1 : log<sub>2</sub>(this & -this))</tt>.)
  895. *
  896. * @return index of the rightmost one bit in this BigInteger.
  897. */
  898. public int getLowestSetBit() {
  899. /*
  900. * Initialize lowestSetBit field the first time this method is
  901. * executed. This method depends on the atomicity of int modifies;
  902. * without this guarantee, it would have to be synchronized.
  903. */
  904. if (lowestSetBit == -2) {
  905. if (signum == 0) {
  906. lowestSetBit = -1;
  907. } else {
  908. /* Search for lowest order nonzero byte */
  909. int i;
  910. byte b;
  911. for (i=0; (b = getByte(i))==0; i++)
  912. ;
  913. lowestSetBit = 8*i + trailingZeroCnt[b & 0xFF];
  914. }
  915. }
  916. return lowestSetBit;
  917. }
  918. // Miscellaneous Bit Operations
  919. /**
  920. * Returns the number of bits in the minimal two's-complement
  921. * representation of this BigInteger, <i>excluding</i> a sign bit.
  922. * For positive BigIntegers, this is equivalent to the number of bits in
  923. * the ordinary binary representation. (Computes
  924. * <tt>(ceil(log<sub>2</sub>(this < 0 ? -this : this+1)))</tt>.)
  925. *
  926. * @return number of bits in the minimal two's-complement
  927. * representation of this BigInteger, <i>excluding</i> a sign bit.
  928. */
  929. public int bitLength() {
  930. /*
  931. * Initialize bitLength field the first time this method is executed.
  932. * This method depends on the atomicity of int modifies; without
  933. * this guarantee, it would have to be synchronized.
  934. */
  935. if (bitLength == -1) {
  936. if (signum == 0) {
  937. bitLength = 0;
  938. } else {
  939. /* Calculate the bit length of the magnitude */
  940. int magBitLength = 8*(magnitude.length-1)
  941. + bitLen[magnitude[0] & 0xff];
  942. if (signum < 0) {
  943. /* Check if magnitude is a power of two */
  944. boolean pow2 = (bitCnt[magnitude[0]&0xff] == 1);
  945. for(int i=1; i<magnitude.length && pow2; i++)
  946. pow2 = (magnitude[i]==0);
  947. bitLength = (pow2 ? magBitLength-1 : magBitLength);
  948. } else {
  949. bitLength = magBitLength;
  950. }
  951. }
  952. }
  953. return bitLength;
  954. }
  955. /*
  956. * bitLen[i] is the number of bits in the binary representation of i.
  957. */
  958. private final static byte bitLen[] = {
  959. 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  960. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  961. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  962. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  963. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  964. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  965. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  966. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  967. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  968. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  969. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  970. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  971. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  972. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  973. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  974. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8};
  975. /**
  976. * Returns the number of bits in the two's complement representation
  977. * of this BigInteger that differ from its sign bit. This method is
  978. * useful when implementing bit-vector style sets atop BigIntegers.
  979. *
  980. * @return number of bits in the two's complement representation
  981. * of this BigInteger that differ from its sign bit.
  982. */
  983. public int bitCount() {
  984. /*
  985. * Initialize bitCount field the first time this method is executed.
  986. * This method depends on the atomicity of int modifies; without
  987. * this guarantee, it would have to be synchronized.
  988. */
  989. if (bitCount == -1) {
  990. /* Count the bits in the magnitude */
  991. int magBitCount = 0;
  992. for (int i=0; i<magnitude.length; i++)
  993. magBitCount += bitCnt[magnitude[i] & 0xff];
  994. if (signum < 0) {
  995. /* Count the trailing zeros in the magnitude */
  996. int magTrailingZeroCount = 0, j;
  997. for (j=magnitude.length-1; magnitude[j]==0; j--)
  998. magTrailingZeroCount += 8;
  999. magTrailingZeroCount += trailingZeroCnt[magnitude[j] & 0xff];
  1000. bitCount = magBitCount + magTrailingZeroCount - 1;
  1001. } else {
  1002. bitCount = magBitCount;
  1003. }
  1004. }
  1005. return bitCount;
  1006. }
  1007. /*
  1008. * bitCnt[i] is the number of 1 bits in the binary representation of i.
  1009. */
  1010. private final static byte bitCnt[] = {
  1011. 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
  1012. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  1013. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  1014. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1015. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  1016. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1017. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1018. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  1019. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  1020. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1021. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1022. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  1023. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  1024. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  1025. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  1026. 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
  1027. /*
  1028. * trailingZeroCnt[i] is the number of trailing zero bits in the binary
  1029. * representaion of i.
  1030. */
  1031. private final static byte trailingZeroCnt[] = {
  1032. 8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1033. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1034. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1035. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1036. 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1037. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1038. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1039. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1040. 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1041. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1042. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1043. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1044. 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1045. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1046. 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1047. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
  1048. // Primality Testing
  1049. /**
  1050. * Returns <tt>true</tt> if this BigInteger is probably prime,
  1051. * <tt>false</tt> if it's definitely composite.
  1052. *
  1053. * @param certainty a measure of the uncertainty that the caller is
  1054. * willing to tolerate: if the call returns <tt>true</tt>
  1055. * the probability that this BigInteger is prime exceeds
  1056. * <tt>(1 - 1/2<sup>certainty</sup>)</tt>. The execution time of
  1057. * this method is proportional to the value of this parameter.
  1058. * @return <tt>true</tt> if this BigInteger is probably prime,
  1059. * <tt>false</tt> if it's definitely composite.
  1060. */
  1061. public boolean isProbablePrime(int certainty) {
  1062. /*
  1063. * This test is taken from the DSA spec.
  1064. */
  1065. int n = (certainty+1)/2;
  1066. if (n <= 0)
  1067. return true;
  1068. BigInteger w = this.abs();
  1069. if (w.equals(TWO))
  1070. return true;
  1071. if (!w.testBit(0) || w.equals(ONE))
  1072. return false;
  1073. // Find a and m such that m is odd and w == 1 + 2**a * m
  1074. BigInteger m = w.subtract(ONE);
  1075. int a = m.getLowestSetBit();
  1076. m = m.shiftRight(a);
  1077. // Do the tests
  1078. Random rnd = new Random();
  1079. for(int i=0; i<n; i++) {
  1080. /* Generate a uniform random on (1, w) */
  1081. BigInteger b;
  1082. do {
  1083. b = new BigInteger(w.bitLength(), rnd);
  1084. } while (b.compareTo(ONE) <= 0 || b.compareTo(w) >= 0);
  1085. int j = 0;
  1086. BigInteger z = b.modPow(m, w);
  1087. while(!((j==0 && z.equals(ONE)) || z.equals(w.subtract(ONE)))) {
  1088. if (j>0 && z.equals(ONE) || ++j==a)
  1089. return false;
  1090. z = z.modPow(TWO, w);
  1091. }
  1092. }
  1093. return true;
  1094. }
  1095. // Comparison Operations
  1096. /**
  1097. * Compares this BigInteger with the specified BigInteger. This method is
  1098. * provided in preference to individual methods for each of the six
  1099. * boolean comparison operators (<, ==, >, >=, !=, <=). The
  1100. * suggested idiom for performing these comparisons is:
  1101. * <tt>(x.compareTo(y)</tt> <<i>op</i>> <tt>0)</tt>,
  1102. * where <<i>op</i>> is one of the six comparison operators.
  1103. *
  1104. * @param val BigInteger to which this BigInteger is to be compared.
  1105. * @return -1, 0 or 1 as this BigInteger is numerically less than, equal
  1106. * to, or greater than <tt>val</tt>.
  1107. */
  1108. public int compareTo(BigInteger val) {
  1109. return (signum==val.signum
  1110. ? signum*byteArrayCmp(magnitude, val.magnitude)
  1111. : (signum>val.signum ? 1 : -1));
  1112. }
  1113. /**
  1114. * Compares this BigInteger with the specified Object. If the Object is a
  1115. * BigInteger, this method behaves like <tt>compareTo(BigInteger)</tt>.
  1116. * Otherwise, it throws a <tt>ClassCastException</tt> (as BigIntegers are
  1117. * comparable only to other BigIntegers).
  1118. *
  1119. * @param o Object to which this BigInteger is to be compared.
  1120. * @return a negative number, zero, or a positive number as this
  1121. * BigInteger is numerically less than, equal to, or greater
  1122. * than <tt>o</tt>, which must be a BigInteger.
  1123. * @throws ClassCastException <tt>o</tt> is not a BigInteger.
  1124. * @see #compareTo(java.math.BigInteger)
  1125. * @see Comparable
  1126. * @since JDK1.2
  1127. */
  1128. public int compareTo(Object o) {
  1129. return compareTo((BigInteger)o);
  1130. }
  1131. /*
  1132. * Returns -1, 0 or +1 as big-endian unsigned byte array arg1 is
  1133. * less than, equal to, or greater than arg2.
  1134. */
  1135. private static int byteArrayCmp(byte[] arg1, byte[] arg2) {
  1136. if (arg1.length < arg2.length)
  1137. return -1;
  1138. if (arg1.length > arg2.length)
  1139. return 1;
  1140. /* Argument lengths are equal; compare the values */
  1141. for (int i=0; i<arg1.length; i++) {
  1142. int b1 = arg1[i] & 0xff;
  1143. int b2 = arg2[i] & 0xff;
  1144. if (b1 < b2)
  1145. return -1;
  1146. if (b1 > b2)
  1147. return 1;
  1148. }
  1149. return 0;
  1150. }
  1151. /**
  1152. * Compares this BigInteger with the specified Object for equality.
  1153. *
  1154. * @param o Object to which this BigInteger is to be compared.
  1155. * @return <tt>true</tt> if and only if the specified Object is a
  1156. * BigInteger whose value is numerically equal to this BigInteger.
  1157. */
  1158. public boolean equals(Object x) {
  1159. // This test is just an optimization, which may or may not help
  1160. if (x == this)
  1161. return true;
  1162. if (!(x instanceof BigInteger))
  1163. return false;
  1164. BigInteger xInt = (BigInteger) x;
  1165. if (xInt.signum != signum || xInt.magnitude.length != magnitude.length)
  1166. return false;
  1167. for (int i=0; i<magnitude.length; i++)
  1168. if (xInt.magnitude[i] != magnitude[i])
  1169. return false;
  1170. return true;
  1171. }
  1172. /**
  1173. * Returns the minimum of this BigInteger and <tt>val</tt>.
  1174. *
  1175. * @param val value with with the minimum is to be computed.
  1176. * @return the BigInteger whose value is the lesser of this BigInteger and
  1177. * <tt>val</tt>. If they are equal, either may be returned.
  1178. */
  1179. public BigInteger min(BigInteger val) {
  1180. return (compareTo(val)<0 ? this : val);
  1181. }
  1182. /**
  1183. * Returns the maximum of this BigInteger and <tt>val</tt>.
  1184. *
  1185. * @param val value with with the maximum is to be computed.
  1186. * @return the BigInteger whose value is the greater of this and
  1187. * <tt>val</tt>. If they are equal, either may be returned.
  1188. */
  1189. public BigInteger max(BigInteger val) {
  1190. return (compareTo(val)>0 ? this : val);
  1191. }
  1192. // Hash Function
  1193. /**
  1194. * Returns the hash code for this BigInteger.
  1195. *
  1196. * @return hash code for this BigInteger.
  1197. */
  1198. public int hashCode() {
  1199. int hashCode = 0;
  1200. for (int i=0; i<magnitude.length; i++)
  1201. hashCode = 31*hashCode + (magnitude[i] & 0xff);
  1202. return hashCode * signum;
  1203. }
  1204. // Format Converters
  1205. /**
  1206. * Returns the String representation of this BigInteger in the given radix.
  1207. * If the radix is outside the range from <tt>Character.MIN_RADIX</tt> (2)
  1208. * to <tt>Character.MAX_RADIX</tt> (36) inclusive, it will default to 10
  1209. * (as is the case for <tt>Integer.toString</tt>). The digit-to-character
  1210. * mapping provided by <tt>Character.forDigit</tt> is used, and a minus
  1211. * sign is prepended if appropriate. (This representation is compatible
  1212. * with the (String, int) constructor.)
  1213. *
  1214. * @param radix radix of the String representation.
  1215. * @return String representation of this BigInteger in the given radix.
  1216. * @see Integer#toString
  1217. * @see Character#forDigit
  1218. * @see #BigInteger(java.lang.String, int)
  1219. */
  1220. public String toString(int radix) {
  1221. if (signum == 0)
  1222. return "0";
  1223. if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  1224. radix = 10;
  1225. /* Compute upper bound on number of digit groups and allocate space */
  1226. int maxNumDigitGroups = (magnitude.length + 6)/7;
  1227. String digitGroup[] = new String[maxNumDigitGroups];
  1228. /* Translate number to string, a digit group at a time */
  1229. BigInteger tmp = this.abs();
  1230. int numGroups = 0;
  1231. while (tmp.signum != 0) {
  1232. BigInteger b[] = tmp.divideAndRemainder(longRadix[radix]);
  1233. digitGroup[numGroups++] = Long.toString(b[1].longValue(), radix);
  1234. tmp = b[0];
  1235. }
  1236. /* Put sign (if any) and first digit group into result buffer */
  1237. StringBuffer buf = new StringBuffer(numGroups*digitsPerLong[radix]+1);
  1238. if (signum<0)
  1239. buf.append('-');
  1240. buf.append(digitGroup[numGroups-1]);
  1241. /* Append remaining digit groups padded with leading zeros */
  1242. for (int i=numGroups-2; i>=0; i--) {
  1243. /* Prepend (any) leading zeros for this digit group */
  1244. int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
  1245. if (numLeadingZeros != 0)
  1246. buf.append(zeros[numLeadingZeros]);
  1247. buf.append(digitGroup[i]);
  1248. }
  1249. return buf.toString();
  1250. }
  1251. /* zero[i] is a string of i consecutive zeros. */
  1252. private static String zeros[] = new String[64];
  1253. static {
  1254. zeros[63] =
  1255. "000000000000000000000000000000000000000000000000000000000000000";
  1256. for (int i=0; i<63; i++)
  1257. zeros[i] = zeros[63].substring(0, i);
  1258. }
  1259. /**
  1260. * Returns the decimal String representation of this BigInteger. The
  1261. * digit-to-character mapping provided by <tt>Character.forDigit</tt> is
  1262. * used, and a minus sign is prepended if appropriate. (This
  1263. * representation is compatible with the (String) constructor, and allows
  1264. * for String concatenation with Java's + operator.)
  1265. *
  1266. * @return decimal String representation of this BigInteger.
  1267. * @see Character#forDigit
  1268. * @see #BigInteger(java.lang.String)
  1269. */
  1270. public String toString() {
  1271. return toString(10);
  1272. }
  1273. /**
  1274. * Returns a byte array containing the two's-complement representation of
  1275. * this BigInteger. The byte array will be in <i>big-endian</i>
  1276. * byte-order: the most significant byte is in the zeroth element. The
  1277. * array will contain the minimum number of bytes required to represent
  1278. * this BigInteger, including at least one sign bit, which is
  1279. * <tt>(ceil((this.bitLength() + 1)/8))</tt>. (This representation is
  1280. * compatible with the (byte[]) constructor.)
  1281. *
  1282. * @return a byte array containing the two's-complement representation of
  1283. * this BigInteger.
  1284. * @see #BigInteger(byte[])
  1285. */
  1286. public byte[] toByteArray() {
  1287. byte[] result = new byte[byteLength()];
  1288. for(int i=0; i<result.length; i++)
  1289. result[i] = getByte(result.length-i-1);
  1290. return result;
  1291. }
  1292. /**
  1293. * Converts this BigInteger to an int. Standard <i>narrowing primitive
  1294. * conversion</i> as defined in <i>The Java Language Specification</i>:
  1295. * if this BigInteger is too big to fit in an int, only the low-order
  1296. * 32 bits are returned.
  1297. *
  1298. * @return this BigInteger converted to an int.
  1299. */
  1300. public int intValue() {
  1301. int result = 0;
  1302. for (int i=3; i>=0; i--)
  1303. result = (result << 8) + (getByte(i) & 0xff);
  1304. return result;
  1305. }
  1306. /**
  1307. * Converts this BigInteger to a long. Standard <i>narrowing primitive
  1308. * conversion</i> as defined in <i>The Java Language Specification</i>:
  1309. * if this BigInteger is too big to fit in a long, only the low-order
  1310. * 64 bits are returned.
  1311. *
  1312. * @return this BigInteger converted to a long.
  1313. */
  1314. public long longValue() {
  1315. long result = 0;
  1316. for (int i=7; i>=0; i--)
  1317. result = (result << 8) + (getByte(i) & 0xff);
  1318. return result;
  1319. }
  1320. /**
  1321. * Converts this BigInteger to a float. Similar to the double-to-float
  1322. * <i>narrowing primitive conversion</i> defined in <i>The Java Language
  1323. * Specification</i>: if this BigInteger has too great a magnitude to
  1324. * represent as a float, it will be converted to infinity or negative
  1325. * infinity, as appropriate.
  1326. *
  1327. * @return this BigInteger converted to a float.
  1328. */
  1329. public float floatValue() {
  1330. // Somewhat inefficient, but guaranteed to work.
  1331. return Float.valueOf(this.toString()).floatValue();
  1332. }
  1333. /**
  1334. * Converts this BigInteger to a double. Similar to the double-to-float
  1335. * <i>narrowing primitive conversion</i> defined in <i>The Java Language
  1336. * Specification</i>: if this BigInteger has too great a magnitude to
  1337. * represent as a double, it will be converted to infinity or negative
  1338. * infinity, as appropriate.
  1339. *
  1340. * @return this BigInteger converted to a double.
  1341. */
  1342. public double doubleValue() {
  1343. // Somewhat inefficient, but guaranteed to work.
  1344. return Double.valueOf(this.toString()).doubleValue();
  1345. }
  1346. static {
  1347. java.security.AccessController.doPrivileged(
  1348. new sun.security.action.LoadLibraryAction("math"));
  1349. plumbInit();
  1350. }
  1351. /**
  1352. * Returns a copy of the input array stripped of any leading zero bytes.
  1353. */
  1354. static private byte[] stripLeadingZeroBytes(byte a[]) {
  1355. int keep;
  1356. /* Find first nonzero byte */
  1357. for (keep=0; keep<a.length && a[keep]==0; keep++)
  1358. ;
  1359. /* Allocate new array and copy relevant part of input array */
  1360. byte result[] = new byte[a.length - keep];
  1361. for (int i = keep; i<a.length; i++)
  1362. result[i - keep] = a[i];
  1363. return result;
  1364. }
  1365. /**
  1366. * Takes an array a representing a negative 2's-complement number and
  1367. * returns the minimal (no leading zero bytes) unsigned whose value is -a.
  1368. */
  1369. static private byte[] makePositive(byte a[]) {
  1370. int keep, j;
  1371. /* Find first non-sign (0xff) byte of input */
  1372. for (keep=0; keep<a.length && a[keep]==-1; keep++)
  1373. ;
  1374. /* Allocate output array. If all non-sign bytes are 0x00, we must
  1375. * allocate space for one extra output byte. */
  1376. for (j=keep; j<a.length && a[j]==0; j++)
  1377. ;
  1378. int extraByte = (j==a.length ? 1 : 0);
  1379. byte result[] = new byte[a.length - keep + extraByte];
  1380. /* Copy one's complement of input into into output, leaving extra
  1381. * byte (if it exists) == 0x00 */
  1382. for (int i = keep; i<a.length; i++)
  1383. result[i - keep + extraByte] = (byte) ~a[i];
  1384. /* Add one to one's complement to generate two's complement */
  1385. for (int i=result.length-1; ++result[i]==0; i--)
  1386. ;
  1387. return result;
  1388. }
  1389. /*
  1390. * The following two arrays are used for fast String conversions. Both
  1391. * are indexed by radix. The first is the number of digits of the given
  1392. * radix that can fit in a Java long without "going negative", i.e., the
  1393. * highest integer n such that radix**n < 2**63. The second is the
  1394. * "long radix" that tears each number into "long digits", each of which
  1395. * consists of the number of digits in the corresponding element in
  1396. * digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have
  1397. * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
  1398. * used.
  1399. */
  1400. private static int digitsPerLong[] = {0, 0,
  1401. 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
  1402. 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
  1403. private static BigInteger longRadix[] = {null, null,
  1404. valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
  1405. valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
  1406. valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
  1407. valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
  1408. valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
  1409. valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
  1410. valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
  1411. valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
  1412. valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
  1413. valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
  1414. valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
  1415. valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
  1416. valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
  1417. valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
  1418. valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
  1419. valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
  1420. valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
  1421. valueOf(0x41c21cb8e1000000L)};
  1422. /**
  1423. * These routines provide access to the two's complement representation
  1424. * of BigIntegers.
  1425. */
  1426. /**
  1427. * Returns the length of the two's complement representation in bytes,
  1428. * including space for at least one sign bit,
  1429. */
  1430. private int byteLength() {
  1431. return bitLength()/8 + 1;
  1432. }
  1433. /* Returns sign bit */
  1434. private int signBit() {
  1435. return (signum < 0 ? 1 : 0);
  1436. }
  1437. /* Returns a byte of sign bits */
  1438. private byte signByte() {
  1439. return (byte) (signum < 0 ? -1 : 0);
  1440. }
  1441. /**
  1442. * Returns the specified byte of the little-endian two's complement
  1443. * representation (byte 0 is the LSB). The byte number can be arbitrarily
  1444. * high (values are logically preceded by infinitely many sign bytes).
  1445. */
  1446. private byte getByte(int n) {
  1447. if (n >= magnitude.length)
  1448. return signByte();
  1449. byte magByte = magnitude[magnitude.length-n-1];
  1450. return (byte) (signum >= 0 ? magByte :
  1451. (n <= firstNonzeroByteNum() ? -magByte : ~magByte));
  1452. }
  1453. /**
  1454. * Returns the index of the first nonzero byte in the little-endian
  1455. * binary representation of the magnitude (byte 0 is the LSB). If
  1456. * the magnitude is zero, return value is undefined.
  1457. */
  1458. private int firstNonzeroByteNum() {
  1459. /*
  1460. * Initialize firstNonzeroByteNum field the first time this method is
  1461. * executed. This method depends on the atomicity of int modifies;
  1462. * without this guarantee, it would have to be synchronized.
  1463. */
  1464. if (firstNonzeroByteNum == -2) {
  1465. /* Search for the first nonzero byte */
  1466. int i;
  1467. for (i=magnitude.length-1; i>=0 && magnitude[i]==0; i--)
  1468. ;
  1469. firstNonzeroByteNum = magnitude.length-i-1;
  1470. }
  1471. return firstNonzeroByteNum;
  1472. }
  1473. /**
  1474. * Native method wrappers for Colin Plumb's big positive integer package.
  1475. * Each of these wrappers (except for plumbInit) behaves as follows:
  1476. *
  1477. * 1) Translate input arguments from java byte arrays into plumbNums.
  1478. *
  1479. * 2) Perform the requested computation.
  1480. *
  1481. * 3) Translate result(s) into Java byte array(s). (The subtract
  1482. * operation translates its result into a BigInteger, as its result
  1483. * is, effectively, signed.)
  1484. *
  1485. * 4) Deallocate all of the plumbNums.
  1486. *
  1487. * 5) Return the resulting Java array(s) (or, in the case of subtract,
  1488. * BigInteger).
  1489. */
  1490. private static native void plumbInit();
  1491. private static native byte[] plumbAdd(byte[] a, byte[] b);
  1492. private static native BigInteger plumbSubtract(byte[] a, byte[] b);
  1493. private static native byte[] plumbMultiply(byte[] a, byte[] b);
  1494. private static native byte[] plumbDivide(byte[] a, byte[] b);
  1495. private static native byte[] plumbRemainder(byte[] a, byte[] b);
  1496. private static native byte[][] plumbDivideAndRemainder(byte[] a, byte[] b);
  1497. private static native byte[] plumbGcd(byte[] a, byte[] b);
  1498. private static native byte[] plumbModPow(byte[] a, byte[] b, byte[] m);
  1499. private static native byte[] plumbModInverse(byte[] a, byte[] m);
  1500. private static native byte[] plumbSquare(byte[] a);
  1501. private static native byte[] plumbGeneratePrime(byte[] a);
  1502. /** use serialVersionUID from JDK 1.1. for interoperability */
  1503. private static final long serialVersionUID = -8287574255936472291L;
  1504. /**
  1505. * Reconstitute the <tt>BigInteger</tt> instance from a stream (that is,
  1506. * deserialize it).
  1507. */
  1508. private synchronized void readObject(java.io.ObjectInputStream s)
  1509. throws java.io.IOException, ClassNotFoundException {
  1510. // Read in all fields
  1511. s.defaultReadObject();
  1512. // Defensively copy magnitude to ensure immutability
  1513. magnitude = (byte[]) magnitude.clone();
  1514. // Validate signum
  1515. if (signum < -1 || signum > 1)
  1516. throw new java.io.StreamCorruptedException(
  1517. "BigInteger: Invalid signum value");
  1518. if ((magnitude.length==0) != (signum==0))
  1519. throw new java.io.StreamCorruptedException(
  1520. "BigInteger: signum-magnitude mismatch");
  1521. // Set "cached computation" fields to their initial values
  1522. bitCount = bitLength = -1;
  1523. lowestSetBit = firstNonzeroByteNum = -2;
  1524. }
  1525. }