javamathmodulonegative-number

How does java do modulus calculations with negative numbers?


Am I doing modulus wrong? Because in Java -13 % 64 evaluates to -13 but I want to get 51.


Solution

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