In Python and Ruby, signed integer division truncates towards negative infinity, and signed integer modulus has the same sign the second operand:
>>>
Here is a simple implementation of floored division and modulus in C89:
#include
div_t div_floor(int x, int y)
{
div_t r = div(x, y);
if (r.rem && (x < 0) != (y < 0)) {
r.quot -= 1;
r.rem += y;
}
return r;
}
Here, div is used because it has well-defined behavior.
If you're using C++11, here is a templated implementation of floored division and modulus:
#include
template
std::tuple div_floor(Integral x, Integral y)
{
typedef std::tuple result_type;
const Integral quot = x / y;
const Integral rem = x % y;
if (rem && (x < 0) != (y < 0))
return result_type(quot - 1, rem + y);
return result_type(quot, rem);
}
In C99 and C++11, you can avoid using div since the behavior of division and modulus in C are no longer depend on the implementation.