How does java do modulus calculations with negative numbers?

Jakir00 picture Jakir00 · Dec 9, 2010 · Viewed 122.4k times · Source

Am I doing modulus wrong? Because in Java -13 % 64 is supposed to evaluate to -13 but I get 51.

Answer

Mark Byers picture Mark Byers · Dec 9, 2010

Both definitions of modulus of negative numbers are in use - some languages use one definition and some the other.

If you want to get a negative number for negative inputs then you can use this:

int r = x % n;
if (r > 0 && x < 0)
{
    r -= n;
}

Likewise if you were using a language that returns a negative number on a negative input and you would prefer positive:

int r = x % n;
if (r < 0)
{
    r += n;
}