In this C++ tutorial, you will learn how to write a program to find the HCF (Highest Common Factor) of given two numbers.

C++ HCF or GCD of Two Numbers

To find the HCF of two numbers in C++, take any of the two numbers in hcf, and other number in a temp variable. Decrement the largest of these two by the other until the values in these two variables are same. When they are same, we have HCF in both of these variables.

Program

In the following program, we read two numbers to n1 and n2, and find their HCF.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
    int n1, n2;
    cout << "Enter first number : ";
    cin >> n1;
    cout << "Enter second number : ";
    cin >> n2;
    
    int hcf = n1, temp = n2;
    while(hcf != temp) {
        if(hcf > temp)
            hcf = hcf - temp;
        else
            temp = temp - hcf;
    }
    
    cout << "HCF : " << hcf << endl;
}

Output

Enter first number : 15
Enter second number : 10
HCF : 5
Program ended with exit code: 0
Enter first number : 12
Enter second number : 16
HCF : 4
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to find HCF of two numbers in C++, with example program.