Search This Blog

Find GCD of two numbers | C programming

 Find GCD of two numbers

 

 

Problem:

Read two integer values, which are natural numbers. Find the GCD of the numbers.

Input

The input file contains two integer values.

Output

Print the GCD of the two numbers.





Solution

 

 In mathematics, the greatest common divisor (gcd) of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers. For example, the gcd of 8 and 12 is 4.
The greatest common divisor is also known as the greatest common factor (gcf), highest common factor (hcf), greatest common measure (gcm), or highest common divisor.

Now, how can we get the gcd of two numbers. There are many ways to get the GCD. But, the most popular method to find the GCD is subtraction method. 
In this method, the larger number is subtracted by the smaller number and then the result is assigned to the variable holding larger number. This process keeps going till the numbers are equal. 



#include<stdio.h>

int main()
{
    int n1,n2,gcd,i;

    scanf("%d %d",&n1,&n2);

    if(n1<0){
        n1 = -n1;
    }
    if(n2<0){
        n2 = -n2;
    }

    for(i=1; n1!=n2; i++){
        if(n1>n2){
                gcd=n1 - n2;
                n1=gcd;
        else{
            gcd=n2 - n1;
                n2=gcd;
                }
    }
   
    printf("%d",gcd);
    return 0;

}

No comments

Powered by Blogger.