#include <iostream>
using namespace std;
int main() {
int n1, n2, hcf;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
// swapping variables n1 and n2 if n2 is greater than n1.
if ( n2 > n1) {
int temp = n2;
n2 = n1;
n1 = temp;
}
for (int i = 1; i <= n2; ++i) {
if (n1 % i == 0 && n2 % i ==0) {
hcf = i;
}
}
cout << "HCF = " << hcf;
return 0;
}
Enter two numbers: 9
12
HCF = 3
n1
and n2
is stored in n2
. Then the loop is iterated from i = 1
to i <= n2
and in each iteration, the value of i is increased by 1.i
then, that number is stored in variable hcf
.HCF
will be stored in variable hcf
.#include <iostream>
using namespace std;
int main() {
int n1, n2;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
while(n1 != n2) {
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
cout << "HCF = " << n1;
return 0;
}
Enter two numbers: 6
9
HCF = 3
n1 -= n2
is the same as n1 = n1 - n2
. Similarly, n2 -= n1
is the same as n2 = n2 - n1
.