2 * Matt McCutchen's Big Integer Library
3 * http://mysite.verizon.net/mccutchen/bigint/
6 #include "BigUnsigned.hh"
8 // The "management" routines that used to be here are now in NumberlikeArray.hh.
11 * The steps for construction of a BigUnsigned
12 * from an integral value x are as follows:
13 * 1. If x is zero, create an empty BigUnsigned and stop.
14 * 2. If x is negative, throw an exception.
15 * 3. Allocate a one-block number array.
16 * 4. If x is of a signed type, convert x to the unsigned
17 * type of the same length.
18 * 5. Expand x to a Blk, and store it in the number array.
20 * Since 2005.01.06, NumberlikeArray uses `NULL' rather
21 * than a real array if one of zero length is needed.
22 * These constructors implicitly call NumberlikeArray's
23 * default constructor, which sets `blk2 = NULL, cap = len = 0'.
24 * So if the input number is zero, they can just return.
25 * See remarks in `NumberlikeArray.hh'.
28 BigUnsigned::BigUnsigned(unsigned long x) {
30 ; // NumberlikeArray already did all the work
39 BigUnsigned::BigUnsigned(long x) {
48 throw "BigUnsigned::BigUnsigned(long): Cannot construct a BigUnsigned from a negative number";
51 BigUnsigned::BigUnsigned(unsigned int x) {
62 BigUnsigned::BigUnsigned(int x) {
71 throw "BigUnsigned::BigUnsigned(int): Cannot construct a BigUnsigned from a negative number";
74 BigUnsigned::BigUnsigned(unsigned short x) {
85 BigUnsigned::BigUnsigned(short x) {
94 throw "BigUnsigned::BigUnsigned(short): Cannot construct a BigUnsigned from a negative number";
99 * The steps for conversion of a BigUnsigned to an
100 * integral type are as follows:
101 * 1. If the BigUnsigned is zero, return zero.
102 * 2. If it is more than one block long or its lowest
103 * block has bits set out of the range of the target
104 * type, throw an exception.
105 * 3. Otherwise, convert the lowest block to the
106 * target type and return it.
110 // These masks are used to test whether a Blk has bits
111 // set out of the range of a smaller integral type. Note
112 // that this range is not considered to include the sign bit.
113 const BigUnsigned::Blk lMask = ~0 >> 1;
114 const BigUnsigned::Blk uiMask = (unsigned int)(~0);
115 const BigUnsigned::Blk iMask = uiMask >> 1;
116 const BigUnsigned::Blk usMask = (unsigned short)(~0);
117 const BigUnsigned::Blk sMask = usMask >> 1;
120 BigUnsigned::operator unsigned long() const {
124 return (unsigned long) blk[0];
126 throw "BigUnsigned::operator unsigned long: Value is too big for an unsigned long";
129 BigUnsigned::operator long() const {
132 else if (len == 1 && (blk[0] & lMask) == blk[0])
133 return (long) blk[0];
135 throw "BigUnsigned::operator long: Value is too big for a long";
138 BigUnsigned::operator unsigned int() const {
141 else if (len == 1 && (blk[0] & uiMask) == blk[0])
142 return (unsigned int) blk[0];
144 throw "BigUnsigned::operator unsigned int: Value is too big for an unsigned int";
147 BigUnsigned::operator int() const {
150 else if (len == 1 && (blk[0] & iMask) == blk[0])
153 throw "BigUnsigned::operator int: Value is too big for an int";
156 BigUnsigned::operator unsigned short() const {
159 else if (len == 1 && (blk[0] & usMask) == blk[0])
160 return (unsigned short) blk[0];
162 throw "BigUnsigned::operator unsigned short: Value is too big for an unsigned short";
165 BigUnsigned::operator short() const {
168 else if (len == 1 && (blk[0] & sMask) == blk[0])
169 return (short) blk[0];
171 throw "BigUnsigned::operator short: Value is too big for a short";
175 BigUnsigned::CmpRes BigUnsigned::compareTo(const BigUnsigned &x) const {
176 // A bigger length implies a bigger number.
179 else if (len > x.len)
182 // Compare blocks one by one from left to right.
186 if (blk[i] == x.blk[i])
188 else if (blk[i] > x.blk[i])
193 // If no blocks differed, the numbers are equal.
198 // PUT-HERE OPERATIONS
201 * Below are implementations of the four basic arithmetic operations
202 * for `BigUnsigned's. Their purpose is to use a mechanism that can
203 * calculate the sum, difference, product, and quotient/remainder of
204 * two individual blocks in order to calculate the sum, difference,
205 * product, and quotient/remainder of two multi-block BigUnsigned
208 * As alluded to in the comment before class `BigUnsigned',
209 * these algorithms bear a remarkable similarity (in purpose, if
210 * not in implementation) to the way humans operate on big numbers.
211 * The built-in `+', `-', `*', `/' and `%' operators are analogous
212 * to elementary-school ``math facts'' and ``times tables''; the
213 * four routines below are analogous to ``long division'' and its
214 * relatives. (Only a computer can ``memorize'' a times table with
215 * 18446744073709551616 entries! (For 32-bit blocks.))
217 * The discovery of these four algorithms, called the ``classical
218 * algorithms'', marked the beginning of the study of computer science.
219 * See Section 4.3.1 of Knuth's ``The Art of Computer Programming''.
223 void BigUnsigned::add(const BigUnsigned &a, const BigUnsigned &b) {
224 // Block unsafe calls
225 if (this == &a || this == &b)
226 throw "BigUnsigned::add: One of the arguments is the invoked object";
227 // If one argument is zero, copy the other.
231 } else if (b.len == 0) {
236 // Carries in and out of an addition stage
237 bool carryIn, carryOut;
240 // a2 points to the longer input, b2 points to the shorter
241 const BigUnsigned *a2, *b2;
242 if (a.len >= b.len) {
249 // Set prelimiary length and make room in this BigUnsigned
252 // For each block index that is present in both inputs...
253 for (i = 0, carryIn = false; i < b2->len; i++) {
255 temp = a2->blk[i] + b2->blk[i];
256 // If a rollover occurred, the result is less than either input.
257 // This test is used many times in the BigUnsigned code.
258 carryOut = (temp < a2->blk[i]);
259 // If a carry was input, handle it
262 carryOut |= (temp == 0);
264 blk[i] = temp; // Save the addition result
265 carryIn = carryOut; // Pass the carry along
267 // If there is a carry left over, increase blocks until
268 // one does not roll over.
269 for (; i < a2->len && carryIn; i++) {
270 temp = a2->blk[i] + 1;
271 carryIn = (temp == 0);
274 // If the carry was resolved but the larger number
275 // still has blocks, copy them over.
276 for (; i < a2->len; i++)
278 // Set the extra block if there's still a carry, decrease length otherwise
286 void BigUnsigned::subtract(const BigUnsigned &a, const BigUnsigned &b) {
287 // Block unsafe calls
288 if (this == &a || this == &b)
289 throw "BigUnsigned::subtract: One of the arguments is the invoked object";
290 // If b is zero, copy a. If a is shorter than b, the result is negative.
294 } else if (a.len < b.len)
295 throw "BigUnsigned::subtract: Negative result in unsigned calculation";
297 bool borrowIn, borrowOut;
300 // Set preliminary length and make room
303 // For each block index that is present in both inputs...
304 for (i = 0, borrowIn = false; i < b.len; i++) {
305 temp = a.blk[i] - b.blk[i];
306 // If a reverse rollover occurred, the result is greater than the block from a.
307 borrowOut = (temp > a.blk[i]);
308 // Handle an incoming borrow
310 borrowOut |= (temp == 0);
313 blk[i] = temp; // Save the subtraction result
314 borrowIn = borrowOut; // Pass the borrow along
316 // If there is a borrow left over, decrease blocks until
317 // one does not reverse rollover.
318 for (; i < a.len && borrowIn; i++) {
319 borrowIn = (a.blk[i] == 0);
320 blk[i] = a.blk[i] - 1;
322 // If there's still a borrow, the result is negative.
323 // Throw an exception, but zero out this object first just in case.
326 throw "BigUnsigned::subtract: Negative result in unsigned calculation";
327 } else // Copy over the rest of the blocks
328 for (; i < a.len; i++)
335 * About the multiplication and division algorithms:
337 * I searched unsucessfully for fast built-in operations like the `b_0'
338 * and `c_0' Knuth describes in Section 4.3.1 of ``The Art of Computer
339 * Programming'' (replace `place' by `Blk'):
341 * ``b_0[:] multiplication of a one-place integer by another one-place
342 * integer, giving a two-place answer;
344 * ``c_0[:] division of a two-place integer by a one-place integer,
345 * provided that the quotient is a one-place integer, and yielding
346 * also a one-place remainder.''
348 * I also missed his note that ``[b]y adjusting the word size, if
349 * necessary, nearly all computers will have these three operations
350 * available'', so I gave up on trying to use algorithms similar to his.
351 * A future version of the library might include such algorithms; I
352 * would welcome contributions from others for this.
354 * I eventually decided to use bit-shifting algorithms. To multiply `a'
355 * and `b', we zero out the result. Then, for each `1' bit in `a', we
356 * shift `b' left the appropriate amount and add it to the result.
357 * Similarly, to divide `a' by `b', we shift `b' left varying amounts,
358 * repeatedly trying to subtract it from `a'. When we succeed, we note
359 * the fact by setting a bit in the quotient. While these algorithms
360 * have the same O(n^2) time complexity as Knuth's, the ``constant factor''
361 * is likely to be larger.
363 * Because I used these algorithms, which require single-block addition
364 * and subtraction rather than single-block multiplication and division,
365 * the innermost loops of all four routines are very similar. Study one
366 * of them and all will become clear.
370 * This is a little inline function used by both the multiplication
371 * routine and the division routine.
373 * `getShiftedBlock' returns the `x'th block of `num << y'.
374 * `y' may be anything from 0 to N - 1, and `x' may be anything from
377 * Two things contribute to this block:
379 * (1) The `N - y' low bits of `num.blk[x]', shifted `y' bits left.
381 * (2) The `y' high bits of `num.blk[x-1]', shifted `N - y' bits right.
383 * But we must be careful if `x == 0' or `x == num.len', in
384 * which case we should use 0 instead of (2) or (1), respectively.
386 * If `y == 0', then (2) contributes 0, as it should. However,
387 * in some computer environments, for a reason I cannot understand,
388 * `a >> b' means `a >> (b % N)'. This means `num.blk[x-1] >> (N - y)'
389 * will return `num.blk[x-1]' instead of the desired 0 when `y == 0';
390 * the test `y == 0' handles this case specially.
392 inline BigUnsigned::Blk getShiftedBlock(const BigUnsigned &num,
393 BigUnsigned::Index x, unsigned int y) {
394 BigUnsigned::Blk part1 = (x == 0 || y == 0) ? 0 : (num.blk[x - 1] >> (BigUnsigned::N - y));
395 BigUnsigned::Blk part2 = (x == num.len) ? 0 : (num.blk[x] << y);
396 return part1 | part2;
400 void BigUnsigned::multiply(const BigUnsigned &a, const BigUnsigned &b) {
401 // Block unsafe calls
402 if (this == &a || this == &b)
403 throw "BigUnsigned::multiply: One of the arguments is the invoked object";
404 // If either a or b is zero, set to zero.
405 if (a.len == 0 || b.len == 0) {
413 * For each 1-bit of `a' (say the `i2'th bit of block `i'):
414 * Add `b << (i blocks and i2 bits)' to *this.
416 // Variables for the calculation
420 bool carryIn, carryOut;
421 // Set preliminary length and make room
424 // Zero out this object
425 for (i = 0; i < len; i++)
427 // For each block of the first number...
428 for (i = 0; i < a.len; i++) {
429 // For each 1-bit of that block...
430 for (i2 = 0; i2 < N; i2++) {
431 if ((a.blk[i] & (1 << i2)) == 0)
434 * Add b to this, shifted left i blocks and i2 bits.
435 * j is the index in b, and k = i + j is the index in this.
437 * `getShiftedBlock', a short inline function defined above,
438 * is now used for the bit handling. It replaces the more
439 * complex `bHigh' code, in which each run of the loop dealt
440 * immediately with the low bits and saved the high bits to
441 * be picked up next time. The last run of the loop used to
442 * leave leftover high bits, which were handled separately.
443 * Instead, this loop runs an additional time with j == b.len.
444 * These changes were made on 2005.01.11.
446 for (j = 0, k = i, carryIn = false; j <= b.len; j++, k++) {
448 * The body of this loop is very similar to the body of the first loop
449 * in `add', except that this loop does a `+=' instead of a `+'.
451 temp = blk[k] + getShiftedBlock(b, j, i2);
452 carryOut = (temp < blk[k]);
455 carryOut |= (temp == 0);
460 // No more extra iteration to deal with `bHigh'.
461 // Roll-over a carry as necessary.
462 for (; carryIn; k++) {
464 carryIn = (blk[k] == 0);
468 // Zap possible leading zero
469 if (blk[len - 1] == 0)
474 * DIVISION WITH REMAINDER
475 * The functionality of divide, modulo, and %= is included in this one monstrous call,
476 * which deserves some explanation.
478 * The division *this / b is performed.
479 * Afterwards, q has the quotient, and *this has the remainder.
480 * Thus, a call is like q = *this / b, *this %= b.
482 * This seemingly bizarre pattern of inputs and outputs has a justification. The
483 * ``put-here operations'' are supposed to be fast. Therefore, they accept inputs
484 * and provide outputs in the most convenient places so that no value ever needs
485 * to be copied in its entirety. That way, the client can perform exactly the
486 * copying it needs depending on where the inputs are and where it wants the output.
488 void BigUnsigned::divideWithRemainder(const BigUnsigned &b, BigUnsigned &q) {
489 // Block unsafe calls
490 if (this == &b || &q == &b || this == &q)
491 throw "BigUnsigned::divideWithRemainder: Some two objects involved are the same";
494 * Note that the mathematical definition of mod (I'm trusting Knuth) is somewhat
495 * different from the way the normal C++ % operator behaves in the case of division by 0.
496 * This function does it Knuth's way.
498 * We let a / 0 == 0 (it doesn't matter) and a % 0 == a, no exceptions thrown.
499 * This allows us to preserve both Knuth's demand that a mod 0 == a
500 * and the useful property that (a / b) * b + (a % b) == a.
508 * If *this.len < b.len, then *this < b, and we can be sure that b doesn't go into
509 * *this at all. The quotient is 0 and *this is already the remainder (so leave it alone).
517 * At this point we know *this > b > 0. (Whew!)
523 * For each appropriate i and i2, decreasing:
524 * Try to subtract (b << (i blocks and i2 bits)) from *this.
525 * (`work2' holds the result of this subtraction.)
526 * If the result is nonnegative:
527 * Turn on bit i2 of block i of the quotient q.
528 * Save the result of the subtraction back into *this.
530 * Bit i2 of block i remains off, and *this is unchanged.
532 * Eventually q will contain the entire quotient, and *this will
533 * be left with the remainder.
535 * We use work2 to temporarily store the result of a subtraction.
536 * work2[x] corresponds to blk[x], not blk[x+i], since 2005.01.11.
537 * If the subtraction is successful, we copy work2 back to blk.
538 * (There's no `work1'. In a previous version, when division was
539 * coded for a read-only dividend, `work1' played the role of
540 * the here-modifiable `*this' and got the remainder.)
542 * We never touch the i lowest blocks of either blk or work2 because
543 * they are unaffected by the subtraction: we are subtracting
544 * (b << (i blocks and i2 bits)), which ends in at least `i' zero blocks.
546 // Variables for the calculation
550 bool borrowIn, borrowOut;
553 * Make sure we have an extra zero block just past the value.
555 * When we attempt a subtraction, we might shift `b' so
556 * its first block begins a few bits left of the dividend,
557 * and then we'll try to compare these extra bits with
558 * a nonexistent block to the left of the dividend. The
559 * extra zero block ensures sensible behavior; we need
560 * an extra block in `work2' for exactly the same reason.
562 * See below `divideWithRemainder' for the interesting and
563 * amusing story of this section of code.
565 Index origLen = len; // Save real length.
566 len++; // Increase the length.
567 allocateAndCopy(len); // Get the space.
568 blk[origLen] = 0; // Zero the extra block.
570 // work2 holds part of the result of a subtraction; see above.
571 Blk *work2 = new Blk[len];
573 // Set preliminary length for quotient and make room
574 q.len = origLen - b.len + 1;
576 // Zero out the quotient
577 for (i = 0; i < q.len; i++)
580 // For each possible left-shift of b in blocks...
584 // For each possible left-shift of b in bits...
585 // (Remember, N is the number of bits in a Blk.)
591 * Subtract b, shifted left i blocks and i2 bits, from *this,
592 * and store the answer in work2. In the for loop, `k == i + j'.
594 * Compare this to the middle section of `multiply'. They
595 * are in many ways analogous. See especially the discussion
596 * of `getShiftedBlock'.
598 for (j = 0, k = i, borrowIn = false; j <= b.len; j++, k++) {
599 temp = blk[k] - getShiftedBlock(b, j, i2);
600 borrowOut = (temp > blk[k]);
602 borrowOut |= (temp == 0);
605 // Since 2005.01.11, indices of `work2' directly match those of `blk', so use `k'.
607 borrowIn = borrowOut;
609 // No more extra iteration to deal with `bHigh'.
610 // Roll-over a borrow as necessary.
611 for (; k < origLen && borrowIn; k++) {
612 borrowIn = (blk[k] == 0);
613 work2[k] = blk[k] - 1;
616 * If the subtraction was performed successfully (!borrowIn),
617 * set bit i2 in block i of the quotient.
619 * Then, copy the portion of work2 filled by the subtraction
620 * back to *this. This portion starts with block i and ends--
621 * where? Not necessarily at block `i + b.len'! Well, we
622 * increased k every time we saved a block into work2, so
623 * the region of work2 we copy is just [i, k).
626 q.blk[i] |= (1 << i2);
634 // Zap possible leading zero in quotient
635 if (q.blk[q.len - 1] == 0)
637 // Zap any/all leading zeros in remainder
639 // Deallocate temporary array.
640 // (Thanks to Brad Spencer for noticing my accidental omission of this!)
645 * The out-of-bounds accesses story:
647 * On 2005.01.06 or 2005.01.07 (depending on your time zone),
648 * Milan Tomic reported out-of-bounds memory accesses in
649 * the Big Integer Library. To investigate the problem, I
650 * added code to bounds-check every access to the `blk' array
651 * of a `NumberlikeArray'.
653 * This gave me warnings that fell into two categories of false
654 * positives. The bounds checker was based on length, not
655 * capacity, and in two places I had accessed memory that I knew
656 * was inside the capacity but that wasn't inside the length:
658 * (1) The extra zero block at the left of `*this'. Earlier
659 * versions said `allocateAndCopy(len + 1); blk[len] = 0;'
660 * but did not increment `len'.
662 * (2) The entire digit array in the conversion constructor
663 * ``BigUnsignedInABase(BigUnsigned)''. It was allocated with
664 * a conservatively high capacity, but the length wasn't set
665 * until the end of the constructor.
667 * To simplify matters, I changed both sections of code so that
668 * all accesses occurred within the length. The messages went
669 * away, and I told Milan that I couldn't reproduce the problem,
670 * sending a development snapshot of the bounds-checked code.
672 * Then, on 2005.01.09-10, he told me his debugger still found
673 * problems, specifically at the line `delete [] work2'.
674 * It was `work2', not `blk', that was causing the problems;
675 * this possibility had not occurred to me at all. In fact,
676 * the problem was that `work2' needed an extra block just
677 * like `*this'. Go ahead and laugh at me for finding (1)
678 * without seeing what was actually causing the trouble. :-)
680 * The 2005.01.11 version fixes this problem. I hope this is
681 * the last of my memory-related bloopers. So this is what
682 * starts happening to your C++ code if you use Java too much!
686 void BigUnsigned::bitAnd(const BigUnsigned &a, const BigUnsigned &b) {
687 // Block unsafe calls
688 if (this == &a || this == &b)
689 throw "BigUnsigned::bitAnd: One of the arguments is the invoked object";
690 len = (a.len >= b.len) ? b.len : a.len;
693 for (i = 0; i < len; i++)
694 blk[i] = a.blk[i] & b.blk[i];
699 void BigUnsigned::bitOr(const BigUnsigned &a, const BigUnsigned &b) {
700 // Block unsafe calls
701 if (this == &a || this == &b)
702 throw "BigUnsigned::bitOr: One of the arguments is the invoked object";
704 const BigUnsigned *a2, *b2;
705 if (a.len >= b.len) {
713 for (i = 0; i < b2->len; i++)
714 blk[i] = a2->blk[i] | b2->blk[i];
715 for (; i < a2->len; i++)
721 void BigUnsigned::bitXor(const BigUnsigned &a, const BigUnsigned &b) {
722 // Block unsafe calls
723 if (this == &a || this == &b)
724 throw "BigUnsigned::bitXor: One of the arguments is the invoked object";
726 const BigUnsigned *a2, *b2;
727 if (a.len >= b.len) {
735 for (i = 0; i < b2->len; i++)
736 blk[i] = a2->blk[i] ^ b2->blk[i];
737 for (; i < a2->len; i++)
743 // INCREMENT/DECREMENT OPERATORS
746 void BigUnsigned::operator ++() {
749 for (i = 0; i < len && carry; i++) {
751 carry = (blk[i] == 0);
754 // Matt fixed a bug 2004.12.24: next 2 lines used to say allocateAndCopy(len + 1)
756 allocateAndCopy(len);
761 // Postfix increment: same as prefix
762 void BigUnsigned::operator ++(int) {
767 void BigUnsigned::operator --() {
769 throw "BigUnsigned::operator --(): Cannot decrement an unsigned zero";
772 for (i = 0; borrow; i++) {
773 borrow = (blk[i] == 0);
776 // Zap possible leading zero (there can only be one)
777 if (blk[len - 1] == 0)
781 // Postfix decrement: same as prefix
782 void BigUnsigned::operator --(int) {