Python week 1
Python week 1
Week lecture 1
python
Copy code
def gcd(m, n):
i = min(m, n)
while i > 0:
if (m % i) == 0 and (n % i) == 0:
return i
i -= 1
Key Concepts
• Efficiency: The final approaches are more efficient than the initial naive
method, reducing the number of operations needed to find the GCD.
• Termination: Ensure the loop eventually terminates, which is guaranteed as iii
decreases to zero.
These points capture the evolution of the GCD algorithm and its optimization
techniques!
Week lecture 2
python
Copy code
def gcd(m, n):
if m < n:
python
Copy code
def gcd(m, n):
if m < n:
(m, n) = (n, m)
while (m % n) != 0:
(m, n) = (n, m % n)
return n
5. Efficiency Improvement:
○ Instead of subtracting, use the remainder:
▪ m=qn+rm = qn + rm=qn+r implies gcd(m,n)=gcd(n,r)\text{gcd}(m, n) =
\text{gcd}(n, r)gcd(m,n)=gcd(n,r).
○ This reduces the number of operations significantly.
6. Final Recursive Implementation:
python
Copy code
def gcd(m, n):
if m < n:
(m, n) = (n, m)
while (m % n) != 0:
(m, n) = (n, m % n)
return n
7. Efficiency:
○ The second version of Euclid's algorithm is more efficient than the naive
method.
○ Time complexity is proportional to the number of digits in m, making it
feasible for large values.
Summary
Euclid's algorithm effectively finds the GCD using division and remainders rather
than direct factor comparison, making it much more efficient, especially for large
integers.