Python Week1 Lecture3 Handout
Python Week1 Lecture3 Handout
PROGRAMMING,
DATA STRUCTURES AND
ALGORITHMS IN PYTHON
Week 1, Lecture 3
Then m = ad, n = bd
So m-n = ad - bd = (a-b)d
So gcd(m,n) = gcd(n,m-n)
Euclids algorithm
If n divides m, return n
if (m%n) == 0:
return(n)
else:
diff = m-n
# diff > n? Possible!
return(gcd(max(n,diff),min(n,diff))
Euclids algorithm, again
def gcd(m,n):
while (m%n) != 0:
diff = m-n
# diff > n? Possible!
(m,n) = (max(n,diff),min(n,diff))
return(n)
Even better
Suppose n does not divide m
Then m = ad, n = bd
So ad = q(bd) + r
If n divides m, return n
Return gcd(n,r)
Euclids algorithm
def gcd(m,n):
if (m%n) == 0:
return(n)
else:
return(gcd(n,m%n)) # m%n < n, always!
Euclids algorithm, revisited
def gcd(m,n):
while (m%n) != 0:
(m,n) = (n,m%n) # m%n < n, always!
return(n)
Efficiency