Skip to content
Devtoolry

Numbers · beginner

C Program to Find the GCD (HCF) of Two Numbers

Find the GCD (HCF) of two numbers in C with Euclid's algorithm, as a loop and recursively, and compute the LCM from it without overflowing.

The greatest common divisor (GCD), also called the highest common factor (HCF), is the largest number that divides both numbers exactly: gcd(48, 18) = 6.

Euclid's algorithm replaces the pair (a, b) by (b, a % b) until b is 0; then a is the answer. It needs only a few steps even for large numbers, much faster than trying every divisor.

The program

C
#include <stdio.h>
#include <stdlib.h>

int gcd(int a, int b) {
    a = abs(a);
    b = abs(b);
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

int main(void) {
    printf("gcd(48, 18) = %d\n", gcd(48, 18));
    printf("gcd(17, 5) = %d\n", gcd(17, 5));
    printf("gcd(0, 9) = %d\n", gcd(0, 9));

    int a = 12, b = 18;
    printf("lcm(%d, %d) = %d\n", a, b, a / gcd(a, b) * b);
    return 0;
}
Output
gcd(48, 18) = 6
gcd(17, 5) = 1
gcd(0, 9) = 9
lcm(12, 18) = 36

How it works

  1. abs() makes both values positive.
  2. Each pass computes the remainder r = a % b and shifts the pair: (48, 18) → (18, 12) → (12, 6) → (6, 0).
  3. When b is 0, a holds the GCD.
  4. The LCM is a × b / gcd; dividing first (a / gcd * b) keeps the intermediate value small and avoids overflow.

Another way: Recursive version

The recursive form is a direct translation of the rule gcd(a, b) = gcd(b, a % b).

C
#include <stdio.h>

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

int main(void) {
    printf("%d %d\n", gcd(48, 18), gcd(84, 126));
    return 0;
}
Output
6 42

Common mistakes

  • Writing a = b; b = a % b; without a temporary: the second line uses the new a.
  • Computing a * b / gcd(a, b) for large numbers, where a * b overflows int.
  • Calling a % b when b is 0, which is undefined behaviour (usually a crash).

Try it yourself

  • Simplify the fraction 84/126 and print it as 2/3.
  • Find the GCD of five numbers stored in an array.

Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 C examples, or write your own program in the online C Compiler.