If we had a pile of
33 pennies and wanted to split it into
5 equal sized piles, we would have enough pennies to create
5 piles with
6 pennies each. We would not have enough for all
5 piles to have
7 pennies, so we settle for
6 pennies in each. With
5 piles of
6 pennies each, we have used
30 of the
33 pennies. Three pennies are left over, and that is the remainder.
For non-negative numbers, the modulus operator gives the remainder from dividing the first operand by the second operand. In the case of the
33 pennies divided into
5 equal sized piles, the math would be expressed as follows:
>>> 33 // 5
>>> 33 % 5
The first of the two operations above is integer division. The result was
The second lets us know how many were left over.
3 pennies are left over.
6 % 4, the
4 can be divided into
2 is left over. So:
>>> 6 % 4
When the first operand is evenly divisible by the second, nothing is left over, so the modulus would be
>>> 8 % 4
It might not be so obvious how to handle negative numbers, but here is an example.
>>> -5 % 4
Basically, the above is giving us the difference between
-5 and the next lower number,
-8, that is evenly divisible by