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
.