Find LCM of two or three numbers | C-Program
LCM of two or three numbers:
Tips:-
- Find the highest number among the two or three numbers through as you like.
- Remember that LCM will not be less than the highest number.
- Now, store it in a variable say x, divide the x with all the others.
- If the remainder is zero, than x is the LCM.
- Else increase the value of x by one and check it again.
- Do it until every number divides x and gives remainder zero.
- You can use a infinite while loop for it and break when it get satisfied.
- At last you will get x as the LCM.
NOTE: Ignore the name of variables used in the program below, just understand how it works and customize it in a way you feel comfortable.
Code:-
#include<stdio.h>
int lcm2(int x, int y)
{ int minval;
minval=(x>y)?x:y;
while(1)
{
if(minval%x==0&&minval%y==0)
{
printf("LCM of %d and %d is %d",x,y,minval);
break;
}
minval++;
}
}
int lcm3(int x, int y, int z)
{ int minval;
minval=(x>y)?((x>z)?x:z):((y>z)?y:z);
while(1)
{
if(minval%x==0&&minval%y==0&&minval%z==0)
{
printf("LCM of %d , %d and %d is %d",x,y,z,minval);
break;
}
minval++;
}
}
void main()
{ int lcm2(int x, int y);
int lcm3(int x, int y, int z);
int x,y,z,var;
nab : printf(" L C M \n\n1. LCM of two numbers.\n2. LCM of three numbers.\n99. Exit\n Enter 1 or 2 or 99\n");
scanf("%d",&var);
while(1)
{
if(var==1)
{ printf("\nEnter two numbers :\n");
scanf("%d %d",&x,&y);
lcm2(x,y);
break;
}
if(var==2)
{ printf("\nEnter three numbers :\n");
scanf("%d %d %d",&x,&y,&z);
lcm3(x,y,z);
break;
}
if(var==99)
{ break; }
else
goto nab;
}
}
Output:
LCM of three numbers :
If you have any doubt to understand the program, feel free to comment down blow.
Thank You.
Comments
Post a Comment
Give your feedback!
DO NOT SPAM !!
NO THIRD PARTY PROMOTIONAL LINK !!!! (else comment will be deleted.)