top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to write a C program to find the GCD of two numbers?

+10 votes
1,722 views
How to write a C program to find the GCD of two numbers?
posted Nov 18, 2013 by Mona Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes
// Iterative algorithm
int gcd( inta, int b)
{
    int temp;
    while(b)
    {
        temp = a % b; 
        a = b; 
        b = temp;
    }
    return(a);
}
// Recursive algorithm
int gcd_recurse( inta, int b)
{
    int temp;
    temp = a % b;

    if (temp == 0)
        return(b);
    else
        return(gcd_recurse(b, temp));
}
answer Nov 18, 2013 by Vikas Upadhyay
0 votes
int getGCD(int a, int b)
{
    if(a > b){
        if(a % b == 0){
            return b;
        }
        else{
            b = a % b;
            getGCD(a, b);
        }
    }
    else{
        if(b % a == 0){
            return a;
        }
        else{
            a = b % a;
            getGCD(a, b);
        }
    }
}
answer Nov 18, 2013 by Salil Agrawal
ur style of programming is wonderfull sir
Thanks Yaswanth
this program not work properly for some inputs like
getGCD(0,0);
getGCD(6,0);
Yes if one of the input is zero.
...