GCD of Two Numbers
Program to find Greatest Common Divisor using Euclidean algorithm
IntermediateTopic: Loop Programs
C++ GCD of Two Numbers Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
int main() {
int a, b, temp;
cout << "Enter two numbers: ";
cin >> a >> b;
int originalA = a, originalB = b;
// Euclidean algorithm
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
cout << "GCD of " << originalA << " and " << originalB << " is: " << a << endl;
return 0;
}Output
Enter two numbers: 48 18 GCD of 48 and 18 is: 6
Understanding GCD of Two Numbers
The Euclidean algorithm finds GCD by repeatedly applying: GCD(a, b) = GCD(b, a % b) until b becomes 0. The GCD is then the value of a. This is an efficient method that works for any two positive integers.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.