Recursion · Euclid · Remainder

GCD Visualizer

What is GCD

Return the greatest common divisor of a and b. gcd(a, 0) = a, so gcd(0, 0) = 0.

Example. gcd(48, 18) returns 6. The remainders are 12, then 6, then 0.

Input:  48 18
Output: 6

Constraints. 0 ≤ a, b ≤ 109. This picture caps each value at 100000.

Approach

Base case When b == 0, every previous remainder has been consumed. Return a.
Recursive case gcd(a, b) = gcd(b, a % b). The new second argument is strictly smaller, so the chain ends.

Recursion tree

Interactive recursion tree
Step 0/0 Answer —

The whole tree is drawn when the page opens. Next and Play start again from the first call.

def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)

Complexity

PieceCostWhy
TimeO(log min(a, b))The remainder shrinks at every step.
StackO(log min(a, b))One pending call per remainder.

Implementation

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)