C Program to find LCM of two numbers

CodingTute

LCM of Two Numbers

In this example, you will learn to find the LCM of two numbers using a c program. LCM is also known as Least Common Multiple. In simpler terms, LCM is defined least or lowest number which is the common multiple of the given numbers.

Ex. LCM of 10 and 15 is 30.

LCM of the given number will be always greater than or equal to the greatest of the given numbers. Here is the given example 15 is larger of given numbers 10 and 15, then the LCM should be greater than 15.

C Program to find LCM of two numbers

// C program to find LCM of two numbers.

#include <stdio.h>
int main() {
    int num1, num2, max;
    printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);

    // maximum number between num1 and num2 is stored in max
    max = (num1 > num2) ? num1 : num2;

    while (1) {
        if (max % num1 == 0 && max % num2 == 0) {
            printf("LCM of %d and %d is %d.", num1, num2, max);
            break;
        }
        max++;
    }
    return 0;
}

Output

Enter two numbers: 10 15
LCM of 10 and 15 is 30.

LCM using GCD

One of the optimal ways to find LCM is using GCD. Mathematically, the product of LCM and GCD should be equal to the product of given numbers.

LCM(num1,num2) x GCD(num1,num2) = num1 x num2

Then, LCM(num1,num2) = num1 x num2 / GCD(num1,num2)

C Program to find LCM of two numbers using GCD

// C program to find LCM of two numbers using GCD
#include <stdio.h>

// Recursive function to return GCD of num1 and num2
int gcd(int num1, int num2)
{
	if (num1 == 0)
		return num2;
	return gcd(num2 % num1, num1);
}

int main()
{
	int num1, num2, lcm;
	printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);
    
    lcm =  num1 * num2 / gcd(num1, num2);
    printf("LCM of %d and %d is %d.",num1, num2, lcm);
    
}

Output

Enter two numbers: 10 15
LCM of 10 and 15 is 30.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.