C++ program to find the GCD or HCF of two numbers

Program to find the GCD or HCF of two numbers

 

Here we will discuss how to find the GCD or HCF of two numbers entered by the user using C++ programming language.

GCD i.e. Greatest Common Divisible or HCF i.e. Highest Common Factor of two numbers is the largest positive integer that can divide both the numbers

There are many methods to calculate GCD:

  • Using Prime Factorisation,
  • Euclid’s Algorithm,
  • Lehmer’s GCD algorithm, etc

Here we will use Euclid’s Algorithm to find the GCD, which is based on the idea that the GCD doesn’t change when smaller number is subtracted from the greater number. This keeps on going until only the GCD left.

C++ program to find the GCD or HCF of two numbers

Working

  • Two inputs are taken from the user.
  • Inputs are stored in two int type variables say first and second.
  • A recursive program findGCD is called with parameters first and second.
    • First it is checked whether any of the input is 0 

                                    if (first == 0)

                                              return second;

                                    if (second==0)

                                              return first;

    • If both input numbers are equal return any of the two numbers

                                    if (first == second)

                                              return second;

    • If first is greater than the second
      • Recursively call findGCD function with parameters ‘first-second’, second.

                                                          findGCD(first – second, second);

    • Otherwise recursively call findGCD function with parameters ‘first’, ‘second-first’.

                                     findGCD(first, second – first);

C++ code:

//C++ Program
//GCD of Two Numbers
#include<iostream>
using namespace std;
// Recursive function declaration
int findGCD(int, int);
// main program
int main()
{
int first, second;
        cout<<"Enter First Number: ";
        cin>>first;
        cout<<"Enter second Number: ";
cin>>second;
        cout<<"GCD of "<<first<<" and "<<second<<" is "<<findGCD(first,second);
        return 0;
}
//body of the function
int findGCD(int first, int second)
{
        // 0 is divisible by every number
        if(first == 0)
       {    
           return second;
       }
       if(second == 0)
        {    
           return first;
       }
       // both numbers are equal
        if(first == second)
        {
           return first;
        }
        // first is greater
        else if(first > second)
        {
           return findGCD(first - second, second);
       }
       return findGCD(first, second - first);
}

Output

Enter First Number: 20
Enter second Number: 25
GCD of 20 and 25 is 5

Please Login/Signup to comment