Common formulas

(Aβˆ’B)β€Šmodβ€Šn=((Aβ€Šmodβ€Šn)βˆ’(Bβ€Šmodβ€Šn)+n)β€Šmodβ€Šn.(A - B) \bmod n = \big((A \bmod n) - (B \bmod n) + n\big) \bmod n.

Adding nn ensures the expression inside the parentheses is non-negative before taking the final modulo.

(A+B)β€Šmodβ€Šn=((Aβ€Šmodβ€Šn)+(Bβ€Šmodβ€Šn))β€Šmodβ€Šn.(A + B) \bmod n = \big((A \bmod n) + (B \bmod n)) \bmod n. (AΓ—B)β€Šmodβ€Šn=((Aβ€Šmodβ€Šn)Γ—(Bβ€Šmodβ€Šn))β€Šmodβ€Šn.(A \times B) \bmod n = \big((A \bmod n) \times (B \bmod n)) \bmod n.

1. What is Modulo?

  • Definition: Modulo (A % n) finds the remainder RR left over after dividing an integer AA by the modulus nn.
  • The Rule: The remainder RR must always satisfy
0≀R<n.0 \le R < n.
  • Concept: Think of modulo as a clock with nn positions. Numbers β€œwrap around” the circle. Adding or subtracting any multiple of nn brings you back to the same position.

2. Why Add nn to Negative Numbers?

When a number is negative (e.g., βˆ’5(mod3)-5 \pmod{3}), ordinary division may produce a negative remainder, which is not the standard mathematical convention.

We instead use the Division Algorithm:

A=qn+R,A = qn + R,

where

0≀R<n.0 \le R < n.

Example: βˆ’5(mod3)-5 \pmod{3}

Find a multiple of 33 that is less than or equal to βˆ’5-5:

βˆ’6=3Γ—(βˆ’2).-6 = 3 \times (-2).

Now write

βˆ’5=βˆ’6+R.-5 = -6 + R.

Therefore,

R=1,R = 1,

so

βˆ’5≑1(mod3).-5 \equiv 1 \pmod{3}.

The Practical Shortcut

Since adding or subtracting nn does not change a number’s residue modulo nn, repeatedly add nn until the result lies in the valid range [0,nβˆ’1][0, n-1].

Example:

βˆ’5+3=βˆ’2-5 + 3 = -2 βˆ’2+3=1-2 + 3 = 1

Hence,

βˆ’5≑1(mod3).-5 \equiv 1 \pmod{3}.

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

0≀R<n.0 \le R < n.
# Python automatically returns the canonical (non-negative) remainder
print(-5 % 3)    # 1
print(-12 % 7)   # 2

So,

βˆ’5%3=1-5 \% 3 = 1

and

βˆ’12%7=2.-12 \% 7 = 2.

Local Graph View

Start typing to search
Try: two sum or #Arrays or #Amazon