Kodewick
Start learning →
Basic←→0 / 50

GCD and LCM

#017Basica % b6 min

Use Euclid's method to write gcd(a, b), which returns the greatest common divisor (a, b are not negative and not both 0): divide a by b to get remainder r, then go on with b and r until the remainder is 0. For 12 and 18: 12, 18 → 18, 12 → 12, 6 → 6, 0, so the answer is 6. Then the LCM is a / gcd(a, b) * b.

Examples
gcd(12, 18)→6
gcd(100, 75)→25
gcd(7, 5)→1
The functionint gcd(int a, int b)
main.c
int gcd(int a, int b) {
    while (b != 0) {
        int r = a % b;
        // your code here: move b forward to be the new a
        b = r;
    }
    return a;
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.