Something like this should do:
if(value<0)
mod = n-(-value)%n;
else
mod = value%n;
if(mod>=n)
mod -= n;
The worst code path is 6 basic instructions (compare, negation, modulus, subtraction, compare, subtraction). As Potatoswatter commented, all the extra instructions are significantly cheaper than the modulus itself.
Depending on how your compiler works, it may be interesting to invert the condition for the first if and swap the statements to have more even costs across cases.
Also, as sth pointed out, you will be getting an overflow when value
is equal to the minimum value for int
. If your code has to work with unconstrained inputs, you may add a check to add n
to the value
when you hit this edge case, at the beginning of the code. This adds +2 base instructions to the code (check + either add or jump).
Unless you can rely on how the target machine will deal with negative modules, you can't get more efficiency than this. Note that, while C99 defines how to deal with negative modules, this doesn't guarantee that the machine's module instruction works that way (that's probably a winning bet for most cases, but still a bet): if it works differently, it's the compiler's task to tweak the result to be what the language specification requires it to be (which means additional machine code generated by the compiler to check and adjust the result).
Unlike most other answers provided, my approach does the checks and manipulations for negative values before computing the modulus, so it is always computed on non-negative values. I tried to give you architecture-agnostic code. If you can be sure that the CPU computes negative modules as C99 defines, then feel free to rely on that fact to simplify the code and shave a few cycles off.
Hope this helps.