CSE 20: Discrete Mathematics for Computer Science Prof. Shachar Lovett
Today’s Topics: 1. GCD 2. Euclid’s algorithm 3. Extended Euclid’s algorithm 2
1. GCD The poor man version of prime factorization 3
GCD Greatest common divisor Given two positive integers a,b, their GCD is the largest integer n such that n|a and n|b 4
GCD What is GCD(20,30)? A. 5 B. 10 C. 20 D. 30 E. Other 5
GCD What is GCD( , )? 6
GCD How can we compute GCD(a,b)? Simple way: (i) Compute prime factorization of a,b (ii) Take common primes and prime powers Example: if a= and b= then GCD(a,b)= However, we believe that computing the prime factorization of large numbers is hard… Euclid’s algorithm provides a much faster way 7
2. Euclid’s algorithm Fast GCD 8
Euclid’s algorithm
(a,b) (b,a mod b)
Euclid’s algorithm
a b Example run: a=20, b=30
Euclid’s algorithm The same basic questions 1. Does it always terminate? 2. Does it return the correct answer? 3. How fast is it?
Euclid’s algorithm: termination
The value of a keeps decreasing, which proves termination
Euclid’s algorithm: correctness g=gcd(a,b)
Euclid’s algorithm: correctness
g=gcd(a,b) Proved!
Euclid’s algorithm: speed How many iterations?
Euclid’s algorithm: speed
3. Extended Euclid’s algorithm Using algorithms to do math! 28
Extended Euclid’s algorithm