What is an efficient way to get the least non-negative residue modulo n in C?
c, math
Solution
Furthermore, in C99 the behaviour is defined to be the annoying one: -2 % 11 = -2.
In general (i.e., `n % m` when `m` is not constant and the range of `n` is unconstrained), you probably can't do better than the usual
res = ((n % m) + m) % m
It may be interesting to compare that to the following on your platform; one branch might win against the extra modulo:
res = n % m;
if (res < 0) res += m;
Problem
Is there an efficient way to get the least non-negative residue modulo n, where n is positive, in C? This is quite easy if the number is non-negative, then it's just a % n (where a is the non-negative integer). However when a is negative, it appears the behaviour, in C89, is implementation defined (thanks kennyTM). I.e. -2 % 11 = -2 or 9.