Definition
Largest divisor
gcd(a, b) divides both; gcd = 1 means coprime.
The GCD of two integers is the largest positive integer that divides both. This tutorial covers Euclid’s algorithm (iterative and recursive), std::gcd, a live preview, worked C++ examples, edge cases, and complexity.
Largest divisor
gcd(a, b) divides both; gcd = 1 means coprime.
gcd(b, a%b)
Remainders shrink until b becomes 0.
gcd = 6
Trace: 48→18→12→6→0.
Library
Best for real code after you can write Euclid.
Try a, b
Compute gcd on magnitudes in the browser.
Euclid steps
Worst case near consecutive Fibonacci pairs.
The greatest common divisor gcd(a, b) is the largest positive integer that divides both a and b. Euclid’s rule gcd(a, b) = gcd(b, a % b) reduces the pair until the remainder is zero — then the leftover value is the answer.
Example: gcd(48, 18) = 6. If gcd is 1, the numbers are coprime. Also, lcm(a, b) = |a b| / gcd(a, b) for nonzero pairs.
GCD underpins fraction reduction, modular inverses, Diophantine equations, and many interview number-theory warm-ups.
(a, b) ← (b, a % b).
When b = 0, return a.
Keep the result nonnegative.
Equals |n| for n ≠ 0.
In short: replace (a, b) with (b, a % b) until b is 0; the leftover a is the gcd.
Given integers a and b, compute gcd(a, b).
// gcd(48, 18) = 6
// gcd(17, 13) = 1 (coprime)
// gcd(0, 21) = 21 | Item | Type | Description |
|---|---|---|
a, b | int | Any integers (we normalize with std::abs). |
| Return | int | Nonnegative gcd (0 for the (0, 0) convention here). |
function gcd(a, b):
a = std::abs(a)
b = std::abs(b)
while b != 0:
(a, b) = (b, a mod b)
return a | Method | Idea | Notes |
|---|---|---|
| Iterative Euclid | Loop with % | O(1) extra space — interview default |
| Recursive Euclid | gcd(b, a % b) | Matches the math formula closely |
| Library | std::gcd | Best for large ints / production helpers |
| Goal | Pattern |
|---|---|
| Normalize | a = std::abs(a); b = std::abs(b); |
| Euclid step | int t = b; b = a % b; a = t; |
| Stop | while (b != 0) then return a |
| Library | std::gcd(a, b) |
| LCM | std::llabs((long long) a / g * b) |
| Classic | gcd(48, 18) = 6 |
Same Euclidean math — pick by clarity and constraints.
while (b != 0) { ... }O(1) space — best default
gcd(b, a % b)Reads like the textbook rule
std::gcdPrefer for large integers
write EuclidThen mention std::gcd / binary gcd
Reach for GCD whenever common divisors or modular structure matter.
Classic modulo + loop problem with log-time analysis.
Divide numerator and denominator by gcd.
Inverse of a mod m exists when gcd(a, m) = 1.
Worst-case Euclid pairs are consecutive Fibonacci numbers.
State the convention (often 0) before coding.
Key benefit: a short log-time algorithm that unlocks fractions, LCM, and modular arithmetic.
Enter two integers (safe range). We compute gcd on magnitudes.
Three complete C++ programs — iterative Euclid, recursive Euclid, and std::gcd. Click View Output to reveal sample console results.
Interview-default loop with constant extra space.
Uses a loop to compute gcd for 48 and 18.
#include <iostream>
#include <cstdlib>
int findGcd(int num1, int num2) {
num1 = std::abs(num1);
num2 = std::abs(num2);
while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1;
}
int main() {
int number1 = 48;
int number2 = 18;
int g = findGcd(number1, number2);
std::cout << "GCD of " << number1 << " and " << number2
<< " is: " << g << "\n";
return 0;
} Each loop step keeps the gcd unchanged and reduces the second value until it becomes zero. The leftover first value is the answer.
Same remainder chain, written as a recurrence.
Base case b == 0; otherwise recurse on (b, a % b).
#include <iostream>
#include <cstdlib>
int gcdRecursive(int a, int b) {
a = std::abs(a);
b = std::abs(b);
if (b == 0) {
return a;
}
return gcdRecursive(b, a % b);
}
int main() {
int number1 = 48;
int number2 = 18;
std::cout << "GCD of " << number1 << " and " << number2
<< " is: " << gcdRecursive(number1, number2) << "\n";
return 0;
} Recursive calls follow the same remainder chain as iterative Euclid, then return the final nonzero value. Stack depth is O(log min(a, b)).
Use std::gcd when you do not need to reinvent Euclid.
std::gcd and LCMLibrary gcd plus the classic LCM identity.
#include <iostream>
#include <numeric>
#include <cstdlib>
int gcd(int a, int b) {
return (int) std::gcd(a, b);
}
long long lcm(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
int g = gcd(a, b);
return std::llabs((long long)a / g * b);
}
int main() {
int pairs[][2] = { { 48, 18 }, { 17, 13 }, { 0, 21 }, { -12, 18 } };
int count = sizeof(pairs) / sizeof(pairs[0]);
for (int i = 0; i < count; i++) {
int a = pairs[i][0];
int b = pairs[i][1];
std::cout << "gcd(" << a << ", " << b << ") = " << gcd(a, b)
<< ", lcm = " << lcm(a, b) << "\n";
}
return 0;
} Prefer std::gcd for large integers (it also handles negatives). In interviews, write Euclid yourself first, then mention the library helper and the LCM identity.
Set a = std::abs(a), b = std::abs(b).
While b != 0, replace (a, b) with (b, a % b).
When b is 0, a is the gcd.
Largest nonnegative common divisor.
gcd(48, 18)Trace the Euclidean remainder chain for the classic interview pair.
| Step | (a, b) | a % b | Next |
|---|---|---|---|
| 1 | (48, 18) | 12 | (18, 12) |
| 2 | (18, 12) | 6 | (12, 6) |
| 3 | (12, 6) | 0 | (6, 0) |
| 4 | (6, 0) | — | return 6 |
Final answer: gcd(48, 18) = 6.
Where GCD shows up beyond the interview prompt.
Modulo loops with clear log-time analysis.
Example: write findGcd(a, b).
Simplify p/q by dividing by gcd.
Example: 18/48 → 3/8.
Compute least common multiple safely.
Example: std::abs(a / g * b) with care for overflow.
Check coprimality for inverses.
Example: gcd(a, m) = 1.
GCD is the largest shared divisor.
Example: related interview page.
Extended Euclid finds x, y with ax + by = gcd.
Example: mention if asked for identity.
Pro Tip: say “gcd(a, b) = gcd(b, a % b)” before coding — it proves you know the invariant.
Why Euclid works well in interviews and classwork.
A few lines encode a deep number-theory idea.
O(log min(a, b)) steps in practice.
Iterative and recursive both match the math.
LCM, extended Euclid, and binary gcd.
Pro Tip: lead with iterative Euclid; offer recursive and std::gcd as follow-ups.
Small habits that keep GCD solutions interview-ready.
Keep the returned gcd nonnegative.
Say your convention (often 0) up front.
Expect 6; also try (0, 21) and (17, 13).
O(1) space and no recursion-depth worry.
Show you know |ab| / gcd when asked.
Pro Tip: worst-case Euclid step counts appear on consecutive Fibonacci inputs — a nice follow-up after the Fibonacci page.
Mistakes that commonly break GCD solutions.
Negative inputs can yield a negative-looking remainder story.
→ Normalize with std::abs first.
Crashing or returning nonsense.
→ Document convention (often return 0).
Looping from min(a, b) to 1 is O(min) and slow.
→ Use Euclid instead.
Computing a * b before dividing in fixed-width languages.
→ In C++, divide by gcd first or use long long to avoid int overflow: std::llabs((long long) a / g * b).
Special-casing zero incorrectly.
→ Euclid already handles it if abs is applied.
Normalize signs and define behavior for gcd(0, 0) explicitly.
gcd(0, 0)Many implementations return 0 by convention.
gcd(0, n)Equals |n| for n ≠ 0.
Use absolute values to keep gcd nonnegative.
gcd(a, b) = gcd(b, a)Input order does not change the answer.
gcd = 1Numbers share no common divisor greater than 1.
Use std::gcd; cost grows with digit length.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
Quick Takeaway: keep replacing (a, b) with (b, a % b) until b is 0; the leftover a is the gcd.
| Version | Time | Extra space |
|---|---|---|
| Iterative Euclid | O(log min(a, b)) | O(1) |
| Recursive Euclid | same | O(log min(a, b)) stack |
std::gcd | same order | O(1) |
Worst-case step count appears on consecutive Fibonacci inputs.
GCD is the largest nonnegative common divisor. Euclid reduces (a, b) via remainders until b is 0; write it iteratively in interviews and use std::gcd for large integers.
Practice the three examples above, then continue to happy numbers for a digit-square cycle problem.
Normalize signs, define gcd(0, 0), and mention the LCM identity when asked.
Compute gcd the interview-friendly way.
gcd(b, a%b)
Euclidb = 0 → a
Baseuse std::abs
Guardstd::gcd
ShipO(log min)
AnalysisBézout's identity: for integers a, b not both zero, there exist integers x, y such that gcd(a,b) = a x + b y.
Learn how happy numbers use repeated sums of squared digits until they reach 1 or a cycle.
9 people found this page helpful