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
.
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;
}
Since "mathematically" both are correct:
-13 % 64 = -13 (on modulus 64)
-13 % 64 = 51 (on modulus 64)
One of the options had to be chosen by Java language developers and they chose:
the sign of the result equals the sign of the dividend.
Says it in Java specs:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3
Are you sure you are working in Java? 'cause Java gives -13 % 64 = -13 as expected. The sign of dividend!