Dynamic Programming21 sections · 916 units
Open in Course

GCD - Recursive Formula

The Euclidean algorithm

The complete recursive formula is: gcd(a,b)={aif b=0gcd(b,amodb)otherwise\gcd(a, b) = \begin{cases} a & \text{if } b = 0 \\ \gcd(b, a \bmod b) & \text{otherwise} \end{cases} This is the Euclidean algorithm, invented around 300300 BCE. It is one of the oldest algorithms still used today.

Notice how each call swaps the arguments: aa becomes bb, and bb becomes amodba \bmod b. This is your first recursion with two changing parameters. Each recursive call brings you closer to the base case.