Saturday, December 28, 2013

C Program to find HCF/GCD of two numbers

Definition of HCF (Highest common factor):

HFC is also called greatest common divisor (gcd). HCF of two numbers is a largest positive numbers which can divide both numbers without any remainder.  For example HCF of two numbers 4 and 8 is 2 since 2 is the largest positive number which can dived 4 as well as 8 without a remainder. 

Logic of HCF or GCD of any two numbers:

In HCF we try to find any largest number which can divide both the number.
For example: HCF or GCD of 20 and 30
Both number 20 and 30 are divisible by 1, 2,5,10.

HCF=max (1, 2, 3, 4, 10) =10

#include<stdio.h>
int main(){
    int x,y,m,i;
    printf("Insert any two number: ");
    scanf("%d%d",&x,&y);
    if(x>y)
         m=y;
    else
         m=x;
    for(i=m;i>=1;i--)
    {
         if(x%i==0 && y%i==0)
        {
             printf("\nHCF of two number is : %d",i) ;
             break;
         }
    }
    return 0;
}

No comments:

Post a Comment