top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

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

+10 votes
185 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 Google+ Share Button LinkedIn Share Button Multiple Social 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.
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...