Am I doing modulus wrong? Because in Java -13 % 64
evaluates to -13
but I want to get 51
.
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.
The modulus of a negative number is found by ignoring the minus sign. The modulus of a number is denoted by writing vertical lines around the number. Note also that the modulus of a negative number can be found by multiplying it by −1 since, for example, −(−8) = 8.
Can a modulus be negative? % can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With