#include #include "safeops.h" SafeInt SafeInt::operator +( SafeInt other ) { if( good() && other.good() ) { int onum = other.num; if( num > 0 && onum > 0 ) { if( num > INT_MAX - onum ) { // overflow. return SafeInt(); } } else if( num < 0 && onum < 0 ) { if( num < INT_MIN - onum ) { // underflow. return SafeInt(); } } return SafeInt( num + onum ); } else { return SafeInt(); } } SafeInt SafeInt::operator *( SafeInt other ) { if( good() && other.good() ) { int onum = other.num; if( num == 0 || onum == 0 ) { return SafeInt( 0 ); } bool neg = (num < 0) != (onum < 0); if( neg ) { if( num < INT_MIN / onum ) { return SafeInt(); } } else { if( num > INT_MAX / onum ) { return SafeInt(); } } return SafeInt( num * onum ); } else { return SafeInt(); } } SafeInt SafeInt::operator /( SafeInt other ) { if( good() && other.good() ) { int onum = other.num; if( onum == 0 ) { return SafeInt(); } else { return SafeInt( num / onum ); } } return SafeInt(); } SafeInt gcd( SafeInt a, SafeInt b ) { if( a.good() && b.good() ) { return GreatestCommonDivisor( a.getValue(), b.getValue() ); } else { return SafeInt(); } } int sign( SafeInt a ) { if( a.good() ) { int x = a.getValue(); if( x < 0 ) { return -1; } else if( x > 0 ) { return 1; } } return 0; } double ratio( SafeInt a, SafeInt b ) { if( a.good() && b.good() ) { return (double)(a.getValue()) / (double)(b.getValue()); } return 0.0; } bool divide( SafeInt a, SafeInt b, SafeInt& q, SafeInt& r ) { if( a.good() && b.good() ) { int aa = a.getValue(); int bb = b.getValue(); int qq = aa / bb; int rr = aa - qq * bb; q = SafeInt( qq ); r = SafeInt( rr ); return true; } return false; } bool good( SafeInt& m ) { return m.good(); } ostream& operator <<( ostream& os, SafeInt& si ) { if( si.good() ) { return os << si.getValue(); } else { return os << "???"; } }