The GCD of two positive integers is the largest integer that divides both of them without leaving a remainder (the GCD of two integers in general is defined in a more subtle way).
In its simplest form, Euclid’s algorithm starts with a pair of positive integers, and forms a new pair that consists of the smaller number and the difference between the larger and smaller numbers. The process repeats until the numbers in the pair are equal. That number then is the greatest common divisor of the original pair of integers.
The main principle is that the GCD does not change if the smaller number is subtracted from the larger number. For example, the GCD of 252 and 105 is exactly the GCD of 147 (= 252 – 105) and 105. Since the larger of the two numbers is reduced, repeating this process gives successively smaller numbers, so this repetition will necessarily stop sooner or later — when the numbers are equal (if the process is attempted once more, one of the numbers will become 0).
Here is source code of the C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
using namespace std;
int gcd(int u, int v)
return (v != 0) ? gcd(v, u % v) : u;
int num1, num2, result;
cout << "Enter two numbers to find GCD using Euclidean algorithm: ";
cin >> num1 >> num2;
result = gcd(num1, num2);
cout << "\nThe GCD of " << num1 << " and " << num2 << " is: " << result
cout << "\nInvalid input!!!\n";
$ g++ GCDEuclidean.cpp $ a.out Enter two numbers to find GCD using Euclidean algorithm: 12 30 The GCD of 12 and 30 is: 6
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Buy Computer Science Books
- Apply for C++ Internship
- Apply for Computer Science Internship
- Practice Computer Science MCQs
- Apply for Information Technology Internship