Python week 1
21 September 2024 22:36
Week lecture 1
GCD Algorithm Overview
• Initial Approach:
○ Create lists of factors for both numbers mmm and nnn (fm, fn).
○ Compare the two lists to find common factors (cf) and return the largest.
Optimization Steps
1. Single Scan:
○ Instead of creating two separate lists, scan from 111 to
max(m,n)\text{max}(m, n)max(m,n) and check divisibility for both numbers.
2. Minimization:
○ Scan only up to min(m,n)\text{min}(m, n)min(m,n) to find common factors.
3. Avoid Lists:
○ Track only the most recent common factor (mrcf) instead of maintaining a
list of all common factors.
4. Backward Scan:
○ Start scanning from min(m,n)\text{min}(m, n)min(m,n) down to 111. The
first common factor found is the GCD.
Final Algorithm
• Use a while loop:
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
Key Points on GCD Algorithm and Euclid’s Algorithm
1. Finding the GCD:
○ Start from min(m, n) and check backwards to find the first common factor,
which is the GCD.
2. Euclid’s Algorithm:
○ If d divides both m and n, and m > n, then:
▪ m−n=(a−b)dm - n = (a - b)dm−n=(a−b)d implies ddd divides m−nm -
nm−n.
▪ Therefore, gcd(m,n)=gcd(n,m−n)\text{gcd}(m, n) = \text{gcd}(n, m - n)
gcd(m,n)=gcd(n,m−n).
3. Recursive Implementation:
python
Copy code
def gcd(m, n):
if m < n:
Quick Notes Page 1
if m < n:
(m, n) = (n, m)
if (m % n) == 0:
return n
else:
return gcd(n, m - n)
4. Iterative 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
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.
Quick Notes Page 2