Thursday, April 21, 2011

Calculating HCF/GCD of two Numbers in C non recursive

HCF: Highest common factor can be calculated using long division method. HCF is also called as GCD (greatest commomn divisor).
Method: Two numbers x and y and passed to the function HCF which calculates HCF and returns it.
we keep on diviing x with y untill it completely divides x. If it does y becomes HCF, if not then we replace x with the remainder and y with x.
Code:

#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 main()
{
    int k;
    k=HCF(18,24);    
    printf("\n HCF=%d",k);
}

No comments:

Post a Comment