Finding GCD

Iterative way:

#include <iostream>

using namespace std;

int main()
{
    int a,b,x,gcd;
    cout<<"Enter one value: "<<endl;
    cin>>a;
    cout<<"Enter another value: ";
    cin>>b;
    if(a<b)
    {
        x=a;
    }
    else
    {
        x=b;
    }
    for(;x>=1;x--)
    {
        if(a%x==0 && b%x==0)
        {
            gcd=x;
            break;
        }
    }
    cout<<"GCD is "<<gcd<<endl;


    return 0;
}

 

Euclidian algorithm ( Recursive way):

#include <iostream>

using namespace std;


int main()
{
    int a,b,remainder,gcd;
    cout<<"Enter one value: "<<endl;
    cin>>a;
    cout<<"Enter another value: "<<endl;
    cin>>b;

    // Assuming a>b always

    while(remainder!=0)
    {
        remainder=a%b;
        if(remainder==0)
        {
            gcd=b;
            cout<<"GCD is "<<gcd<<endl;
        }
        a=b;
        b=remainder;
    }
    return 0;
}

The above code can be written further in a shortcut as follows:

#include <iostream>

using namespace std;

int gcd(int a,int b)
{
    return b==0 ? a : gcd(b,a%b);
}

int main()
{
    int c,d;

    for(;;)
    {
        cout<<"Enter any number:"<<endl;
        cin>>c;
        cout<<"Enter another number:"<<endl;
        cin>>d;

        cout<<"GCD is "<<gcd(c,d)<<endl<<endl;
    }


    return 0;
}

Leave a comment