English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Other

C Language Reference Manual

C program to find the LCM of two numbers

Comprehensive Collection of C Programming Examples

In this example, you will learn how to calculate the LCM (least common multiple) of two numbers entered by the user.

To understand this example, you should understand the followingC programmingTopic:

Two integers n1and n2The LCM is the smallest positive integer that can be divided by n1and n2Divisible completely (no remainder). For example,72and12The LCM of 0 is360.

Use while and if to calculate LCM (least common multiple)

#include <stdio.h>
int main() {
    int n1, n2, min;
    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);
    //n1and n2The maximum value between them is stored in min
    min = (n1 > n2) ? n1 : n2;
    while (1) {
        if (min % n1 == 0 && min % n2 == 0) {
            printf("%d and %d of LCM is %d.", n1, n2, min);
            break;
        }
        ++min;
    }
    return 0;
}

Output Result

Enter two positive integers: 72
120
72and12The LCM of 0 is360.

In this program, the integers entered by the user are stored in the variables n1and n2.

n1and n2The maximum value stored in min, and the LCM of the two numbers cannot be less than min.

in each iteration.

Check if min can be divided by n1and n2Divisible completely.

if (min % n1 == 0 && min % n2 == 0) { ... }

If this test condition is not true, then min will increment1, and continue iterating until the test expression of the If statement is true.

You can also use the following formula to find the LCM of two numbers:

LCM = (num1*num2)/GCD

Learn how to find GCD in C programmingGCD of two numbers.

Use GCD to calculate LCM

#include <stdio.h>
int main() {
    int n1, n2, i, gcd, lcm;
    printf("Enter two positive integers: ");
    scanf("%d %d", &n1, &n2);
    for (i = 1; i <= n1 && i <= n2; ++i) {
        
        // Check if i is a factor of two integers
        if (n1 % i == 0 && n2 % i == 0)
            gcd = i;
    }
    lcm = (n1 * n2) / gcd;
    printf("The LCM of two numbers %d and %d is %d.", n1, n2, lcm);
    return 0;
}

Output Result

Enter two positive integers: 78
150
two numbers78and15The LCM of 0 is1950.

Comprehensive Collection of C Programming Examples