Dynamic Programming21 sections · 916 units
Open in Course

GCD - Base Case

When to stop

When does the recursion stop? When b=0b = 0. At that point, gcd(a,0)=a\gcd(a, 0) = a. Any number divides 00 (since 0=0×n0 = 0 \times n for any nn), so the GCD of aa and 00 is just aa itself.

This is your base case. Every recursive call reduces bb (since amodb<ba \bmod b < b), so you will always reach b=0b = 0 eventually. This is where recursion stops. Without it, you get infinite recursion and a stack overflow. Every recursive solution needs at least one base case.