Old snapshot `BigIntegerLibrary-2005.01.06'; see the ChangeLog file.
[bigint/bigint.git] / BigUnsigned.cc
CommitLineData
05780f4b
MM
1/*
2* Matt McCutchen's Big Integer Library
3* http://mysite.verizon.net/mccutchen/bigint/
4*/
5
6#include "BigUnsigned.hh"
7
b3fe29df 8// The "management" routines that used to be here are now in NumberlikeArray.hh.
05780f4b
MM
9
10/*
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.
b3fe29df
MM
19*
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 `blk = NULL, cap = len = 0'.
24* So if the input number is zero, they can just return.
25* See remarks in `NumberlikeArray.hh'.
05780f4b
MM
26*/
27
28BigUnsigned::BigUnsigned(unsigned long x) {
b3fe29df
MM
29 if (x == 0)
30 ; // NumberlikeArray already did all the work
31 else {
05780f4b
MM
32 cap = 1;
33 blk = new Blk[1];
34 len = 1;
35 blk[0] = Blk(x);
36 }
37}
38
39BigUnsigned::BigUnsigned(long x) {
b3fe29df
MM
40 if (x == 0)
41 ;
42 else if (x > 0) {
05780f4b
MM
43 cap = 1;
44 blk = new Blk[1];
45 len = 1;
46 blk[0] = Blk(x);
47 } else
b3fe29df 48 throw "BigUnsigned::BigUnsigned(long): Cannot construct a BigUnsigned from a negative number";
05780f4b
MM
49}
50
51BigUnsigned::BigUnsigned(unsigned int x) {
b3fe29df
MM
52 if (x == 0)
53 ;
54 else {
05780f4b
MM
55 cap = 1;
56 blk = new Blk[1];
57 len = 1;
58 blk[0] = Blk(x);
59 }
60}
61
62BigUnsigned::BigUnsigned(int x) {
b3fe29df
MM
63 if (x == 0)
64 ;
65 else if (x > 0) {
05780f4b
MM
66 cap = 1;
67 blk = new Blk[1];
68 len = 1;
69 blk[0] = Blk(x);
70 } else
b3fe29df 71 throw "BigUnsigned::BigUnsigned(int): Cannot construct a BigUnsigned from a negative number";
05780f4b
MM
72}
73
74BigUnsigned::BigUnsigned(unsigned short x) {
b3fe29df
MM
75 if (x == 0)
76 ;
77 else {
05780f4b
MM
78 cap = 1;
79 blk = new Blk[1];
80 len = 1;
81 blk[0] = Blk(x);
82 }
83}
84
85BigUnsigned::BigUnsigned(short x) {
b3fe29df
MM
86 if (x == 0)
87 ;
88 else if (x > 0) {
05780f4b
MM
89 cap = 1;
90 blk = new Blk[1];
91 len = 1;
92 blk[0] = Blk(x);
93 } else
b3fe29df 94 throw "BigUnsigned::BigUnsigned(short): Cannot construct a BigUnsigned from a negative number";
05780f4b
MM
95}
96
97// CONVERTERS
98/*
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.
107*/
108
109namespace {
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;
118}
119
120BigUnsigned::operator unsigned long() const {
121 if (len == 0)
122 return 0;
123 else if (len == 1)
124 return (unsigned long) blk[0];
125 else
126 throw "BigUnsigned::operator unsigned long: Value is too big for an unsigned long";
127}
128
129BigUnsigned::operator long() const {
130 if (len == 0)
131 return 0;
132 else if (len == 1 && (blk[0] & lMask) == blk[0])
133 return (long) blk[0];
134 else
135 throw "BigUnsigned::operator long: Value is too big for a long";
136}
137
138BigUnsigned::operator unsigned int() const {
139 if (len == 0)
140 return 0;
141 else if (len == 1 && (blk[0] & uiMask) == blk[0])
142 return (unsigned int) blk[0];
143 else
144 throw "BigUnsigned::operator unsigned int: Value is too big for an unsigned int";
145}
146
147BigUnsigned::operator int() const {
148 if (len == 0)
149 return 0;
150 else if (len == 1 && (blk[0] & iMask) == blk[0])
151 return (int) blk[0];
152 else
153 throw "BigUnsigned::operator int: Value is too big for an int";
154}
155
156BigUnsigned::operator unsigned short() const {
157 if (len == 0)
158 return 0;
159 else if (len == 1 && (blk[0] & usMask) == blk[0])
160 return (unsigned short) blk[0];
161 else
162 throw "BigUnsigned::operator unsigned short: Value is too big for an unsigned short";
163}
164
165BigUnsigned::operator short() const {
166 if (len == 0)
167 return 0;
168 else if (len == 1 && (blk[0] & sMask) == blk[0])
169 return (short) blk[0];
170 else
171 throw "BigUnsigned::operator short: Value is too big for a short";
172}
173
174// COMPARISON
175BigUnsigned::CmpRes BigUnsigned::compareTo(const BigUnsigned &x) const {
176 // A bigger length implies a bigger number.
177 if (len < x.len)
178 return less;
179 else if (len > x.len)
180 return greater;
181 else {
182 // Compare blocks one by one from left to right.
183 Index i = len;
184 while (i > 0) {
185 i--;
186 if (blk[i] == x.blk[i])
187 continue;
188 else if (blk[i] > x.blk[i])
189 return greater;
190 else
191 return less;
192 }
193 // If no blocks differed, the numbers are equal.
194 return equal;
195 }
196}
197
198// PUT-HERE OPERATIONS
199
200// Addition
201void BigUnsigned::add(const BigUnsigned &a, const BigUnsigned &b) {
202 // Block unsafe calls
203 if (this == &a || this == &b)
204 throw "BigUnsigned::add: One of the arguments is the invoked object";
205 // If one argument is zero, copy the other.
206 if (a.len == 0) {
207 operator =(b);
208 return;
209 } else if (b.len == 0) {
210 operator =(a);
211 return;
212 }
213 // Carries in and out of an addition stage
214 bool carryIn, carryOut;
215 Blk temp;
216 Index i;
217 // a2 points to the longer input, b2 points to the shorter
218 const BigUnsigned *a2, *b2;
219 if (a.len >= b.len) {
220 a2 = &a;
221 b2 = &b;
222 } else {
223 a2 = &b;
224 b2 = &a;
225 }
226 // Set prelimiary length and make room in this BigUnsigned
227 len = a2->len + 1;
228 allocate(len);
229 // For each block index that is present in both inputs...
230 for (i = 0, carryIn = false; i < b2->len; i++) {
231 // Add input blocks
232 temp = a2->blk[i] + b2->blk[i];
233 // If a rollover occurred, the result is less than either input.
234 // This test is used many times in the BigUnsigned code.
235 carryOut = (temp < a2->blk[i]);
236 // If a carry was input, handle it
237 if (carryIn) {
238 temp++;
239 carryOut |= (temp == 0);
240 }
241 blk[i] = temp; // Save the addition result
242 carryIn = carryOut; // Pass the carry along
243 }
244 // If there is a carry left over, increase blocks until
245 // one does not roll over.
246 for (; i < a2->len && carryIn; i++) {
247 temp = a2->blk[i] + 1;
248 carryIn = (temp == 0);
249 blk[i] = temp;
250 }
251 // If the carry was resolved but the larger number
252 // still has blocks, copy them over.
253 for (; i < a2->len; i++)
254 blk[i] = a2->blk[i];
255 // Set the extra block if there's still a carry, decrease length otherwise
256 if (carryIn)
257 blk[i] = 1;
258 else
259 len--;
260}
261
262// Subtraction
263void BigUnsigned::subtract(const BigUnsigned &a, const BigUnsigned &b) {
264 // Block unsafe calls
265 if (this == &a || this == &b)
266 throw "BigUnsigned::subtract: One of the arguments is the invoked object";
267 // If b is zero, copy a. If a is shorter than b, the result is negative.
268 if (b.len == 0) {
269 operator =(a);
270 return;
271 } else if (a.len < b.len)
272 throw "BigUnsigned::subtract: Negative result in unsigned calculation";
273 bool borrowIn, borrowOut;
274 Blk temp;
275 Index i;
276 // Set preliminary length and make room
277 len = a.len;
278 allocate(len);
279 // For each block index that is present in both inputs...
280 for (i = 0, borrowIn = false; i < b.len; i++) {
281 temp = a.blk[i] - b.blk[i];
282 // If a reverse rollover occurred, the result is greater than the block from a.
283 borrowOut = (temp > a.blk[i]);
284 // Handle an incoming borrow
285 if (borrowIn) {
286 borrowOut |= (temp == 0);
287 temp--;
288 }
289 blk[i] = temp; // Save the subtraction result
290 borrowIn = borrowOut; // Pass the borrow along
291 }
292 // If there is a borrow left over, decrease blocks until
293 // one does not reverse rollover.
294 for (; i < a.len && borrowIn; i++) {
295 borrowIn = (a.blk[i] == 0);
296 blk[i] = a.blk[i] - 1;
297 }
298 // If there's still a borrow, the result is negative.
299 // Throw an exception, but zero out this object first just in case.
300 if (borrowIn) {
301 len = 0;
302 throw "BigUnsigned::subtract: Negative result in unsigned calculation";
303 } else // Copy over the rest of the blocks
304 for (; i < a.len; i++)
305 blk[i] = a.blk[i];
306 // Zap leading zeros
307 zapLeadingZeros();
308}
309
310// Multiplication
311void BigUnsigned::multiply(const BigUnsigned &a, const BigUnsigned &b) {
312 // Block unsafe calls
313 if (this == &a || this == &b)
314 throw "BigUnsigned::multiply: One of the arguments is the invoked object";
315 // If either a or b is zero, set to zero.
316 if (a.len == 0 || b.len == 0) {
317 len = 0;
318 return;
319 }
320 // Overall method: this = 0, then for each 1-bit of a, add b
321 // to this shifted the appropriate amount.
322 // Variables for the calculation
323 Index i, j, k;
324 unsigned int i2;
325 Blk aBlk, bHigh, temp;
326 bool carryIn, carryOut;
327 // Set preliminary length and make room
328 len = a.len + b.len;
329 allocate(len);
330 // Zero out this object
331 for (i = 0; i < len; i++)
332 blk[i] = 0;
333 // For each block of the first number...
334 for (i = 0; i < a.len; i++) {
335 // For each 1-bit of that block...
336 for (i2 = 0, aBlk = a.blk[i]; aBlk != 0; i2++, aBlk >>= 1) {
337 if ((aBlk & 1) == 0)
338 continue;
339 /* Add b to this, shifted left i blocks and i2 bits.
340 * j is the index in b, and k = i + j is the index in this.
341 * The low bits of b.blk[j] are shifted and added to blk[k].
342 * bHigh is used to carry the high bits to the next addition. */
343 bHigh = 0;
344 for (j = 0, k = i, carryIn = false; j < b.len; j++, k++) {
345 temp = blk[k] + ((b.blk[j] << i2) | bHigh);
346 carryOut = (temp < blk[k]);
347 if (carryIn) {
348 temp++;
349 carryOut |= (temp == 0);
350 }
351 blk[k] = temp;
352 carryIn = carryOut;
353 bHigh = (i2 == 0) ? 0 : b.blk[j] >> (8 * sizeof(Blk) - i2);
354 }
355 temp = blk[k] + bHigh;
356 carryOut = (temp < blk[k]);
357 if (carryIn) {
358 temp++;
359 carryOut |= (temp == 0);
360 }
361 blk[k] = temp;
362 carryIn = carryOut;
363 k++; // Added by Matt 2004.12.23: Move to the next block. It belongs here (and there was a corresponding line in the division routine), but I'm not certain whether it ever matters.
364 for (; carryIn; k++) {
365 blk[k]++;
366 carryIn = (blk[k] == 0);
367 }
368 }
369 }
370 // Zap possible leading zero
371 if (blk[len - 1] == 0)
372 len--;
373}
374
375/*
376* DIVISION WITH REMAINDER
377* The functionality of divide, modulo, and %= is included in this one monstrous call,
378* which deserves some explanation.
379*
380* The division *this / b is performed.
381* Afterwards, q has the quotient, and *this has the remainder.
382* Thus, a call is like q = *this / b, *this %= b.
383*
384* This seemingly bizarre pattern of inputs and outputs has a justification. The
385* ``put-here operations'' are supposed to be fast. Therefore, they accept inputs
386* and provide outputs in the most convenient places so that no value ever needs
387* to be copied in its entirety. That way, the client can perform exactly the
388* copying it needs depending on where the inputs are and where it wants the output.
389*/
390void BigUnsigned::divideWithRemainder(const BigUnsigned &b, BigUnsigned &q) {
391 // Block unsafe calls
392 if (this == &b || &q == &b || this == &q)
393 throw "BigUnsigned::divideWithRemainder: Some two objects involved are the same";
394
395 /*
396 * Note that the mathematical definition of mod (I'm trusting Knuth) is somewhat
397 * different from the way the normal C++ % operator behaves in the case of division by 0.
398 * This function does it Knuth's way.
399 *
400 * We let a / 0 == 0 (it doesn't matter) and a % 0 == a, no exceptions thrown.
401 * This allows us to preserve both Knuth's demand that a mod 0 == a
402 * and the useful property that (a / b) * b + (a % b) == a.
403 */
404 if (b.len == 0) {
405 q.len = 0;
406 return;
407 }
408
409 /*
410 * If *this.len < b.len, then *this < b, and we can be sure that b doesn't go into
411 * *this at all. The quotient is 0 and *this is already the remainder (so leave it alone).
412 */
413 if (len < b.len) {
414 q.len = 0;
415 return;
416 }
417
418 /*
419 * At this point we know *this > b > 0. (Whew!)
420 */
421
422 /* DEBUG *
423 std::cout << "divideWithRemainder starting\n"
424 << "length of dividend: " << len
425 << "\nlast block of dividend: " << getBlock(0)
426 << "\nlength of divisor: " << b.len
427 << "\nlast block of divisor: " << b.getBlock(0)
428 << std::endl; */
429
430 /*
431 * Overall method: Subtract b, shifted varying amounts to
432 * the left, from this, setting the bit in the quotient q
433 * whenever the subtraction succeeds. Eventually q will contain the entire
434 * quotient, and this will be left with the remainder.
435 *
436 * We use work2 to temporarily store the result of a subtraction.
437 * But we don't even compute the i lowest blocks of the result,
438 * because they are unaffected (we shift left i places).
439 * */
440 // Variables for the calculation
441 Index i, j, k;
442 unsigned int i2;
443 Blk bHigh, temp;
444 bool borrowIn, borrowOut;
445
446 // Make sure we have an extra zero block just past the value,
447 // but don't increase the logical length. A shifted subtraction
448 // (for example, subtracting 1 << 2 from 4) might stick into
449 // this block.
450 allocateAndCopy(len + 1);
451 blk[len] = 0;
452
453 // work2 holds part of the result of a subtraction.
454 // (There's no work1. The name work2 is from a previous version.)
455 Blk *work2 = new Blk[len];
456
457 // Set preliminary length for quotient and make room
458 q.len = len - b.len + 1;
459 q.allocate(q.len);
460 // Zero out the quotient
461 for (i = 0; i < q.len; i++)
462 q.blk[i] = 0;
463
464 // For each possible left-shift of b in blocks...
465 i = q.len;
466 while (i > 0) {
467 i--;
468 // For each possible left-shift of b in bits...
469 q.blk[i] = 0;
470 i2 = 8 * sizeof(Blk);
471 while (i2 > 0) {
472 i2--;
473 /*
474 * Subtract b, shifted left i blocks and i2 bits, from this.
475 * and store the answer in work2.
476 *
477 * Compare this to the middle section of `multiply'. They
478 * are in many ways analogous.
479 */
480 bHigh = 0;
481 for (j = 0, k = i, borrowIn = false; j < b.len; j++, k++) {
482 temp = blk[k] - ((b.blk[j] << i2) | bHigh);
483 borrowOut = (temp > blk[k]);
484 if (borrowIn) {
485 borrowOut |= (temp == 0);
486 temp--;
487 }
488 work2[j] = temp;
489 borrowIn = borrowOut;
490 bHigh = (i2 == 0) ? 0 : b.blk[j] >> (8 * sizeof(Blk) - i2);
491 }
492 temp = blk[k] - bHigh;
493 borrowOut = (temp > blk[k]);
494 if (borrowIn) {
495 borrowOut |= (temp == 0);
496 temp--;
497 }
498 work2[j] = temp;
499 borrowIn = borrowOut;
500 j++;
501 k++;
502 for (; k < len && borrowIn; j++, k++) {
503 borrowIn = (blk[k] == 0);
504 work2[j] = blk[k] - 1;
505 }
506 /* If the subtraction was performed successfully (!borrowIn), set bit i2
507 * in block i of the quotient, and copy the changed portion of
508 * work2 back to this. Otherwise, reset that bit and move on. */
509 if (!borrowIn) {
510 q.blk[i] |= (1 << i2);
511 while (j > 0) {
512 j--;
513 k--;
514 blk[k] = work2[j];
515 }
516 }
517 }
518 }
519 // Zap possible leading zero in quotient
520 if (q.blk[q.len - 1] == 0)
521 q.len--;
522 // Zap any/all leading zeros in remainder
523 zapLeadingZeros();
524 // Deallocate temporary array.
525 // (Thanks to Brad Spencer for noticing my accidental omission of this!)
526 delete [] work2;
527
528 /* DEBUG *
529 std::cout << "divideWithRemainder complete\n"
530 << "length of quotient: " << q.len
531 << "\nlast block of quotient: " << q.getBlock(0)
532 << "\nlength of remainder: " << len
533 << "\nlast block of remainder: " << getBlock(0)
534 << std::endl; */
535}
536
537// Bitwise and
538void BigUnsigned::bitAnd(const BigUnsigned &a, const BigUnsigned &b) {
539 // Block unsafe calls
540 if (this == &a || this == &b)
541 throw "BigUnsigned::bitAnd: One of the arguments is the invoked object";
542 len = (a.len >= b.len) ? b.len : a.len;
543 allocate(len);
544 Index i;
545 for (i = 0; i < len; i++)
546 blk[i] = a.blk[i] & b.blk[i];
547 zapLeadingZeros();
548}
549
550// Bitwise or
551void BigUnsigned::bitOr(const BigUnsigned &a, const BigUnsigned &b) {
552 // Block unsafe calls
553 if (this == &a || this == &b)
554 throw "BigUnsigned::bitOr: One of the arguments is the invoked object";
555 Index i;
556 const BigUnsigned *a2, *b2;
557 if (a.len >= b.len) {
558 a2 = &a;
559 b2 = &b;
560 } else {
561 a2 = &b;
562 b2 = &a;
563 }
564 allocate(a2->len);
565 for (i = 0; i < b2->len; i++)
566 blk[i] = a2->blk[i] | b2->blk[i];
567 for (; i < a2->len; i++)
568 blk[i] = a2->blk[i];
569 len = a2->len;
570}
571
572// Bitwise xor
573void BigUnsigned::bitXor(const BigUnsigned &a, const BigUnsigned &b) {
574 // Block unsafe calls
575 if (this == &a || this == &b)
576 throw "BigUnsigned::bitXor: One of the arguments is the invoked object";
577 Index i;
578 const BigUnsigned *a2, *b2;
579 if (a.len >= b.len) {
580 a2 = &a;
581 b2 = &b;
582 } else {
583 a2 = &b;
584 b2 = &a;
585 }
586 allocate(b2->len);
587 for (i = 0; i < b2->len; i++)
588 blk[i] = a2->blk[i] ^ b2->blk[i];
589 for (; i < a2->len; i++)
590 blk[i] = a2->blk[i];
591 len = a2->len;
592 zapLeadingZeros();
593}
594
595// INCREMENT/DECREMENT OPERATORS
596
597// Prefix increment
598void BigUnsigned::operator ++() {
599 Index i;
600 bool carry = true;
601 for (i = 0; i < len && carry; i++) {
602 blk[i]++;
603 carry = (blk[i] == 0);
604 }
605 if (carry) {
606 // Matt fixed a bug 2004.12.24: next 2 lines used to say allocateAndCopy(len + 1)
607 len++;
608 allocateAndCopy(len);
609 blk[i] = 1;
610 }
611}
612
613// Postfix increment: same as prefix
614void BigUnsigned::operator ++(int) {
615 operator ++();
616}
617
618// Prefix decrement
619void BigUnsigned::operator --() {
620 if (len == 0)
621 throw "BigUnsigned::operator --(): Cannot decrement an unsigned zero";
622 Index i;
623 bool borrow = true;
624 for (i = 0; borrow; i++) {
625 borrow = (blk[i] == 0);
626 blk[i]--;
627 }
628 // Zap possible leading zero (there can only be one)
629 if (blk[len - 1] == 0)
630 len--;
631}
632
633// Postfix decrement: same as prefix
634void BigUnsigned::operator --(int) {
635 operator --();
636}