Boost logo

Boost :

From: Eric Ford (eford_at_[hidden])
Date: 2001-09-26 18:42:25


> 2) no way (that I could fathom) to simply detect an overflow if one
> occurs, in lcm (there is a multiplication that really can overflow),
> static or runtime versions.

Indeed, I ran into this problem when trying to implement a compile
time root finder with this. What's wrong with checking for overflows
by

template<class T>
T lcm(T const & a,T const & b)
{
T zero = static_cast<T>(0);
T temp = gcd(a,b)
if(temp==zero) return zero;
T val = a / temp;
if ( b>integer_traits<T>::const_max/val )
  throw std::overflow_error(make_pair(val,b));
T val *= b;
return (val<zero) ? -val : val;
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk