LCM of two numbers - CodingTute https://codingtute.com/tag/lcm-of-two-numbers/ Learn to code in an easier way Sat, 30 Oct 2021 19:27:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 https://codingtute.com/wp-content/uploads/2021/06/cropped-codingtute_favicon-32x32.png LCM of two numbers - CodingTute https://codingtute.com/tag/lcm-of-two-numbers/ 32 32 187525380 C Program to find LCM of two numbers https://codingtute.com/c-program-to-find-lcm-of-two-numbers/ Sat, 30 Oct 2021 18:59:09 +0000 https://codingtute.com/?p=2844 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 ... Read more

The post C Program to find LCM of two numbers appeared first on CodingTute.

]]>
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.

The post C Program to find LCM of two numbers appeared first on CodingTute.

]]>
2844