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.
Furthermore, in C99 the behaviour is defined to be the annoying one: -2 % 11 = -2.
In general (i.e.,
n % mwhenmis not constant and the range ofnis unconstrained), you probably can’t do better than the usualIt may be interesting to compare that to the following on your platform; one branch might win against the extra modulo: