The symbol (%) is used as the modulus operator in most languages including C, Java, Python and JavaScript; but some other keywords like ‘mod’ and ‘rem’ may also be used in other languages. Basically, the meaning of a modulus operation is to take the remainder when a number is being divided by another number. For example. 7 % 5 = 2, because 7 = 5 x 1 + 2. Obviously, this operation applies only to whole numbers (integers).

Let’s try out a few examples:

- 97 % 6 = ___
- 54 % 11 = ___
- 7 % 8 = ___
- -14 % 3 = ___
- 19 % -4 = ___
- -20 % -6 = ___

…

The first three are easy.

- 97 % 6 = 1 ( 97 = 6 x 16 + 1 )
- 54 % 11 = 10 ( 54 = 11 x 4 + 10 )
- 7 % 8 = 7 ( 7 = 8 x 0 + 7)

The confusion arises when negative integers are involved.

By standard (*ISO*/*IEC 14882:2003)*, the modulus operation must yield a remainder, r such that

where a = dividend, n = divisor, and q = quotient.

In this case, q must be the result of the division operator. Division of two integers often involves rounding, and it happens that there are two different ways to perform rounding after a division. What this means is that the result of division and consequently the result of the modulus operator is implementation-specific, i.e it may varies across different compilers and languages.

…

C, Java and JavaScript uses the “round towards zero” method. This method is also known as the truncate method, because it simply throws away the fraction part and take only the integer part of the number. Examples are: 5.67 => 5, -6.2 => -6.

Now lets solve example 4 – 6 above:

4. -14 / 3 = -4.6667 => -4, then -14 = 3 x (-4) + (-2). Hence, -14 % 3 = -2.

5. 19 / -4 = -4.75 => -4, then 19 = (-4) x (-4) + (3). Hence, 19 % -4 = 3.

6. -20 / -6 => 3.3333 => 3, then -20 = (-6) x (-3) + (-2). Hence, -20 % -6 = -2.

…

On the other side, Python uses the “round down” (or “round towards minus infinity”) method. Compared to the previous method, the output differs only for negative numbers. Examples are: 5.67 => 5, -6.2 => -7.

The solution for example 4 – 6 above is now different:

4. -14 / 3 = -4.6667 => -5, then -14 = 3 x (-5) + (1). Hence, -14 % 3 = 1.

5. 19 / -4 = -4.75 => -5, then 19 = (-4) x (-5) + (-1). Hence, 19 % -4 = -1.

6. -20 / -6 => 3.3333 => 3, then -20 = (-6) x (-3) + (-2). Hence, -20 % -6 = -2.

…

From the discussion, are you able to offer any other conclusions? If you look closely, you should be able to find some way to deduce the sign of the result without even evaluating the modulus operation.

Feel free to share and comment below.