Time Complexity of Euclidean GCD Algorithm
π Core Result
The Euclidean GCD algorithm runs in:
The intuition is simple:
Every two iterations, the larger number becomes at least half of what it was before.
Repeatedly halving a number leads to logarithmic time.
π‘ Key Observation
The Euclidean Algorithm repeatedly transforms
where
Since
the remainder satisfies
Why does the size shrink?
There are two cases.
Case 1
If
then
because
Example
25 % 10 = 5
Case 2
If
then
a % b = a - b
because the quotient is exactly 1.
Since
we get
- The divisor
bis so big that it can only fit intoaexactly one time. - The remainder is just what is left over:
a - b. Example
25 % 18 = 7
Therefore,
after at most two iterations, one of the numbers has been reduced to less than half of its previous size.
This halving repeats throughout the algorithm.
Interview Explanation
Step 1
At every iteration we replace
gcd(a,b)
with
gcd(b,a%b)
without changing the answer.
Step 2
Within every two iterations, the larger value is reduced by at least half.
Step 3
If a quantity keeps getting halved,
n
β
n/2
β
n/4
β
n/8
β
...
β
1
the number of halvings is
Hence,
Dry Run
Example:
gcd(48,18)
β
gcd(18,12)
β
gcd(12,6)
β
gcd(6,0)
Notice how the numbers shrink very quickly.
Worst Case
The Euclidean Algorithm is slowest when the inputs are consecutive Fibonacci numbers.
Example
gcd(21,13)
β
gcd(13,8)
β
gcd(8,5)
β
gcd(5,3)
β
gcd(3,2)
β
gcd(2,1)
β
gcd(1,0)
This is known as LamΓ©βs Theorem.
Even in this worst case,
Code
def gcd(a, b):
while b:
a, b = b, a % b
return a
Complexity
| Operation | Complexity |
|---|---|
| Time | |
| Space (Iterative) | |
| Space (Recursive) | (call stack) |
Interview Takeaways
- Euclid replaces
(a,b)with(b,a%b). - The GCD never changes during this replacement.
- The numbers shrink rapidly.
- Every two iterations, the larger number becomes at least half as large.
- Repeated halving gives logarithmic complexity.
- Worst case occurs for consecutive Fibonacci numbers, but complexity is still .