Skip to content
doubtly

1 answer

LCM of two numbers = (product of the numbers) ÷ HCF, where the HCF is found with Euclid's algorithm.

#include <stdio.h>

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

int main() {
    int a, b;
    printf("Enter two positive integers: ");
    scanf("%d %d", &a, &b);

    long lcm = (long)a / gcd(a, b) * b;
    printf("LCM of %d and %d = %ld\n", a, b, lcm);
    return 0;
}

How it works: gcd() repeatedly replaces (a, b) by (b, a % b) until b becomes 0; then a is the HCF. Since \(\text{HCF}\times\text{LCM} = a\times b\), we get the LCM. Dividing before multiplying (a / gcd * b) avoids overflow for large numbers.

Sample run: input 12 18 gives HCF 6, so LCM \(= 12\times18/6 = 36\).

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.