Possible Duplicate:
How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers
From what I understand (see Modulo operator with negative values and Modulo operation) C & C++ have a "remainder" operator a % b
but no operator that actually does modular arithmetic when the LHS is negative.
Several languages do have such a function. Is it possible to build an efficient function in C/C++ (or is there no efficient way to do it on i686/x64 CPUs)?
Currently I use (n * b + a) % b
where n
is picked such that I'm fairly sure the entire LHS is non-negative, but inevitably code gets changed and bugs sometimes occur.
Note: in case it's not clear, by modular arithmetic I mean an operator such that a + b % b = a % b
for all integers a
and all positive integers b
.
There is no simple way to do it, however it is more efficient if you create a two-line solution, and spare a multiplication plus determining n
.
inline int modulo(int a, int b) {
const int result = a % b;
return result >= 0 ? result : result + b;
}
Also, if you need to work correctly for negative b
numbers as well, add to the beginning:
if(b < 0) return modulo(-a, -b);
I would suggest a function like the one above, but using inline int modulo(int a, int b) {}
(just as if the operator existed in C++). Personnally I don't use negative numbers often, and still think you should keep %
whenever your code doesn't use negative numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With