basics · beginner · ~15 min
Apply Euclid's algorithm; iterative remainder.
Find the greatest common divisor of two non-negative integers using Euclid's algorithm.
Implement int gcd(int a, int b) that returns the largest integer dividing both a and b. Use the iterative remainder method: repeatedly replace (a, b) with (b, a % b) until b is 0, then return a.
Two non-negative ints a and b.
Returns their greatest common divisor as an int. By convention, gcd(x, 0) is x.
gcd(12, 8) -> 4
gcd(13, 7) -> 1
gcd(10, 0) -> 10
gcd(6, 6) -> 6
b is 0, the answer is a.Euclid's algorithm is the oldest known nontrivial algorithm. It's the basis of modular arithmetic, RSA key generation, and many number-theoretic constructs.
Two non-negative ints a and b.
The greatest common divisor of a and b, as an int.
a and b are non-negative integers. Returns greatest common divisor.
int gcd(int a, int b) { /* TODO */ return 0; }
Dividing by zero when b is 0 without checking loop condition.
a == 0, b == 0, a == b, prime numbers.
O(log min(a, b)) — Fibonacci-like number of iterations in the worst case.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.