C++ Program to Calculate GCD of Two Numbers

Here is a C++ program to calculate GCD and HCF of two numbers.


C++ program to find GCD of two numbers

#include <iostream>

using namespace std;  
 
int getMinimum(int a, int b){
    if(a >= b)
        return b;
    else
        return a;
}
 
int main() {  
    int a, b, min, i, gcd = 1;  
    /* 
     * Take two numbers as input from user  
     */ 
    cout << "Enter Two Integers\n";  
    cin >> a >> b;  
   
    min = getMinimum(a, b);
    // Search for larget number less than min which divides both a and b
    for(i = 1; i <= min; i++) {  
        if(a%i==0 && b%i==0) {
            /* Update GCD to new larger value */
            gcd = i;  
        }  
    }  
   
    cout << "GCD of " << a << " and " << b << " is " << gcd; 
    return 0;  
}
Output
Enter Two Integers
30 12
GCD of 30 and 12 is 6

C++ program to find GCD of two numbers by repetative subtracting

#include <iostream>

using namespace std;

int main() {
    int num1, num2;
    cout << "Enter Two Integers\n";
    cin >> num1 >> num2;
    
    while(num1 != num2) {
        if(num1 > num2)
            num1 = num1 - num2;
        else
            num2 = num2 - num1;
    }

    cout << "GCD is " << num1;
    
    return 0;
}
Output
Enter Two Integers
22 8
GCD is 2

Recommended Posts
C++ Program to Find GCD or HCF of Two Numbers Using Recursion
C++ Program to Find LCM and GCD of Two Numbers
C++ Program to Make a Simple Calculator
C++ Program to Find Factorial of a Number
C++ Program to Convert Decimal Number to Binary Number
C++ Program to Convert Temperature from Celsius to Fahrenheit
C++ Program to Check Prime Number
C++ Program to Check Prime Number Using Function
C++ Program to Find Largest Element of an Array
C++ Program to Find Smallest Element in Array
C++ Program to Calculate Standard Deviation
All C++ Programs