Saturday, April 23, 2011

Calculating LCM of two Numbers in C

LCM : least common multiplier, is a number to which given two numbers can divide exactly (and of course there are a lot of numbers like that , but LCM is the least one of them). E.g. given two numbers 12,15 these numbers can divide 60,120,180 but LCM is 60 as its the least.


Method:  how to calculate this in C ? well its easy. We can use the mathematical relation between two numbers and their HCF and LCM. the relation is :-
product of two number =HCF x LCM.

Code in C:
#include<stdio.h>
int HCF(int x, int y)
{
    int tmp;
    if(x<y)
    {
        tmp=x;
        x=y;
        y=tmp;//using tmp to swap x and y    
    }
   while(x%y!=0)
    {
        tmp=x%y; //using tmp to store remainder
        y=x;
        x=tmp;    
    }
    return(y);
}
int LCM(int x, int y)
{
    return(x*y/HCF(x,y));
}
int main()
{
    int k;
    k=LCM(12,15);    
    printf("\n LCM=%d",k);
}

No comments:

Post a Comment