Mod of negative number is melting my brain
I always use my own mod
function, defined as
int mod(int x, int m) {
return (x%m + m)%m;
}
Of course, if you're bothered about having two calls to the modulus operation, you could write it as
int mod(int x, int m) {
int r = x%m;
return r<0 ? r+m : r;
}
or variants thereof.
The reason it works is that "x%m" is always in the range [-m+1, m-1]. So if at all it is negative, adding m to it will put it in the positive range without changing its value modulo m.
Please note that C# and C++'s % operator is actually NOT a modulo, it's remainder. The formula for modulo that you want, in your case, is:
float nfmod(float a,float b)
{
return a - b * floor(a / b);
}
You have to recode this in C# (or C++) but this is the way you get modulo and not a remainder.
Single-line implementation using %
only once:
int mod(int k, int n) { return ((k %= n) < 0) ? k+n : k; }