Euclidean Gcd Algorithm
Basic Math
📋 Problem Statement
Given two integers a and b, find their Greatest Common Divisor (GCD) using the Euclidean Algorithm. Also compute the Least Common Multiple (LCM) using .
💡 Intuition
The Euclidean Algorithm is based on the identity . Repeatedly replacing the larger number with the remainder shrinks the problem rapidly ( steps) compared to the naive approach of checking every divisor from 1 to ( steps).
🔧 Approach
- While
b != 0, computea, b = b, a % b. - When
b == 0,aholds the GCD. - Compute LCM as
a * b // gcd(a, b)using the formula . - Use
//(integer division) to avoid floating-point issues.
⚡ Complexity Analysis
Time
— the number of steps is bounded by the number of digits in the smaller input
Space
— only two variables updated in-place
⚠️ Common Mistakes
- Dividing after multiplying can cause integer overflow in languages with fixed-size integers; in Python this isn't an issue
- Forgetting that
gcd(0, n) = n— the Euclidean stopping condition handles this correctly - Using
a / b(float division) instead ofa // bin the LCM formula
🎯 Final Thoughts
The Euclidean Algorithm is one of the oldest algorithms in existence (~300 BCE). Its performance comes from the Fibonacci numbers being the worst case — consecutive Fibonacci numbers require the maximum number of steps for any pair of that size.