4 #include "NumberlikeArray.hh"
6 /* A BigUnsigned object represents a nonnegative integer of size limited only by
7 * available memory. BigUnsigneds support most mathematical operators and can
8 * be converted to and from most primitive integer types.
10 * The number is stored as a NumberlikeArray of unsigned longs as if it were
11 * written in base 256^sizeof(unsigned long). The least significant block is
12 * first, and the length is such that the most significant block is nonzero. */
13 class BigUnsigned : protected NumberlikeArray<unsigned long> {
16 // Enumeration for the result of a comparison.
17 enum CmpRes { less = -1, equal = 0, greater = 1 };
19 // BigUnsigneds are built with a Blk type of unsigned long.
20 typedef unsigned long Blk;
22 typedef NumberlikeArray<Blk>::Index Index;
23 NumberlikeArray<Blk>::N;
26 // Creates a BigUnsigned with a capacity; for internal use.
27 BigUnsigned(int, Index c) : NumberlikeArray<Blk>(0, c) {}
29 // Decreases len to eliminate any leading zero blocks.
30 void zapLeadingZeros() {
31 while (len > 0 && blk[len - 1] == 0)
37 BigUnsigned() : NumberlikeArray<Blk>() {}
40 BigUnsigned(const BigUnsigned &x) : NumberlikeArray<Blk>(x) {}
42 // Assignment operator
43 void operator=(const BigUnsigned &x) {
44 NumberlikeArray<Blk>::operator =(x);
47 // Constructor that copies from a given array of blocks.
48 BigUnsigned(const Blk *b, Index blen) : NumberlikeArray<Blk>(b, blen) {
49 // Eliminate any leading zeros we may have been passed.
53 // Destructor. NumberlikeArray does the delete for us.
56 // Constructors from primitive integer types
57 BigUnsigned(unsigned long x);
59 BigUnsigned(unsigned int x);
61 BigUnsigned(unsigned short x);
62 BigUnsigned( short x);
65 template <class X> void initFromPrimitive (X x);
66 template <class X> void initFromSignedPrimitive(X x);
69 /* Converters to primitive integer types
70 * The implicit conversion operators caused trouble, so these are now
72 unsigned long toUnsignedLong () const;
74 unsigned int toUnsignedInt () const;
76 unsigned short toUnsignedShort() const;
77 short toShort () const;
80 template <class X> X convertToSignedPrimitive() const;
81 template <class X> X convertToPrimitive () const;
86 // Expose these from NumberlikeArray directly.
87 NumberlikeArray<Blk>::getCapacity;
88 NumberlikeArray<Blk>::getLength;
90 /* Returns the requested block, or 0 if it is beyond the length (as if
91 * the number had 0s infinitely to the left). */
92 Blk getBlock(Index i) const { return i >= len ? 0 : blk[i]; }
94 // The number is zero if and only if the canonical length is zero.
95 bool isZero() const { return NumberlikeArray<Blk>::isEmpty(); }
99 // Compares this to x like Perl's <=>
100 CmpRes compareTo(const BigUnsigned &x) const;
102 // Ordinary comparison operators
103 bool operator ==(const BigUnsigned &x) const {
104 return NumberlikeArray<Blk>::operator ==(x);
106 bool operator !=(const BigUnsigned &x) const {
107 return NumberlikeArray<Blk>::operator !=(x);
109 bool operator < (const BigUnsigned &x) const { return compareTo(x) == less ; }
110 bool operator <=(const BigUnsigned &x) const { return compareTo(x) != greater; }
111 bool operator >=(const BigUnsigned &x) const { return compareTo(x) != less ; }
112 bool operator > (const BigUnsigned &x) const { return compareTo(x) == greater; }
115 * BigUnsigned and BigInteger both provide three kinds of operators.
116 * Here ``big-integer'' refers to BigInteger or BigUnsigned.
118 * (1) Overloaded ``return-by-value'' operators:
119 * +, -, *, /, %, unary -, &, |, ^, <<, >>.
120 * Big-integer code using these operators looks identical to code using
121 * the primitive integer types. These operators take one or two
122 * big-integer inputs and return a big-integer result, which can then
123 * be assigned to a BigInteger variable or used in an expression.
125 * BigInteger a(1), b = 1;
126 * BigInteger c = a + b;
128 * (2) Overloaded assignment operators:
129 * +=, -=, *=, /=, %=, flipSign, &=, |=, ^=, <<=, >>=, ++, --.
130 * Again, these are used on big integers just like on ints. They take
131 * one writable big integer that both provides an operand and receives a
132 * result. Most also take a second read-only operand.
134 * BigInteger a(1), b(1);
137 * (3) Copy-less operations: `add', `subtract', etc.
138 * These named methods take operands as arguments and store the result
139 * in the receiver (*this), avoiding unnecessary copies and allocations.
140 * `divideWithRemainder' is special: it both takes the dividend from and
141 * stores the remainder into the receiver, and it takes a separate
142 * object in which to store the quotient. NOTE: If you are wondering
143 * why these don't return a value, you probably mean to use the
144 * overloaded return-by-value operators instead.
147 * BigInteger a(43), b(7), c, d;
149 * c = a + b; // Now c == 50.
150 * c.add(a, b); // Same effect but without the two copies.
152 * c.divideWithRemainder(b, d);
153 * // 50 / 7; now d == 7 (quotient) and c == 1 (remainder).
155 * // ``Aliased'' calls now do the right thing using a temporary
156 * // copy, but see note on `divideWithRemainder'.
160 // COPY-LESS OPERATIONS
162 // These 8: Arguments are read-only operands, result is saved in *this.
163 void add(const BigUnsigned &a, const BigUnsigned &b);
164 void subtract(const BigUnsigned &a, const BigUnsigned &b);
165 void multiply(const BigUnsigned &a, const BigUnsigned &b);
166 void bitAnd(const BigUnsigned &a, const BigUnsigned &b);
167 void bitOr(const BigUnsigned &a, const BigUnsigned &b);
168 void bitXor(const BigUnsigned &a, const BigUnsigned &b);
169 /* Negative shift amounts translate to opposite-direction shifts,
170 * except for -2^(8*sizeof(int)-1) which is unimplemented. */
171 void bitShiftLeft(const BigUnsigned &a, int b);
172 void bitShiftRight(const BigUnsigned &a, int b);
174 /* `a.divideWithRemainder(b, q)' is like `q = a / b, a %= b'.
175 * / and % use semantics similar to Knuth's, which differ from the
176 * primitive integer semantics under division by zero. See the
177 * implementation in BigUnsigned.cc for details.
178 * `a.divideWithRemainder(b, a)' throws an exception: it doesn't make
179 * sense to write quotient and remainder into the same variable. */
180 void divideWithRemainder(const BigUnsigned &b, BigUnsigned &q);
182 /* `divide' and `modulo' are no longer offered. Use
183 * `divideWithRemainder' instead. */
185 // OVERLOADED RETURN-BY-VALUE OPERATORS
186 BigUnsigned operator +(const BigUnsigned &x) const;
187 BigUnsigned operator -(const BigUnsigned &x) const;
188 BigUnsigned operator *(const BigUnsigned &x) const;
189 BigUnsigned operator /(const BigUnsigned &x) const;
190 BigUnsigned operator %(const BigUnsigned &x) const;
191 /* OK, maybe unary minus could succeed in one case, but it really
192 * shouldn't be used, so it isn't provided. */
193 BigUnsigned operator &(const BigUnsigned &x) const;
194 BigUnsigned operator |(const BigUnsigned &x) const;
195 BigUnsigned operator ^(const BigUnsigned &x) const;
196 BigUnsigned operator <<(int b) const;
197 BigUnsigned operator >>(int b) const;
199 // OVERLOADED ASSIGNMENT OPERATORS
200 void operator +=(const BigUnsigned &x);
201 void operator -=(const BigUnsigned &x);
202 void operator *=(const BigUnsigned &x);
203 void operator /=(const BigUnsigned &x);
204 void operator %=(const BigUnsigned &x);
205 void operator &=(const BigUnsigned &x);
206 void operator |=(const BigUnsigned &x);
207 void operator ^=(const BigUnsigned &x);
208 void operator <<=(int b);
209 void operator >>=(int b);
211 /* INCREMENT/DECREMENT OPERATORS
212 * To discourage messy coding, these do not return *this, so prefix
213 * and postfix behave the same. */
215 void operator ++(int);
217 void operator --(int);
219 // Helper function that needs access to BigUnsigned internals
220 friend Blk getShiftedBlock(const BigUnsigned &num, Index x,
223 // See BigInteger.cc.
225 friend X convertBigUnsignedToPrimitiveAccess(const BigUnsigned &a);
228 /* Implementing the return-by-value and assignment operators in terms of the
229 * copy-less operations. The copy-less operations are responsible for making
230 * any necessary temporary copies to work around aliasing. */
232 inline BigUnsigned BigUnsigned::operator +(const BigUnsigned &x) const {
237 inline BigUnsigned BigUnsigned::operator -(const BigUnsigned &x) const {
239 ans.subtract(*this, x);
242 inline BigUnsigned BigUnsigned::operator *(const BigUnsigned &x) const {
244 ans.multiply(*this, x);
247 inline BigUnsigned BigUnsigned::operator /(const BigUnsigned &x) const {
248 if (x.isZero()) throw "BigUnsigned::operator /: division by zero";
251 r.divideWithRemainder(x, q);
254 inline BigUnsigned BigUnsigned::operator %(const BigUnsigned &x) const {
255 if (x.isZero()) throw "BigUnsigned::operator %: division by zero";
258 r.divideWithRemainder(x, q);
261 inline BigUnsigned BigUnsigned::operator &(const BigUnsigned &x) const {
263 ans.bitAnd(*this, x);
266 inline BigUnsigned BigUnsigned::operator |(const BigUnsigned &x) const {
271 inline BigUnsigned BigUnsigned::operator ^(const BigUnsigned &x) const {
273 ans.bitXor(*this, x);
276 inline BigUnsigned BigUnsigned::operator <<(int b) const {
278 ans.bitShiftLeft(*this, b);
281 inline BigUnsigned BigUnsigned::operator >>(int b) const {
283 ans.bitShiftRight(*this, b);
287 inline void BigUnsigned::operator +=(const BigUnsigned &x) {
290 inline void BigUnsigned::operator -=(const BigUnsigned &x) {
293 inline void BigUnsigned::operator *=(const BigUnsigned &x) {
296 inline void BigUnsigned::operator /=(const BigUnsigned &x) {
297 if (x.isZero()) throw "BigUnsigned::operator /=: division by zero";
298 /* The following technique is slightly faster than copying *this first
299 * when x is large. */
301 divideWithRemainder(x, q);
302 // *this contains the remainder, but we overwrite it with the quotient.
305 inline void BigUnsigned::operator %=(const BigUnsigned &x) {
306 if (x.isZero()) throw "BigUnsigned::operator %=: division by zero";
308 // Mods *this by x. Don't care about quotient left in q.
309 divideWithRemainder(x, q);
311 inline void BigUnsigned::operator &=(const BigUnsigned &x) {
314 inline void BigUnsigned::operator |=(const BigUnsigned &x) {
317 inline void BigUnsigned::operator ^=(const BigUnsigned &x) {
320 inline void BigUnsigned::operator <<=(int b) {
321 bitShiftLeft(*this, b);
323 inline void BigUnsigned::operator >>=(int b) {
324 bitShiftRight(*this, b);
327 /* Templates for conversions of BigUnsigned to and from primitive integers.
328 * BigInteger.cc needs to instantiate convertToPrimitive, and the uses in
329 * BigUnsigned.cc didn't do the trick; I think gcc inlined convertToPrimitive
330 * instead of generating linkable instantiations. So for consistency, I put
331 * all the templates here. */
333 // CONSTRUCTION FROM PRIMITIVE INTEGERS
335 /* Initialize this BigUnsigned from the given primitive integer. The same
336 * pattern works for all primitive integer types, so I put it into a template to
337 * reduce code duplication. (Don't worry: this is protected and we instantiate
338 * it only with primitive integer types.) Type X could be signed, but x is
339 * known to be nonnegative. */
341 void BigUnsigned::initFromPrimitive(X x) {
343 ; // NumberlikeArray already initialized us to zero.
345 // Create a single block. blk is NULL; no need to delete it.
353 /* Ditto, but first check that x is nonnegative. I could have put the check in
354 * initFromPrimitive and let the compiler optimize it out for unsigned-type
355 * instantiations, but I wanted to avoid the warning stupidly issued by g++ for
356 * a condition that is constant in *any* instantiation, even if not in all. */
358 void BigUnsigned::initFromSignedPrimitive(X x) {
360 throw "BigUnsigned constructor: "
361 "Cannot construct a BigUnsigned from a negative number";
363 initFromPrimitive(x);
366 // CONVERSION TO PRIMITIVE INTEGERS
368 /* Template with the same idea as initFromPrimitive. This might be slightly
369 * slower than the previous version with the masks, but it's much shorter and
370 * clearer, which is the library's stated goal. */
372 X BigUnsigned::convertToPrimitive() const {
374 // The number is zero; return zero.
377 // The single block might fit in an X. Try the conversion.
379 // Make sure the result accurately represents the block.
380 if (Blk(x) == blk[0])
381 // Successful conversion.
383 // Otherwise fall through.
385 throw "BigUnsigned::to<Primitive>: "
386 "Value is too big to fit in the requested type";
389 /* Wrap the above in an x >= 0 test to make sure we got a nonnegative result,
390 * not a negative one that happened to convert back into the correct nonnegative
391 * one. (E.g., catch incorrect conversion of 2^31 to the long -2^31.) Again,
392 * separated to avoid a g++ warning. */
394 X BigUnsigned::convertToSignedPrimitive() const {
395 X x = convertToPrimitive<X>();
399 throw "BigUnsigned::to(Primitive): "
400 "Value is too big to fit in the requested type";