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 jus
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;