basics · beginner · ~15 min

Greatest common divisor

Apply Euclid's algorithm; iterative remainder.

Challenge

Implement int gcd(int a, int b) using Euclid's algorithm. Inputs are non-negative.

Why this matters

Euclid's algorithm is the oldest known nontrivial algorithm. It's the basis of modular arithmetic, RSA key generation, and many number-theoretic constructs.

Starter code

int gcd(int a, int b) { /* TODO */ return 0; }

Common mistakes

Stopping when a == b (works but is inelegant — Euclid's is while (b) { ... }). Recursing without a base case for negative inputs. Using % on negative numbers (implementation-defined sign in older C).

Edge cases to handle

gcd(0, 0) = 0 (some define as undefined). gcd(n, 0) = n. gcd(0, n) = n.

Complexity

O(log min(a, b)) — Fibonacci-like number of iterations in the worst case.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.