Modular Arithmetic

Modular Arithmetic
ICS 6D
Sandy Irani
Modular Arithmetic
• Integer division: divide 25 by 7
– What’s the quotient?
– What’s the remainder?
DIV and MOD functions
• d an integer d ≥ 1
• n an integer
– There are unique integers
• q for “quotient”
• r for “remainder”
– Such that
• r ∈ {0, 1, 2,…,d-1}
• n = d·q + r
– r = n MOD d
– q = n DIV d
DIV and MOD functions
negative n
• d an integer d ≥ 1
• n an integer
– There are unique integers
• q for “quotient”
• r for “remainder”
– Such that
• r ∈ {0, 1, 2,…,d-1}
• n = d·q + r
– r = n MOD d
– q = n DIV d
n = -25
d=7
DIV and MOD functions
for n < 0
• q = floor(n/d)
• r = n - q·d
Example:
n = -25, d = 6
DIV and MOD functions
for n < 0
• q = floor(n/d)
• r = n - q·d
Example
n = -75, d = 12
DIV and MOD functions
for n < 0
• r=n
• q=0
• while (r < 0)
– r=r+d
– q = q -1
Example
n = -25, d = 6
DIV and MOD functions
for n < 0
• r=n
• q=0
• while (r < 0)
r=r+d
q = q -1
Example
n = -75, d = 12
*
What is -52 DIV 5?
What is -52 MOD 5?
A) -52 DIV 5 = -10
-52 MOD 5 = 3
C) -52 DIV 5 = -10
-52 MOD 5 = -2
B) -52 DIV 5 = -11
-52 MOD 5 = 3
D) -52 DIV 5 = -11
-52 MOD 5 = -2
What is -66 MOD 10?
What is -66 MOD 11?
A) -66 MOD 10 = -6
-66 MOD 11 = 11
C) -66 MOD 10 = -6
-66 MOD 11 = 0
B) -66 MOD 10 = 4
-66 MOD 11 = 11
D) -66 MOD 10 = 4
-66 MOD 11 = 0
Modular Arithmetic
• “Mod n” is a function
from ℤ to {0, 1, …, n-1}
• Addition mod n:
(x + y) mod n
Multiplication mod n:
xy mod n
Modular Arithmetic
• In computing arithmetic expressions mod n, can
compute partial results mod n and the result is the
same:
– ((x mod n) + (y mod n)) mod n = (x + y) mod n
– (158 + 219) mod 5 =
– ((x mod n) · (y mod n)) mod n = (x · y) mod n
– (158 · 219) mod 5 =
*
What is ((13)122 + 56 ) MOD 12 ?
A) 1
C) 9
B) 8
D) 57
E) 56
Modular Arithmetic
• (3474 + 120) mod 11
(56·72 + 62) mod 7
Modular Arithmetic
• Any multiple of n acts like 0 mod n:
– (1235 ·170 + 2) mod 17
– (8 + 170 ·98) mod 17 =
Rings
– A ring is a closed mathematical system with
addition and multiplication operations that
– Obeys certain laws (associative, distributive, etc.)
– Has identities:
• 0+x=x
• 1·x = x
• The elements of a ring can be different kinds of
objects:
– Polynomials, sequences, numbers, etc.
The ring ℤn
• The ring ℤn is the set {0, 1, 2, …, n-1} along with
– Addition mod n
– Multiplication mod n
• Example: ℤ5
x
0
1
2
3
4
0
1
2
+
3
4
0
1
2
3
4
0
1
2
3
4
*
Equivalence mod n
x mod n = y mod n ↔
(x-y) = integer multiple of n ↔
x ≡ y mod n ↔ “x is equivalent to y mod n”
Example: n = 5
-9 -8 -7 -6 -5 -4 -3 -2 -1
0
1
2
3
4
5
6
7
8
9
Which numbers are equivalent to 3 mod 11?
-7
11
58
113
-2
3 -11
-30
C) 58, 113, 3
A) 3
D) 3, 58, 113, -30
B) 113, 3
E) -7, 58, 113, 3,
-30