BigUnsigned.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. #include "BigUnsigned.hh"
  2. // Memory management definitions have moved to the bottom of NumberlikeArray.hh.
  3. // The templates used by these constructors and converters are at the bottom of
  4. // BigUnsigned.hh.
  5. BigUnsigned::BigUnsigned(unsigned long x) { initFromPrimitive (x); }
  6. BigUnsigned::BigUnsigned(unsigned int x) { initFromPrimitive (x); }
  7. BigUnsigned::BigUnsigned(unsigned short x) { initFromPrimitive (x); }
  8. BigUnsigned::BigUnsigned( long x) { initFromSignedPrimitive(x); }
  9. BigUnsigned::BigUnsigned( int x) { initFromSignedPrimitive(x); }
  10. BigUnsigned::BigUnsigned( short x) { initFromSignedPrimitive(x); }
  11. unsigned long BigUnsigned::toUnsignedLong () const { return convertToPrimitive <unsigned long >(); }
  12. unsigned int BigUnsigned::toUnsignedInt () const { return convertToPrimitive <unsigned int >(); }
  13. unsigned short BigUnsigned::toUnsignedShort() const { return convertToPrimitive <unsigned short>(); }
  14. long BigUnsigned::toLong () const { return convertToSignedPrimitive< long >(); }
  15. int BigUnsigned::toInt () const { return convertToSignedPrimitive< int >(); }
  16. short BigUnsigned::toShort () const { return convertToSignedPrimitive< short>(); }
  17. // BIT/BLOCK ACCESSORS
  18. void BigUnsigned::setBlock(Index i, Blk newBlock) {
  19. if (newBlock == 0) {
  20. if (i < len) {
  21. blk[i] = 0;
  22. zapLeadingZeros();
  23. }
  24. // If i >= len, no effect.
  25. } else {
  26. if (i >= len) {
  27. // The nonzero block extends the number.
  28. allocateAndCopy(i+1);
  29. // Zero any added blocks that we aren't setting.
  30. for (Index j = len; j < i; j++)
  31. blk[j] = 0;
  32. len = i+1;
  33. }
  34. blk[i] = newBlock;
  35. }
  36. }
  37. /* Evidently the compiler wants BigUnsigned:: on the return type because, at
  38. * that point, it hasn't yet parsed the BigUnsigned:: on the name to get the
  39. * proper scope. */
  40. BigUnsigned::Index BigUnsigned::bitLength() const {
  41. if (isZero())
  42. return 0;
  43. else {
  44. Blk leftmostBlock = getBlock(len - 1);
  45. Index leftmostBlockLen = 0;
  46. while (leftmostBlock != 0) {
  47. leftmostBlock >>= 1;
  48. leftmostBlockLen++;
  49. }
  50. return leftmostBlockLen + (len - 1) * N;
  51. }
  52. }
  53. void BigUnsigned::setBit(Index bi, bool newBit) {
  54. Index blockI = bi / N;
  55. Blk block = getBlock(blockI), mask = Blk(1) << (bi % N);
  56. block = newBit ? (block | mask) : (block & ~mask);
  57. setBlock(blockI, block);
  58. }
  59. // COMPARISON
  60. BigUnsigned::CmpRes BigUnsigned::compareTo(const BigUnsigned &x) const {
  61. // A bigger length implies a bigger number.
  62. if (len < x.len)
  63. return less;
  64. else if (len > x.len)
  65. return greater;
  66. else {
  67. // Compare blocks one by one from left to right.
  68. Index i = len;
  69. while (i > 0) {
  70. i--;
  71. if (blk[i] == x.blk[i])
  72. continue;
  73. else if (blk[i] > x.blk[i])
  74. return greater;
  75. else
  76. return less;
  77. }
  78. // If no blocks differed, the numbers are equal.
  79. return equal;
  80. }
  81. }
  82. // COPY-LESS OPERATIONS
  83. /*
  84. * On most calls to copy-less operations, it's safe to read the inputs little by
  85. * little and write the outputs little by little. However, if one of the
  86. * inputs is coming from the same variable into which the output is to be
  87. * stored (an "aliased" call), we risk overwriting the input before we read it.
  88. * In this case, we first compute the result into a temporary BigUnsigned
  89. * variable and then copy it into the requested output variable *this.
  90. * Each put-here operation uses the DTRT_ALIASED macro (Do The Right Thing on
  91. * aliased calls) to generate code for this check.
  92. *
  93. * I adopted this approach on 2007.02.13 (see Assignment Operators in
  94. * BigUnsigned.hh). Before then, put-here operations rejected aliased calls
  95. * with an exception. I think doing the right thing is better.
  96. *
  97. * Some of the put-here operations can probably handle aliased calls safely
  98. * without the extra copy because (for example) they process blocks strictly
  99. * right-to-left. At some point I might determine which ones don't need the
  100. * copy, but my reasoning would need to be verified very carefully. For now
  101. * I'll leave in the copy.
  102. */
  103. #define DTRT_ALIASED(cond, op) \
  104. if (cond) { \
  105. BigUnsigned tmpThis; \
  106. tmpThis.op; \
  107. *this = tmpThis; \
  108. return; \
  109. }
  110. void BigUnsigned::add(const BigUnsigned &a, const BigUnsigned &b) {
  111. DTRT_ALIASED(this == &a || this == &b, add(a, b));
  112. // If one argument is zero, copy the other.
  113. if (a.len == 0) {
  114. operator =(b);
  115. return;
  116. } else if (b.len == 0) {
  117. operator =(a);
  118. return;
  119. }
  120. // Some variables...
  121. // Carries in and out of an addition stage
  122. bool carryIn, carryOut;
  123. Blk temp;
  124. Index i;
  125. // a2 points to the longer input, b2 points to the shorter
  126. const BigUnsigned *a2, *b2;
  127. if (a.len >= b.len) {
  128. a2 = &a;
  129. b2 = &b;
  130. } else {
  131. a2 = &b;
  132. b2 = &a;
  133. }
  134. // Set prelimiary length and make room in this BigUnsigned
  135. len = a2->len + 1;
  136. allocate(len);
  137. // For each block index that is present in both inputs...
  138. for (i = 0, carryIn = false; i < b2->len; i++) {
  139. // Add input blocks
  140. temp = a2->blk[i] + b2->blk[i];
  141. // If a rollover occurred, the result is less than either input.
  142. // This test is used many times in the BigUnsigned code.
  143. carryOut = (temp < a2->blk[i]);
  144. // If a carry was input, handle it
  145. if (carryIn) {
  146. temp++;
  147. carryOut |= (temp == 0);
  148. }
  149. blk[i] = temp; // Save the addition result
  150. carryIn = carryOut; // Pass the carry along
  151. }
  152. // If there is a carry left over, increase blocks until
  153. // one does not roll over.
  154. for (; i < a2->len && carryIn; i++) {
  155. temp = a2->blk[i] + 1;
  156. carryIn = (temp == 0);
  157. blk[i] = temp;
  158. }
  159. // If the carry was resolved but the larger number
  160. // still has blocks, copy them over.
  161. for (; i < a2->len; i++)
  162. blk[i] = a2->blk[i];
  163. // Set the extra block if there's still a carry, decrease length otherwise
  164. if (carryIn)
  165. blk[i] = 1;
  166. else
  167. len--;
  168. }
  169. void BigUnsigned::subtract(const BigUnsigned &a, const BigUnsigned &b) {
  170. DTRT_ALIASED(this == &a || this == &b, subtract(a, b));
  171. if (b.len == 0) {
  172. // If b is zero, copy a.
  173. operator =(a);
  174. return;
  175. } else if (a.len < b.len)
  176. // If a is shorter than b, the result is negative.
  177. throw "BigUnsigned::subtract: "
  178. "Negative result in unsigned calculation";
  179. // Some variables...
  180. bool borrowIn, borrowOut;
  181. Blk temp;
  182. Index i;
  183. // Set preliminary length and make room
  184. len = a.len;
  185. allocate(len);
  186. // For each block index that is present in both inputs...
  187. for (i = 0, borrowIn = false; i < b.len; i++) {
  188. temp = a.blk[i] - b.blk[i];
  189. // If a reverse rollover occurred,
  190. // the result is greater than the block from a.
  191. borrowOut = (temp > a.blk[i]);
  192. // Handle an incoming borrow
  193. if (borrowIn) {
  194. borrowOut |= (temp == 0);
  195. temp--;
  196. }
  197. blk[i] = temp; // Save the subtraction result
  198. borrowIn = borrowOut; // Pass the borrow along
  199. }
  200. // If there is a borrow left over, decrease blocks until
  201. // one does not reverse rollover.
  202. for (; i < a.len && borrowIn; i++) {
  203. borrowIn = (a.blk[i] == 0);
  204. blk[i] = a.blk[i] - 1;
  205. }
  206. /* If there's still a borrow, the result is negative.
  207. * Throw an exception, but zero out this object so as to leave it in a
  208. * predictable state. */
  209. if (borrowIn) {
  210. len = 0;
  211. throw "BigUnsigned::subtract: Negative result in unsigned calculation";
  212. } else
  213. // Copy over the rest of the blocks
  214. for (; i < a.len; i++)
  215. blk[i] = a.blk[i];
  216. // Zap leading zeros
  217. zapLeadingZeros();
  218. }
  219. /*
  220. * About the multiplication and division algorithms:
  221. *
  222. * I searched unsucessfully for fast C++ built-in operations like the `b_0'
  223. * and `c_0' Knuth describes in Section 4.3.1 of ``The Art of Computer
  224. * Programming'' (replace `place' by `Blk'):
  225. *
  226. * ``b_0[:] multiplication of a one-place integer by another one-place
  227. * integer, giving a two-place answer;
  228. *
  229. * ``c_0[:] division of a two-place integer by a one-place integer,
  230. * provided that the quotient is a one-place integer, and yielding
  231. * also a one-place remainder.''
  232. *
  233. * I also missed his note that ``[b]y adjusting the word size, if
  234. * necessary, nearly all computers will have these three operations
  235. * available'', so I gave up on trying to use algorithms similar to his.
  236. * A future version of the library might include such algorithms; I
  237. * would welcome contributions from others for this.
  238. *
  239. * I eventually decided to use bit-shifting algorithms. To multiply `a'
  240. * and `b', we zero out the result. Then, for each `1' bit in `a', we
  241. * shift `b' left the appropriate amount and add it to the result.
  242. * Similarly, to divide `a' by `b', we shift `b' left varying amounts,
  243. * repeatedly trying to subtract it from `a'. When we succeed, we note
  244. * the fact by setting a bit in the quotient. While these algorithms
  245. * have the same O(n^2) time complexity as Knuth's, the ``constant factor''
  246. * is likely to be larger.
  247. *
  248. * Because I used these algorithms, which require single-block addition
  249. * and subtraction rather than single-block multiplication and division,
  250. * the innermost loops of all four routines are very similar. Study one
  251. * of them and all will become clear.
  252. */
  253. /*
  254. * This is a little inline function used by both the multiplication
  255. * routine and the division routine.
  256. *
  257. * `getShiftedBlock' returns the `x'th block of `num << y'.
  258. * `y' may be anything from 0 to N - 1, and `x' may be anything from
  259. * 0 to `num.len'.
  260. *
  261. * Two things contribute to this block:
  262. *
  263. * (1) The `N - y' low bits of `num.blk[x]', shifted `y' bits left.
  264. *
  265. * (2) The `y' high bits of `num.blk[x-1]', shifted `N - y' bits right.
  266. *
  267. * But we must be careful if `x == 0' or `x == num.len', in
  268. * which case we should use 0 instead of (2) or (1), respectively.
  269. *
  270. * If `y == 0', then (2) contributes 0, as it should. However,
  271. * in some computer environments, for a reason I cannot understand,
  272. * `a >> b' means `a >> (b % N)'. This means `num.blk[x-1] >> (N - y)'
  273. * will return `num.blk[x-1]' instead of the desired 0 when `y == 0';
  274. * the test `y == 0' handles this case specially.
  275. */
  276. inline BigUnsigned::Blk getShiftedBlock(const BigUnsigned &num,
  277. BigUnsigned::Index x, unsigned int y) {
  278. BigUnsigned::Blk part1 = (x == 0 || y == 0) ? 0 : (num.blk[x - 1] >> (BigUnsigned::N - y));
  279. BigUnsigned::Blk part2 = (x == num.len) ? 0 : (num.blk[x] << y);
  280. return part1 | part2;
  281. }
  282. void BigUnsigned::multiply(const BigUnsigned &a, const BigUnsigned &b) {
  283. DTRT_ALIASED(this == &a || this == &b, multiply(a, b));
  284. // If either a or b is zero, set to zero.
  285. if (a.len == 0 || b.len == 0) {
  286. len = 0;
  287. return;
  288. }
  289. /*
  290. * Overall method:
  291. *
  292. * Set this = 0.
  293. * For each 1-bit of `a' (say the `i2'th bit of block `i'):
  294. * Add `b << (i blocks and i2 bits)' to *this.
  295. */
  296. // Variables for the calculation
  297. Index i, j, k;
  298. unsigned int i2;
  299. Blk temp;
  300. bool carryIn, carryOut;
  301. // Set preliminary length and make room
  302. len = a.len + b.len;
  303. allocate(len);
  304. // Zero out this object
  305. for (i = 0; i < len; i++)
  306. blk[i] = 0;
  307. // For each block of the first number...
  308. for (i = 0; i < a.len; i++) {
  309. // For each 1-bit of that block...
  310. for (i2 = 0; i2 < N; i2++) {
  311. if ((a.blk[i] & (Blk(1) << i2)) == 0)
  312. continue;
  313. /*
  314. * Add b to this, shifted left i blocks and i2 bits.
  315. * j is the index in b, and k = i + j is the index in this.
  316. *
  317. * `getShiftedBlock', a short inline function defined above,
  318. * is now used for the bit handling. It replaces the more
  319. * complex `bHigh' code, in which each run of the loop dealt
  320. * immediately with the low bits and saved the high bits to
  321. * be picked up next time. The last run of the loop used to
  322. * leave leftover high bits, which were handled separately.
  323. * Instead, this loop runs an additional time with j == b.len.
  324. * These changes were made on 2005.01.11.
  325. */
  326. for (j = 0, k = i, carryIn = false; j <= b.len; j++, k++) {
  327. /*
  328. * The body of this loop is very similar to the body of the first loop
  329. * in `add', except that this loop does a `+=' instead of a `+'.
  330. */
  331. temp = blk[k] + getShiftedBlock(b, j, i2);
  332. carryOut = (temp < blk[k]);
  333. if (carryIn) {
  334. temp++;
  335. carryOut |= (temp == 0);
  336. }
  337. blk[k] = temp;
  338. carryIn = carryOut;
  339. }
  340. // No more extra iteration to deal with `bHigh'.
  341. // Roll-over a carry as necessary.
  342. for (; carryIn; k++) {
  343. blk[k]++;
  344. carryIn = (blk[k] == 0);
  345. }
  346. }
  347. }
  348. // Zap possible leading zero
  349. if (blk[len - 1] == 0)
  350. len--;
  351. }
  352. /*
  353. * DIVISION WITH REMAINDER
  354. * This monstrous function mods *this by the given divisor b while storing the
  355. * quotient in the given object q; at the end, *this contains the remainder.
  356. * The seemingly bizarre pattern of inputs and outputs was chosen so that the
  357. * function copies as little as possible (since it is implemented by repeated
  358. * subtraction of multiples of b from *this).
  359. *
  360. * "modWithQuotient" might be a better name for this function, but I would
  361. * rather not change the name now.
  362. */
  363. void BigUnsigned::divideWithRemainder(const BigUnsigned &b, BigUnsigned &q) {
  364. /* Defending against aliased calls is more complex than usual because we
  365. * are writing to both *this and q.
  366. *
  367. * It would be silly to try to write quotient and remainder to the
  368. * same variable. Rule that out right away. */
  369. if (this == &q)
  370. throw "BigUnsigned::divideWithRemainder: Cannot write quotient and remainder into the same variable";
  371. /* Now *this and q are separate, so the only concern is that b might be
  372. * aliased to one of them. If so, use a temporary copy of b. */
  373. if (this == &b || &q == &b) {
  374. BigUnsigned tmpB(b);
  375. divideWithRemainder(tmpB, q);
  376. return;
  377. }
  378. /*
  379. * Knuth's definition of mod (which this function uses) is somewhat
  380. * different from the C++ definition of % in case of division by 0.
  381. *
  382. * We let a / 0 == 0 (it doesn't matter much) and a % 0 == a, no
  383. * exceptions thrown. This allows us to preserve both Knuth's demand
  384. * that a mod 0 == a and the useful property that
  385. * (a / b) * b + (a % b) == a.
  386. */
  387. if (b.len == 0) {
  388. q.len = 0;
  389. return;
  390. }
  391. /*
  392. * If *this.len < b.len, then *this < b, and we can be sure that b doesn't go into
  393. * *this at all. The quotient is 0 and *this is already the remainder (so leave it alone).
  394. */
  395. if (len < b.len) {
  396. q.len = 0;
  397. return;
  398. }
  399. // At this point we know (*this).len >= b.len > 0. (Whew!)
  400. /*
  401. * Overall method:
  402. *
  403. * For each appropriate i and i2, decreasing:
  404. * Subtract (b << (i blocks and i2 bits)) from *this, storing the
  405. * result in subtractBuf.
  406. * If the subtraction succeeds with a nonnegative result:
  407. * Turn on bit i2 of block i of the quotient q.
  408. * Copy subtractBuf back into *this.
  409. * Otherwise bit i2 of block i remains off, and *this is unchanged.
  410. *
  411. * Eventually q will contain the entire quotient, and *this will
  412. * be left with the remainder.
  413. *
  414. * subtractBuf[x] corresponds to blk[x], not blk[x+i], since 2005.01.11.
  415. * But on a single iteration, we don't touch the i lowest blocks of blk
  416. * (and don't use those of subtractBuf) because these blocks are
  417. * unaffected by the subtraction: we are subtracting
  418. * (b << (i blocks and i2 bits)), which ends in at least `i' zero
  419. * blocks. */
  420. // Variables for the calculation
  421. Index i, j, k;
  422. unsigned int i2;
  423. Blk temp;
  424. bool borrowIn, borrowOut;
  425. /*
  426. * Make sure we have an extra zero block just past the value.
  427. *
  428. * When we attempt a subtraction, we might shift `b' so
  429. * its first block begins a few bits left of the dividend,
  430. * and then we'll try to compare these extra bits with
  431. * a nonexistent block to the left of the dividend. The
  432. * extra zero block ensures sensible behavior; we need
  433. * an extra block in `subtractBuf' for exactly the same reason.
  434. */
  435. Index origLen = len; // Save real length.
  436. /* To avoid an out-of-bounds access in case of reallocation, allocate
  437. * first and then increment the logical length. */
  438. allocateAndCopy(len + 1);
  439. len++;
  440. blk[origLen] = 0; // Zero the added block.
  441. // subtractBuf holds part of the result of a subtraction; see above.
  442. Blk *subtractBuf = new Blk[len];
  443. // Set preliminary length for quotient and make room
  444. q.len = origLen - b.len + 1;
  445. q.allocate(q.len);
  446. // Zero out the quotient
  447. for (i = 0; i < q.len; i++)
  448. q.blk[i] = 0;
  449. // For each possible left-shift of b in blocks...
  450. i = q.len;
  451. while (i > 0) {
  452. i--;
  453. // For each possible left-shift of b in bits...
  454. // (Remember, N is the number of bits in a Blk.)
  455. q.blk[i] = 0;
  456. i2 = N;
  457. while (i2 > 0) {
  458. i2--;
  459. /*
  460. * Subtract b, shifted left i blocks and i2 bits, from *this,
  461. * and store the answer in subtractBuf. In the for loop, `k == i + j'.
  462. *
  463. * Compare this to the middle section of `multiply'. They
  464. * are in many ways analogous. See especially the discussion
  465. * of `getShiftedBlock'.
  466. */
  467. for (j = 0, k = i, borrowIn = false; j <= b.len; j++, k++) {
  468. temp = blk[k] - getShiftedBlock(b, j, i2);
  469. borrowOut = (temp > blk[k]);
  470. if (borrowIn) {
  471. borrowOut |= (temp == 0);
  472. temp--;
  473. }
  474. // Since 2005.01.11, indices of `subtractBuf' directly match those of `blk', so use `k'.
  475. subtractBuf[k] = temp;
  476. borrowIn = borrowOut;
  477. }
  478. // No more extra iteration to deal with `bHigh'.
  479. // Roll-over a borrow as necessary.
  480. for (; k < origLen && borrowIn; k++) {
  481. borrowIn = (blk[k] == 0);
  482. subtractBuf[k] = blk[k] - 1;
  483. }
  484. /*
  485. * If the subtraction was performed successfully (!borrowIn),
  486. * set bit i2 in block i of the quotient.
  487. *
  488. * Then, copy the portion of subtractBuf filled by the subtraction
  489. * back to *this. This portion starts with block i and ends--
  490. * where? Not necessarily at block `i + b.len'! Well, we
  491. * increased k every time we saved a block into subtractBuf, so
  492. * the region of subtractBuf we copy is just [i, k).
  493. */
  494. if (!borrowIn) {
  495. q.blk[i] |= (Blk(1) << i2);
  496. while (k > i) {
  497. k--;
  498. blk[k] = subtractBuf[k];
  499. }
  500. }
  501. }
  502. }
  503. // Zap possible leading zero in quotient
  504. if (q.blk[q.len - 1] == 0)
  505. q.len--;
  506. // Zap any/all leading zeros in remainder
  507. zapLeadingZeros();
  508. // Deallocate subtractBuf.
  509. // (Thanks to Brad Spencer for noticing my accidental omission of this!)
  510. delete [] subtractBuf;
  511. }
  512. /* BITWISE OPERATORS
  513. * These are straightforward blockwise operations except that they differ in
  514. * the output length and the necessity of zapLeadingZeros. */
  515. void BigUnsigned::bitAnd(const BigUnsigned &a, const BigUnsigned &b) {
  516. DTRT_ALIASED(this == &a || this == &b, bitAnd(a, b));
  517. // The bitwise & can't be longer than either operand.
  518. len = (a.len >= b.len) ? b.len : a.len;
  519. allocate(len);
  520. Index i;
  521. for (i = 0; i < len; i++)
  522. blk[i] = a.blk[i] & b.blk[i];
  523. zapLeadingZeros();
  524. }
  525. void BigUnsigned::bitOr(const BigUnsigned &a, const BigUnsigned &b) {
  526. DTRT_ALIASED(this == &a || this == &b, bitOr(a, b));
  527. Index i;
  528. const BigUnsigned *a2, *b2;
  529. if (a.len >= b.len) {
  530. a2 = &a;
  531. b2 = &b;
  532. } else {
  533. a2 = &b;
  534. b2 = &a;
  535. }
  536. allocate(a2->len);
  537. for (i = 0; i < b2->len; i++)
  538. blk[i] = a2->blk[i] | b2->blk[i];
  539. for (; i < a2->len; i++)
  540. blk[i] = a2->blk[i];
  541. len = a2->len;
  542. // Doesn't need zapLeadingZeros.
  543. }
  544. void BigUnsigned::bitXor(const BigUnsigned &a, const BigUnsigned &b) {
  545. DTRT_ALIASED(this == &a || this == &b, bitXor(a, b));
  546. Index i;
  547. const BigUnsigned *a2, *b2;
  548. if (a.len >= b.len) {
  549. a2 = &a;
  550. b2 = &b;
  551. } else {
  552. a2 = &b;
  553. b2 = &a;
  554. }
  555. allocate(a2->len);
  556. for (i = 0; i < b2->len; i++)
  557. blk[i] = a2->blk[i] ^ b2->blk[i];
  558. for (; i < a2->len; i++)
  559. blk[i] = a2->blk[i];
  560. len = a2->len;
  561. zapLeadingZeros();
  562. }
  563. void BigUnsigned::bitShiftLeft(const BigUnsigned &a, int b) {
  564. DTRT_ALIASED(this == &a, bitShiftLeft(a, b));
  565. if (b < 0) {
  566. if (b << 1 == 0)
  567. throw "BigUnsigned::bitShiftLeft: "
  568. "Pathological shift amount not implemented";
  569. else {
  570. bitShiftRight(a, -b);
  571. return;
  572. }
  573. }
  574. Index shiftBlocks = b / N;
  575. unsigned int shiftBits = b % N;
  576. // + 1: room for high bits nudged left into another block
  577. len = a.len + shiftBlocks + 1;
  578. allocate(len);
  579. Index i, j;
  580. for (i = 0; i < shiftBlocks; i++)
  581. blk[i] = 0;
  582. for (j = 0, i = shiftBlocks; j <= a.len; j++, i++)
  583. blk[i] = getShiftedBlock(a, j, shiftBits);
  584. // Zap possible leading zero
  585. if (blk[len - 1] == 0)
  586. len--;
  587. }
  588. void BigUnsigned::bitShiftRight(const BigUnsigned &a, int b) {
  589. DTRT_ALIASED(this == &a, bitShiftRight(a, b));
  590. if (b < 0) {
  591. if (b << 1 == 0)
  592. throw "BigUnsigned::bitShiftRight: "
  593. "Pathological shift amount not implemented";
  594. else {
  595. bitShiftLeft(a, -b);
  596. return;
  597. }
  598. }
  599. // This calculation is wacky, but expressing the shift as a left bit shift
  600. // within each block lets us use getShiftedBlock.
  601. Index rightShiftBlocks = (b + N - 1) / N;
  602. unsigned int leftShiftBits = N * rightShiftBlocks - b;
  603. // Now (N * rightShiftBlocks - leftShiftBits) == b
  604. // and 0 <= leftShiftBits < N.
  605. if (rightShiftBlocks >= a.len + 1) {
  606. // All of a is guaranteed to be shifted off, even considering the left
  607. // bit shift.
  608. len = 0;
  609. return;
  610. }
  611. // Now we're allocating a positive amount.
  612. // + 1: room for high bits nudged left into another block
  613. len = a.len + 1 - rightShiftBlocks;
  614. allocate(len);
  615. Index i, j;
  616. for (j = rightShiftBlocks, i = 0; j <= a.len; j++, i++)
  617. blk[i] = getShiftedBlock(a, j, leftShiftBits);
  618. // Zap possible leading zero
  619. if (blk[len - 1] == 0)
  620. len--;
  621. }
  622. // INCREMENT/DECREMENT OPERATORS
  623. // Prefix increment
  624. void BigUnsigned::operator ++() {
  625. Index i;
  626. bool carry = true;
  627. for (i = 0; i < len && carry; i++) {
  628. blk[i]++;
  629. carry = (blk[i] == 0);
  630. }
  631. if (carry) {
  632. // Allocate and then increase length, as in divideWithRemainder
  633. allocateAndCopy(len + 1);
  634. len++;
  635. blk[i] = 1;
  636. }
  637. }
  638. // Postfix increment: same as prefix
  639. void BigUnsigned::operator ++(int) {
  640. operator ++();
  641. }
  642. // Prefix decrement
  643. void BigUnsigned::operator --() {
  644. if (len == 0)
  645. throw "BigUnsigned::operator --(): Cannot decrement an unsigned zero";
  646. Index i;
  647. bool borrow = true;
  648. for (i = 0; borrow; i++) {
  649. borrow = (blk[i] == 0);
  650. blk[i]--;
  651. }
  652. // Zap possible leading zero (there can only be one)
  653. if (blk[len - 1] == 0)
  654. len--;
  655. }
  656. // Postfix decrement: same as prefix
  657. void BigUnsigned::operator --(int) {
  658. operator --();
  659. }