Algorithm
-
Input:
Accept two integers as input. -
Initialization:
-
Initialize two variables to store the input integers, say
num1
andnum2
. -
Algorithm:
Seta
to the larger ofnum1
andnum2
, andb
to the smaller. - Use a loop to repeatedly update
a
tob
andb
to the remainder when dividinga
byb
, untilb
becomes 0. - The value of
a
at this point is the GCD. -
Output:
Print the GCD.
Code Examples
#1 Code Example- C++ Programing Find HCF/GCD
Code -
C++ Programming
#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;
}
Copy The Code &
Try With Live Editor
Output
Enter two numbers: 16
76
HCF = 4
76
HCF = 4
#2 Code Example- C++ Programing Find GCD/HCF using while loop
Code -
C++ Programming
#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;
}
Copy The Code &
Try With Live Editor
Output
Enter two numbers: 16
76
HCF = 4
76
HCF = 4
Demonstration
C++ Programing Example to Find GCD-DevsEnv