Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mod of negative number is melting my brain

Tags:

c#

math

modulo

People also ask

What happens if you modulo a negative number?

If both the divisor and dividend are negative, then both truncated division and floored division return the negative remainder.

Are mods always positive?

Is modulus always positive? The answer is “Yes”. Reason: The value of modulus of any number is always positive.

How does mod work with negative numbers Java?

The sign of the first operand decides the sign of the result. x % y always equals x % -y . You can think of the sign of the second operand as being ignored.


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

Comparing two predominant answers

(x%m + m)%m;

and

int r = x%m;
return r<0 ? r+m : r;

Nobody actually mentioned the fact that the first one may throw an OverflowException while the second one won't. Even worse, with default unchecked context, the first answer may return the wrong answer (see mod(int.MaxValue - 1, int.MaxValue) for example). So the second answer not only seems to be faster, but also more correct.