Defination
Modulus Operator is the remainder of the euclidean division of one number by another. %
is called the modulo operation. The remainder operation for operands that are integers after binary numeric promotion produces a result value such that (a/b)*b+(a%b) is equal to a.
Division Operator i.e. / operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor. Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.
There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend.
Calculation
The modulo operation can be calculated using this equation:
a % b = a - floor(a / b) * b
- floor(a / b) represents the number of times you can divide a by b
- floor(a / b) * b is the amount that was successfully shared entirely
- The total (a) minus what was shared equals the remainder of the division
It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.
Modular Arithmetic
There are two conventions, depending on whether you allow the remainder to be negative. For example If −27 is divided by 5, what would be the remainder? Either
- −27=−6×5+3−27=−6×5+3
Reminder is 3
- −27=−5×5+(−2)−27=−5×5+(−2)
Reminder is -2
Note that whatever convention you choose, the two possibilities for the remainder will always differ by 5 (divisor). As per the Euclidean Algorithm, when dividend is divided by the divisor d, where r is the remainder and q is the quotient .
Example
class Modulus { public static void main(String[] args) { int a = 5%3; // 2 int b = 5%(-3); // 2 int c = (-5)%3; // -2 int d = (-5)%(-3); // -2 } }