LCM of two integers a and b is the lowest positive integer this is perfectly divisible by both a and b.
C Program to Find LCM of two Numbers
Program 1
#include <stdio.h>
int main()
{
int num1, num2, max;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
max=(num1>num2) ? num1 : num2; /* maximum value is stored in variable max */
while(1) /* Always true. */
{
if(max%num1==0 && max%num2==0)
{
printf("LCM of %d and %d is %d", num1, num2,max);
break; /* while loop terminates. */
}
++max;
}
return 0;
}
Explanation
In this program, user is asked to enter two positive integers which will be stored in variable num1 and num2 respectively and largest of two integers is assigned to variablemax. Then, while loop is executed and in each iteration it is checked whether max is perfectly divisible by two numbers entered by user or not. If max is not perfecly divisible, max is increased by 1 and this process goes not until max is perfectly divisible by both numbers. The test condition of while loop in above program is always true so, the loop is terminated using break statement.
The LCM of two numbers also can be found using following formula:
LCM=(num1*num2)/GCD /*GCD Means Greatest common divisor HCF */
Program 2
#include<stdio.h>
int main()
{
int n1,n2,temp1,temp2;
printf("Enter two positive integers: ");
scanf("%d %d",&n1,&n2);
temp1=n1;
temp2=n2;
while(temp1!=temp2)
{
if(temp1>temp2)
temp1-=temp2;
else
temp2-=temp1;
}
printf("LCM of two numbers %d and %d is %d", n1, n2, (n1*n2)/temp1);
return 0;
}
The output of these two programs is same.
Output
Enter two positive numbers: 15 9 LCM of two numbers 15 and 9 is 45