c++ program to Find HCF or GCD

FInding GCD:

HCF is the highest common factor of the two numbers,how to find in the cpp programming language.
For the calculation of the HCF or GCD, you must have knowledge of the following topics.




Here is the code for finding GCD 

Code:
#include <iostream>
using namespace std;

int main()
{
    int num1, num2;

    cout << "Enter two numbers: ";
    cin >> num1 >> num2;
    
    while(num1 != num2)
    {
        if(num1 > num2)
            num1 -= num2;
        else
            num2 -= num1;
    }
    cout << "HCF = " << num1;
    return 0;
}

Output:

Enter two numbers: 13
26
HCF = 13


Here is another to find the GCD of the two number in cpp .


Code:
#include <iostream>
using namespace std;

int main() {
    int num1, num2, hcf;
    
    cout << "Enter first numbers "<<endl;
    cin >> num1;
    
    cout << "Enter second numbers "<<endl;
    cin >> num2;

    // Swap variable num1 and num2 if num2 is greater than num1.

    if ( num2 > num1) {   
        int temp = num2;
        num2 = num1;
        num1 = temp;
    }
    
    for (int i = 1; i <=  num2; i++) {
        if (num1 % i == 0 && num2 % i ==0) {
            hcf = i;
        }
    }

    cout << "HCF=" << hcf<<endl;
    return 0;
}

Output:

Enter first numbers
64
Enter second numbers
46
HCF=2

In the above code,take input of two number from the user , find the greater number between two number, use the for loop starting from the i=1 and find the number which is divisible both number .
This number is store in the hcf and display on the screen by output method.

Comments

Popular posts from this blog

how to cout in cpp

Flutter layout

Diferrence between flutter and react native