Sunday 15 June 2014

C++ program to calculate Greatest Common Divisor(GCD)

Here are three C++ program to calculate Greatest Common Divisor(GCD) or Highest Common Factor(HCF) of two numbers using for-loop, recursion(Euclid Method) and class.


C++ program to calculate Greatest Common Divisor

#include<iostream>
using namespace std;
int main()
{
    int i, a, b, n, gcd;
    cout<<" Enter the First Number : ";
    cin>>a;
    cout<<" Enter the Second Number : ";
    cin>>b;
    if(a>b)
        n=a;
    else
        n=b;
    for(i=1;i<=n;i++)
    {
        if(a%i==0&&b%i==0)
        {
            cout<<" "<<i;
            gcd = i;
        }
    }
    cout<<"\n Greatest Common Divisor : "<<gcd;
    return 0;
}



C++ program to calculate Greatest Common Divisor using recursion(Euclid Method)

#include<iostream>
using namespace std;
int gcd(int num1,int num2)
{
    if(num2==1)
        return 1;
    else if(num1%num2==0)
        return num2;
    else
        return gcd(num2,num1%num2);
}
int main()
{
    int num1,num2;
    cout<<"Enter two numbers : ";
    cin>>num1>>num2;
    cout<<"Greatest Common divisor of two numbers : "<<gcd(num1,num2);
    return 0;
}



C++ program to calculate Greatest Common Divisor using class

#include<iostream>
using namespace std;
class gcd
{
private:
    int a,b,hcf;
public:
    void getdata()
    {
       cout<<"Enter the First Number : ";
       cin>>a;
       cout<<"Enter the Second Number : ";
       cin>>b;
    }
    int findgcd();
};
int gcd::findgcd()
{
    int n;
    if(a>b)
        n=a;
    else
        n=b;
    for(int i=1;i<=n;i++)
    {
        if(a%i==0&&b%i==0)
            hcf = i;
    }
    return hcf;
}
int main()
{
    gcd obj;
    obj.getdata();
    cout<<"\nGreatest Common Divisor : "<<obj.findgcd();
    return 0;
}





No comments:

Post a Comment