basics · intermediate · ~15 min

Greatest common divisor

Write a small reusable function with a loop.

Challenge

Implement int gcd(int a, int b) returning the greatest common divisor of two non-negative integers (Euclid's algorithm). gcd(x,0)==x.

Starter code

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.