- Improve comments for the new BigUnsigned accessors.
[bigint/bigint.git] / BigInteger.cc
CommitLineData
05780f4b 1#include "BigInteger.hh"
e67d6049 2
e67d6049
MM
3void BigInteger::operator =(const BigInteger &x) {
4 // Calls like a = a have no effect
5 if (this == &x)
6 return;
7 // Copy sign
8 sign = x.sign;
9 // Copy the rest
3e132790 10 mag = x.mag;
e67d6049
MM
11}
12
3e132790 13BigInteger::BigInteger(const Blk *b, Index blen, Sign s) : mag(b, blen) {
e67d6049 14 switch (s) {
3e132790
MM
15 case zero:
16 case positive:
17 case negative:
18 sign = mag.isZero() ? zero : s;
e67d6049 19 break;
3e132790
MM
20 default:
21 throw "BigInteger::BigInteger(const Blk *, Index, Sign): Invalid sign";
e67d6049
MM
22 }
23}
24
3e132790 25BigInteger::BigInteger(const BigUnsigned &x, Sign s) : mag(x) {
e67d6049 26 switch (s) {
3e132790
MM
27 case zero:
28 case positive:
29 case negative:
30 sign = mag.isZero() ? zero : s;
e67d6049 31 break;
3e132790 32 default:
05780f4b 33 throw "BigInteger::BigInteger(Blk *, Index, Sign): Invalid sign";
e67d6049
MM
34 }
35}
36
3e132790
MM
37/* CONSTRUCTION FROM PRIMITIVE INTEGERS
38 * Same idea as in BigUnsigned.cc, except that negative input results in a
39 * negative BigInteger instead of an exception. */
e67d6049 40
3e132790 41// Done longhand to let us use initialization.
83a639e6
MM
42BigInteger::BigInteger(unsigned long x) : mag(x) { sign = mag.isZero() ? zero : positive; }
43BigInteger::BigInteger(unsigned int x) : mag(x) { sign = mag.isZero() ? zero : positive; }
44BigInteger::BigInteger(unsigned short x) : mag(x) { sign = mag.isZero() ? zero : positive; }
e67d6049 45
3e132790 46// For signed input, determine the desired magnitude and sign separately.
e67d6049 47
3e132790
MM
48namespace {
49 template <class X, class UX>
50 BigInteger::Blk magOf(X x) {
51 /* UX(...) cast needed to stop short(-2^15), which negates to
52 * itself, from sign-extending in the conversion to Blk. */
53 return BigInteger::Blk(x < 0 ? UX(-x) : x);
54 }
55 template <class X>
56 BigInteger::Sign signOf(X x) {
57 return (x == 0) ? BigInteger::zero
58 : (x > 0) ? BigInteger::positive
59 : BigInteger::negative;
e67d6049
MM
60 }
61}
62
83a639e6
MM
63BigInteger::BigInteger(long x) : sign(signOf(x)), mag(magOf<long , unsigned long >(x)) {}
64BigInteger::BigInteger(int x) : sign(signOf(x)), mag(magOf<int , unsigned int >(x)) {}
65BigInteger::BigInteger(short x) : sign(signOf(x)), mag(magOf<short, unsigned short>(x)) {}
3e132790
MM
66
67// CONVERSION TO PRIMITIVE INTEGERS
68
69/* Reuse BigUnsigned's conversion to an unsigned primitive integer.
70 * The friend is a separate function rather than
71 * BigInteger::convertToUnsignedPrimitive to avoid requiring BigUnsigned to
72 * declare BigInteger. */
73template <class X>
74inline X convertBigUnsignedToPrimitiveAccess(const BigUnsigned &a) {
75 return a.convertToPrimitive<X>();
e67d6049
MM
76}
77
3e132790
MM
78template <class X>
79X BigInteger::convertToUnsignedPrimitive() const {
80 if (sign == negative)
81 throw "BigInteger::to<Primitive>: "
82 "Cannot convert a negative integer to an unsigned type";
83 else
84 return convertBigUnsignedToPrimitiveAccess<X>(mag);
e67d6049
MM
85}
86
3e132790
MM
87/* Similar to BigUnsigned::convertToPrimitive, but split into two cases for
88 * nonnegative and negative numbers. */
89template <class X, class UX>
90X BigInteger::convertToSignedPrimitive() const {
91 if (sign == zero)
e67d6049 92 return 0;
3e132790
MM
93 else if (mag.getLength() == 1) {
94 // The single block might fit in an X. Try the conversion.
95 Blk b = mag.getBlock(0);
96 if (sign == positive) {
97 X x = X(b);
98 if (x >= 0 && Blk(x) == b)
99 return x;
100 } else {
101 X x = -X(b);
102 /* UX(...) needed to avoid rejecting conversion of
103 * -2^15 to a short. */
104 if (x < 0 && Blk(UX(-x)) == b)
105 return x;
106 }
107 // Otherwise fall through.
e67d6049 108 }
3e132790
MM
109 throw "BigInteger::to<Primitive>: "
110 "Value is too big to fit in the requested type";
e67d6049
MM
111}
112
83a639e6
MM
113unsigned long BigInteger::toUnsignedLong () const { return convertToUnsignedPrimitive<unsigned long > (); }
114unsigned int BigInteger::toUnsignedInt () const { return convertToUnsignedPrimitive<unsigned int > (); }
115unsigned short BigInteger::toUnsignedShort() const { return convertToUnsignedPrimitive<unsigned short> (); }
116long BigInteger::toLong () const { return convertToSignedPrimitive <long , unsigned long> (); }
117int BigInteger::toInt () const { return convertToSignedPrimitive <int , unsigned int> (); }
118short BigInteger::toShort () const { return convertToSignedPrimitive <short, unsigned short>(); }
e67d6049
MM
119
120// COMPARISON
121BigInteger::CmpRes BigInteger::compareTo(const BigInteger &x) const {
122 // A greater sign implies a greater number
123 if (sign < x.sign)
124 return less;
125 else if (sign > x.sign)
126 return greater;
127 else switch (sign) {
128 // If the signs are the same...
3e132790 129 case zero:
e67d6049 130 return equal; // Two zeros are equal
3e132790 131 case positive:
e67d6049 132 // Compare the magnitudes
3e132790
MM
133 return mag.compareTo(x.mag);
134 case negative:
e67d6049 135 // Compare the magnitudes, but return the opposite result
3e132790
MM
136 return CmpRes(-mag.compareTo(x.mag));
137 default:
138 throw "BigInteger internal error";
e67d6049
MM
139 }
140}
141
3e132790
MM
142/* COPY-LESS OPERATIONS
143 * These do some messing around to determine the sign of the result,
144 * then call one of BigUnsigned's copy-less operations. */
e67d6049 145
8c16728a 146// See remarks about aliased calls in BigUnsigned.cc .
a8e1d2a4 147#define DTRT_ALIASED(cond, op) \
8c16728a
MM
148 if (cond) { \
149 BigInteger tmpThis; \
150 tmpThis.op; \
151 *this = tmpThis; \
152 return; \
153 }
154
e67d6049 155void BigInteger::add(const BigInteger &a, const BigInteger &b) {
a8e1d2a4 156 DTRT_ALIASED(this == &a || this == &b, add(a, b));
e67d6049
MM
157 // If one argument is zero, copy the other.
158 if (a.sign == zero)
159 operator =(b);
160 else if (b.sign == zero)
161 operator =(a);
162 // If the arguments have the same sign, take the
163 // common sign and add their magnitudes.
164 else if (a.sign == b.sign) {
165 sign = a.sign;
3e132790 166 mag.add(a.mag, b.mag);
e67d6049
MM
167 } else {
168 // Otherwise, their magnitudes must be compared.
3e132790
MM
169 switch (a.mag.compareTo(b.mag)) {
170 case equal:
e67d6049 171 // If their magnitudes are the same, copy zero.
3e132790 172 mag = 0;
e67d6049
MM
173 sign = zero;
174 break;
175 // Otherwise, take the sign of the greater, and subtract
176 // the lesser magnitude from the greater magnitude.
3e132790 177 case greater:
e67d6049 178 sign = a.sign;
3e132790 179 mag.subtract(a.mag, b.mag);
e67d6049 180 break;
3e132790 181 case less:
e67d6049 182 sign = b.sign;
3e132790 183 mag.subtract(b.mag, a.mag);
e67d6049
MM
184 break;
185 }
186 }
187}
188
e67d6049
MM
189void BigInteger::subtract(const BigInteger &a, const BigInteger &b) {
190 // Notice that this routine is identical to BigInteger::add,
191 // if one replaces b.sign by its opposite.
a8e1d2a4 192 DTRT_ALIASED(this == &a || this == &b, subtract(a, b));
e67d6049
MM
193 // If a is zero, copy b and flip its sign. If b is zero, copy a.
194 if (a.sign == zero) {
3e132790 195 mag = b.mag;
f316def7
MM
196 // Take the negative of _b_'s, sign, not ours.
197 // Bug pointed out by Sam Larkin on 2005.03.30.
198 sign = Sign(-b.sign);
e67d6049 199 } else if (b.sign == zero)
f316def7 200 operator =(a);
e67d6049
MM
201 // If their signs differ, take a.sign and add the magnitudes.
202 else if (a.sign != b.sign) {
203 sign = a.sign;
3e132790 204 mag.add(a.mag, b.mag);
e67d6049
MM
205 } else {
206 // Otherwise, their magnitudes must be compared.
3e132790 207 switch (a.mag.compareTo(b.mag)) {
e67d6049 208 // If their magnitudes are the same, copy zero.
3e132790
MM
209 case equal:
210 mag = 0;
e67d6049
MM
211 sign = zero;
212 break;
213 // If a's magnitude is greater, take a.sign and
214 // subtract a from b.
3e132790 215 case greater:
e67d6049 216 sign = a.sign;
3e132790 217 mag.subtract(a.mag, b.mag);
e67d6049
MM
218 break;
219 // If b's magnitude is greater, take the opposite
220 // of b.sign and subtract b from a.
3e132790 221 case less:
e67d6049 222 sign = Sign(-b.sign);
3e132790 223 mag.subtract(b.mag, a.mag);
e67d6049
MM
224 break;
225 }
226 }
227}
228
e67d6049 229void BigInteger::multiply(const BigInteger &a, const BigInteger &b) {
a8e1d2a4 230 DTRT_ALIASED(this == &a || this == &b, multiply(a, b));
e67d6049
MM
231 // If one object is zero, copy zero and return.
232 if (a.sign == zero || b.sign == zero) {
233 sign = zero;
3e132790 234 mag = 0;
e67d6049
MM
235 return;
236 }
237 // If the signs of the arguments are the same, the result
238 // is positive, otherwise it is negative.
239 sign = (a.sign == b.sign) ? positive : negative;
240 // Multiply the magnitudes.
3e132790 241 mag.multiply(a.mag, b.mag);
e67d6049
MM
242}
243
05780f4b 244/*
6e1e0f2f
MM
245 * DIVISION WITH REMAINDER
246 * Please read the comments before the definition of
247 * `BigUnsigned::divideWithRemainder' in `BigUnsigned.cc' for lots of
248 * information you should know before reading this function.
249 *
250 * Following Knuth, I decree that x / y is to be
251 * 0 if y==0 and floor(real-number x / y) if y!=0.
252 * Then x % y shall be x - y*(integer x / y).
253 *
254 * Note that x = y * (x / y) + (x % y) always holds.
255 * In addition, (x % y) is from 0 to y - 1 if y > 0,
256 * and from -(|y| - 1) to 0 if y < 0. (x % y) = x if y = 0.
257 *
258 * Examples: (q = a / b, r = a % b)
259 * a b q r
260 * === === === ===
261 * 4 3 1 1
262 * -4 3 -2 2
263 * 4 -3 -2 -2
264 * -4 -3 1 -1
265 */
05780f4b 266void BigInteger::divideWithRemainder(const BigInteger &b, BigInteger &q) {
8c16728a
MM
267 // Defend against aliased calls;
268 // same idea as in BigUnsigned::divideWithRemainder .
269 if (this == &q)
270 throw "BigInteger::divideWithRemainder: Cannot write quotient and remainder into the same variable";
271 if (this == &b || &q == &b) {
272 BigInteger tmpB(b);
273 divideWithRemainder(tmpB, q);
274 return;
275 }
5ff40cf5 276
05780f4b
MM
277 // Division by zero gives quotient 0 and remainder *this
278 if (b.sign == zero) {
3e132790 279 q.mag = 0;
05780f4b 280 q.sign = zero;
e67d6049
MM
281 return;
282 }
05780f4b
MM
283 // 0 / b gives quotient 0 and remainder 0
284 if (sign == zero) {
3e132790 285 q.mag = 0;
05780f4b 286 q.sign = zero;
e67d6049
MM
287 return;
288 }
5ff40cf5 289
05780f4b 290 // Here *this != 0, b != 0.
5ff40cf5 291
05780f4b
MM
292 // Do the operands have the same sign?
293 if (sign == b.sign) {
294 // Yes: easy case. Quotient is zero or positive.
295 q.sign = positive;
296 } else {
297 // No: harder case. Quotient is negative.
298 q.sign = negative;
299 // Decrease the magnitude of the dividend by one.
3e132790 300 mag--;
05780f4b 301 /*
6e1e0f2f
MM
302 * We tinker with the dividend before and with the
303 * quotient and remainder after so that the result
304 * comes out right. To see why it works, consider the following
305 * list of examples, where A is the magnitude-decreased
306 * a, Q and R are the results of BigUnsigned division
307 * with remainder on A and |b|, and q and r are the
308 * final results we want:
309 *
310 * a A b Q R q r
311 * -3 -2 3 0 2 -1 0
312 * -4 -3 3 1 0 -2 2
313 * -5 -4 3 1 1 -2 1
314 * -6 -5 3 1 2 -2 0
315 *
316 * It appears that we need a total of 3 corrections:
317 * Decrease the magnitude of a to get A. Increase the
318 * magnitude of Q to get q (and make it negative).
319 * Find r = (b - 1) - R and give it the desired sign.
320 */
05780f4b 321 }
5ff40cf5 322
05780f4b 323 // Divide the magnitudes.
3e132790 324 mag.divideWithRemainder(b.mag, q.mag);
5ff40cf5 325
05780f4b
MM
326 if (sign != b.sign) {
327 // More for the harder case (as described):
328 // Increase the magnitude of the quotient by one.
3e132790 329 q.mag++;
05780f4b 330 // Modify the remainder.
3e132790
MM
331 mag.subtract(b.mag, mag);
332 mag--;
05780f4b 333 }
5ff40cf5 334
05780f4b
MM
335 // Sign of the remainder is always the sign of the divisor b.
336 sign = b.sign;
5ff40cf5 337
05780f4b 338 // Set signs to zero as necessary. (Thanks David Allen!)
3e132790 339 if (mag.isZero())
e67d6049 340 sign = zero;
3e132790 341 if (q.mag.isZero())
05780f4b 342 q.sign = zero;
5ff40cf5 343
05780f4b 344 // WHEW!!!
e67d6049
MM
345}
346
347// Negation
348void BigInteger::negate(const BigInteger &a) {
a8e1d2a4 349 DTRT_ALIASED(this == &a, negate(a));
e67d6049 350 // Copy a's magnitude
3e132790 351 mag = a.mag;
e67d6049
MM
352 // Copy the opposite of a.sign
353 sign = Sign(-a.sign);
354}
355
356// INCREMENT/DECREMENT OPERATORS
357
358// Prefix increment
359void BigInteger::operator ++() {
3e132790
MM
360 if (sign == negative) {
361 mag--;
362 if (mag == 0)
e67d6049 363 sign = zero;
3e132790
MM
364 } else {
365 mag++;
366 sign = positive; // if not already
e67d6049
MM
367 }
368}
369
370// Postfix increment: same as prefix
371void BigInteger::operator ++(int) {
372 operator ++();
373}
374
375// Prefix decrement
376void BigInteger::operator --() {
3e132790
MM
377 if (sign == positive) {
378 mag--;
379 if (mag == 0)
e67d6049 380 sign = zero;
3e132790
MM
381 } else {
382 mag++;
383 sign = negative;
e67d6049
MM
384 }
385}
386
387// Postfix decrement: same as prefix
388void BigInteger::operator --(int) {
389 operator --();
390}
391