Source Code to Compute LCM
/* C program to find LCM of two positive integers entered by user */
#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;
}
In this program, user is asked to enter two positive integers which will be stored in variable num1 andnum2 respectively and largest of two integers is assigned to variable max. 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
Visit this page to learn different methods for finding GCD of two numbers.
#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
No comments:
Post a Comment