bigint-2010.04.30
[bigint/bigint.git] / BigInteger.hh
index 11be062..cf6e910 100644 (file)
@@ -157,12 +157,14 @@ inline BigInteger BigInteger::operator *(const BigInteger &x) const {
        return ans;
 }
 inline BigInteger BigInteger::operator /(const BigInteger &x) const {
+       if (x.isZero()) throw "BigInteger::operator /: division by zero";
        BigInteger q, r;
        r = *this;
        r.divideWithRemainder(x, q);
        return q;
 }
 inline BigInteger BigInteger::operator %(const BigInteger &x) const {
+       if (x.isZero()) throw "BigInteger::operator %: division by zero";
        BigInteger q, r;
        r = *this;
        r.divideWithRemainder(x, q);
@@ -191,18 +193,19 @@ inline void BigInteger::operator *=(const BigInteger &x) {
        multiply(*this, x);
 }
 inline void BigInteger::operator /=(const BigInteger &x) {
-       // Updated for divideWithRemainder
-       BigInteger thisCopy(*this);
-       thisCopy.divideWithRemainder(x, *this);
-       // quotient left in *this
-       // don't care about remainder left in thisCopy
+       if (x.isZero()) throw "BigInteger::operator /=: division by zero";
+       /* The following technique is slightly faster than copying *this first
+        * when x is large. */
+       BigInteger q;
+       divideWithRemainder(x, q);
+       // *this contains the remainder, but we overwrite it with the quotient.
+       *this = q;
 }
 inline void BigInteger::operator %=(const BigInteger &x) {
-       // Shortcut (woohoo!)
+       if (x.isZero()) throw "BigInteger::operator %=: division by zero";
        BigInteger q;
+       // Mods *this by x.  Don't care about quotient left in q.
        divideWithRemainder(x, q);
-       // remainder left in *this
-       // don't care about quotient left in q
 }
 // This one is trivial
 inline void BigInteger::flipSign() {