HCF or the Highest Common Factor is defined as the highest number which can able to divide all the numbers perfectly. The highest common factor (HCF) is also called the greatest common divisor (GCD).
In this program, we are using the Division method to find the HCF or GCD using the below steps
Recursion can be defined as a function that calls itself repeatedly until a condition is met.
Ask the user to enter two positive integers and read the number to the variables n1 and n2. Define a recursive function HCF() to find the G.C.D of the number. Then pass the entered number to the HCF function. In this function, check the condition n2 != 0 using an if
conditional statement. then, perform the operation recursively by calling the function with arguments n2, n1 % n2, and return the value.
return hcf(n2, n1 % n2); else return the value n1 to the main function. return n1;
Step 1: Call the header file iostream
.
Step 2: Use the namespace std.
Step 3: Define a function HCF ( );
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1
Step 4: Open the integer type main function; int main().
Step 5: Declare integer variables; n1 and n2;
Step 6: Print a message to enter two positive integers;
Step 7: Read the value into the variables n1 and n2;
Step 8: Call the function HCF(int n1, int n2);
Step 9: Exit;
#include <iostream>
using namespace std;
int hcf(int n1, int n2);
int main()
{
int n1, n2;
cout << "Enter two positive integers: ";
cin >> n1 >> n2;
cout << "H.C.F of " << n1 << " & " << n2 << " is: " << hcf(n1, n2);
return 0;
}
int HCF(int n1, int n2)
{
if (n2 != 0)
return HCF(n2, n1 % n2);
else
return n1;
}
Enter two positive integers: 8 12 H.C.F of 8 & 12 is: 4