GCD of Two Numbers in C++

GCD of two numbers in C++ programming language. The greatest factor that is common to both the integers a and b is the greatest common divisor for any two positive integers (a, b). It’s also called the greatest common factor or the highest common factor.

#include <iostream>
using namespace std;

int main()
int a, b, hcf;
cout << "Enter two numbers";
cin >> a >> b;
if ( b > a)
int temp = b;
b = a;
a = temp;
for (int i = 1; i <= b; ++i)
if (a % i == 0 && b % i ==0)
hcf = i;
cout << "HCF = " << hcf;
return 0;



Enter two numbers

HCF = 1

GCD of Two Numbers in C++ and How it is Calculated

Euclid’s method for finding the greatest common divisor of two positive integers involves replacing the larger number with the difference between the two numbers and continuing the process until the two numbers are equal: this is their greatest common divisor.

HCF and GCD is Same or Not in C++

HCF stands for “highest common factors.” GCD stands for “greatest common divisor.” The only thing that distinguishes them is their names; otherwise, they are identical.

What is Temporary Variable in C++

A temporary variable is one that has a brief lifetime and is used to store data that will be destroyed quickly or before it can be stored in a more permanent memory location. It’s commonly stated as a local variable, or a variable with local scope, because it’s short-lived. This program can execute GCD of two numbers in C++ for beginners.

Similar Programs