Monday, December 30, 2013

Finding H.C.F (Highest Common Factor) of two numbers : logic and program

Highest common factor(hcf) also know as greatest common divisor(gcd) is the largest common factor among the factors of two numbers
For example, find the hcf of 8,12
factors of 8= 1,2,4,8
factors of 12=1,2,3,4,6,12
hcf(8,12)=4

The process of finding hcf is more straight-forward and easy.
Dividend  Divisor  Remainder
12                8              4
8                  4              0
hcf(12,8)=4


Dividend  Divisor  Remainder
45               27             18
27               18             9
18                9              0
hcf(45,27)=9

Steps
1. Divide the bigger number by smaller number. and store the remainder
2. If remainder is equal to 0 then divisor is hcf.
3. If remainder is not equal to 0 then divisor becomes dividend and remainder becomes divisor
4. Goto step 2.

#include<stdio.h>
int hcf(int a,int b); /* Function Prototype */
int main()
{
        int x,y, h;
        printf("\nEnter two numbers:");
        scanf("%d%d",&x,&y);

        if (x<y)
             h=hcf(y,x);
        else
             h=hcf(x,y);

        printf("\nH.C.F(%d,%d)=%d",x,y,h);
        return 0;
}
int hcf(int a, int b)
{
         int rem;
         do
          {
                 rem=a%b;
                 a=b;
                 b=rem;
           }while(rem!=0);
          return a;
}

No comments:

Post a Comment