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
How about
if (a > 0)
return a % n;
if (a < 0)
{
r = n - (-a % n);
if (r == n)
return 0;
return r;
}
If a < 0, then r = -a % n
is a value in [0, n) such that k * n + r = -a for some integer k.
Then n - r is a value in (0, n], and since -r = a + k * n, we have n - r = a + (k + 1) * n, or a = (n - r) + (-k - 1) * n. From this you can see that n - r is the modulus of a, and since it is in (0, n], it is non-negative.
Finally, you want the result to be in the range [0, n), not in (0, n]. To ensure this, we check if r is n, and if so, return 0. (Which is of course modulus-n-equivalent to n)