Common formulas
Adding ensures the expression inside the parentheses is non-negative before taking the final modulo.
1. What is Modulo?
- Definition: Modulo (
A % n) finds the remainder left over after dividing an integer by the modulus . - The Rule: The remainder must always satisfy
- Concept: Think of modulo as a clock with positions. Numbers βwrap aroundβ the circle. Adding or subtracting any multiple of brings you back to the same position.
2. Why Add to Negative Numbers?
When a number is negative (e.g., ), ordinary division may produce a negative remainder, which is not the standard mathematical convention.
We instead use the Division Algorithm:
where
Example:
Find a multiple of that is less than or equal to :
Now write
Therefore,
so
The Practical Shortcut
Since adding or subtracting does not change a numberβs residue modulo , repeatedly add until the result lies in the valid range .
Example:
Hence,
3. Python Behavior
Python uses floor division for the modulo operator. As a result, when the divisor is positive, the remainder is always in the range
# Python automatically returns the canonical (non-negative) remainder
print(-5 % 3) # 1
print(-12 % 7) # 2
So,
and