GCD & LCM
Greatest Common Divisor & Least Common Multiple
Two of the most fundamental operations in number theory are the GCD (greatest common divisor) and the LCM (least common multiple).
Euclidean Algorithm
The GCD of two integers and is the largest integer that divides both. The Euclidean algorithm computes it efficiently using the key identity:
This recurses until , at which point .
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(48, 18)) # 6
The algorithm runs in steps — extremely fast even for very large numbers.
Least Common Multiple
The LCM is the smallest positive integer divisible by both and . It is related to GCD by:
Use integer division (//) to avoid floating-point issues:
def lcm(a, b):
return a * b // gcd(a, b)
print(lcm(4, 6)) # 12
Why This Works
For any two integers, . This is because the prime factorizations of and interlock: GCD takes the minimum exponent of each prime, while LCM takes the maximum.
Your Task
Implement gcd(a, b) using the Euclidean algorithm (do not use math.gcd), and lcm(a, b) using the formula above.