Java: Remainder (modulo) operator with negative numbers
-11 % 5 == -1 11 % -5 == 1 -11 % -5 == -1
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.
Here's a diagram of
x % 5 (which is the same as
x % -5).
% computes the remainder in a division and should not be confused with the concept of modulo arithmetic.
According to the spec (§15.17.3), the following should always hold:
(a / b) * b + (a % b) == a
a % b should always represent the remainder of an integer division, and the remainder always has the same sign as the dividend.