Dynamic Programming21 sections · 916 units
Open in Course

GCD - Implementation

Three lines of code

Here is the recursive GCD function:

function gcd(a, b)
    if b = 0 then
        return a
    return gcd(b, a mod b)

The entire algorithm is just one line of logic. If bb is 00, return aa. Otherwise, call gcd(b, a mod b). Trace gcd(48, 18): you get gcd(18, 12), then gcd(12, 6), then gcd(6, 0), which returns 66. Four calls total. Compare that to checking every number from 11 to 1818. The recursive version is both simpler and faster.

Time complexity: O(log(min(a,b)))O(\log(\min(a, b))) because the remainder shrinks rapidly.

Space complexity: O(log(min(a,b)))O(\log(\min(a, b))) for the call stack.