Thursday, April 21, 2011

HCF/GCD in C using recursion

HCF: Highest common factor can be calculated using recursive 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. 
Recursive method ending: if y divides x then y is the HCF and we return it.
Recursive call: if y doesnt divides x then we again call HCF function on  y and x%y.
(Which is similar to long division method)

Code:
#include<stdio.h>
int HCF(int x, int y){
    if(x%y==0)
    {
        return(y);
    }
    else
    {
        HCF(y,x%y);
    }
}
int main()
{
    int k;
    k=HCF(24,18);    
    printf("\n HCF=%d",k);
}

No comments:

Post a Comment