basics · intermediate · ~15 min
Write a small reusable function with a loop.
Compute the greatest common divisor of two integers with Euclid's algorithm.
Implement int gcd(int a, int b) that returns the largest integer dividing both a and b. Use the iterative method: repeatedly replace (a, b) with (b, a % b) until b is 0, then return a. By convention gcd(x, 0) == x. No main — the grader calls it.
Two non-negative ints a and b.
Returns their greatest common divisor, as an int.
gcd(12, 8) -> 4
gcd(17, 5) -> 1
gcd(9, 0) -> 9
gcd(0, 6) -> 6
gcd(x, 0) == x and gcd(0, y) == y.Two non-negative ints a and b.
The greatest common divisor of a and b, as an int.
Inputs non-negative; gcd(x, 0) == x.
int gcd(int a, int b) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.