C++ Example - Find the greatest common divisor of two numbers

C++ Examples

User inputs two numbers and finds the greatest common divisor of these two numbers.

Example

#include <iostream> using namespace std; int main() { int n1, n2; cout << "Enter two integers:"; cin >> n1 >> n2; while(n1 != n2) { if(n1 > n2) n1 -= n2; else n2 -= n1; } cout << "HCF = " << n1; return 0; }

The output of the above program execution is:

输入两个整数: 78
52
HCF = 26

Example

#include <iostream> using namespace std; int main() { int n1, n2, hcf; cout << "Enter two integers:"; cin >> n1 >> n2; //If n2 is greater than n1, swap the two variables 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; }

The output of the above program execution is:

输入两个整数: 78
52
HCF = 26

C++ Examples

other extensions