CSE390D Notes for Friday, 10/11/24

gcd = Greatest Common Divisor lcm = Least Common Multiple gcd/lcm intuition: a = p1^a1 * p2 ^ a2 ... * pn ^ an b = p1^b1 * p2 ^ b2 ... * pn ^ bn gcd is produce of mins lcm is produce of maxes so ab = gcd(a, b) * lcm(a, b) consider: a = 2^3 * 3^5 * 7^2 b = 2^4 * 3^3 gcd(a, b) = 2^3 * 3^3 lcm(a, b) = 2^4 * 3^5 * 7^2 ------------------------------------------------------------------------------- Euclid's algorithm gcd(91, 287): 287 = 91 * 3 + 14 = gcd(91, 14) 91 = 14 * 6 + 7 = gcd(14, 7) 14 = 7 * 2 + 0 = gcd(7, 0) = 7 in general: if a = bq + r gcd(a, b) = gcd(b, r) proof: suppose d | a and d | b, then it divides r, gcd(a, b) <= gcd(b, r) suppose d | b and d | r, then it divides a, gcd(b, r) <= gcd(a, b) qed ------------------------------------------------------------------------------- We wrote a Python function for computing the prime factors of a number, as in factors(100) -> [2, 2, 5, 5]. We wrote a loop that started a local variable m at 2 (smallest prime). Then each time through the loop we either added another prime factor of m if it goes evenly into n or we added 1 to m to consider a different possible factor. This is inefficient in that we test all possible values of m and not just primes, but there isn't an easy way to "go to next prime." We had the loop terminate when the potential factor m was no longer less than or equal to the square root of n. In that case, we have reduced the original value to its final prime factor, which we added to the list before returning the result. # returns the prime factors of n as a list def factors(n): m = 2 result = [] while m * m <= n: if n % m == 0: result.append(m) n = n / m else: m += 1 result.append(n) return result We wrote a Python function to compute the gcd of two numbers x and y using Euclid's algorithm. # returns the greatest common divisor of x and y def gcd(x, y): if y == 0: return x else: return gcd(y, x % y)
Stuart Reges
Last modified: Fri Oct 11 12:40:38 PDT 2024