GCD of Two Numbers in C++
GCD in C++ with Euclid: (a, b) → (b, a % b) until b is 0. GCD(48, 18) is 6.
1#include <iostream>2using namespace std;34int main() {5 int a, b, temp;67 cout << "Enter two numbers: ";8 cin >> a >> b;910 int originalA = a, originalB = b;1112 // Euclidean algorithm13 while (b != 0) {14 temp = b;15 b = a % b;16 a = temp;17 }1819 cout << "GCD of " << originalA << " and " << originalB << " is: " << a << endl;2021 return 0;22}
Output
Enter two numbers: 48 18 GCD of 48 and 18 is: 6
What's going on
GCD is the largest integer that divides both numbers. GCD(48, 18) is 6. This C++ program uses Euclid: replace (a, b) with (b, a % b) until b is 0. Then a is the GCD.
cin >> a >> b;
int originalA = a, originalB = b;
The loop overwrites a and b. Save copies for the print.
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
Walk 48 and 18:
a is 6. Print uses originalA and originalB: GCD of 48 and 18 is: 6.
If one number is 0, GCD is the other (Euclid stops immediately). Both 0 is undefined; this loop would hang or return 0 depending how you start — don't.
Order doesn't matter. GCD(18, 48) takes one extra remainder and lands on 6 too.
LCM is next: (a × b) / GCD. You need this loop first.