div() and ldiv() from <cstdlib> can be used to explicitly compute the quotient and remainder simultaneously (at least if the processor is capable of it, anyway).
div() and ldiv() from <cstdlib> can be used to explicitly compute the quotient and remainder simultaneously (at least if the processor is capable of it, anyway).
Good point. I'm not aware of any integer divide-capable processor that doesn't also give the remainder as a side-effect - it is sort of trivial to calculate that when you do the divide - otherwise one would have to implement a separate instruction "mod" that does that, and it's not any more efficient. The same applies, by the way, to the more common versions of integer divide algorithms used on processors without hardware for divide.
I tested with Visual Studio .Net, and in my test, the compiler did only one div instruction for both the divide and the modulo at once. I believe GCC does the same, which covers most code produced... :-)
--
Mats
There is the downside that there are versions of this function available only for certain types - div(), ldiv(), lldiv(), imaxdiv() for int, long, long long, and intmax_t, resp. (only the first two being standard C++). This means that if one wants to compute i/j and i%j where i and j are std::size_t, say, it might be better to just use i/j and i%j in close proximity and hope that it gets optimized. Is there a reason why there isn't a templated version in C++, similar to the way that functions from <cmath> such as sqrt() are templated in C++ for different floating-point types, even though in C they're only available for double?