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), lcm from gcd, a live preview, worked PHP 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.
Reuse gcd
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 abs). |
| Return | int | Nonnegative gcd (0 for the (0, 0) convention here). |
function gcd(a, b):
a = abs(a)
b = 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 |
| LCM demo | intdiv(abs(ab), gcd) | Reuse your gcd helper |
| Goal | Pattern |
|---|---|
| Normalize | $a = abs($a); $b = abs($b); |
| Euclid step | [$a, $b] = [$b, $a % $b] |
| Stop | while ($b !== 0) then return $a |
| LCM | intdiv(abs($a * $b), gcd($a, $b)) |
| LCM | intdiv(abs($a * $b), gcd($a, $b)) |
| Classic | gcd(48, 18) = 6 |
Same Euclidean math — pick by clarity and constraints.
while b: a,b=b,a%bO(1) space — best default
gcd(b, a % b)Reads like the textbook rule
intdiv(abs(ab), g)Reuse gcd in app code
write EuclidThen mention GMP or 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 PHP programs — iterative Euclid, recursive Euclid, and an LCM demo. 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.
<?php
function findGcd(int $num1, int $num2): int
{
$num1 = abs($num1);
$num2 = abs($num2);
while ($num2 !== 0) {
[$num1, $num2] = [$num2, $num1 % $num2];
}
return $num1;
}
$number1 = 48;
$number2 = 18;
$g = findGcd($number1, $number2);
echo "GCD of $number1 and $number2 is: $g" . PHP_EOL;
?> 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).
<?php
function gcdRecursive(int $a, int $b): int
{
$a = abs($a);
$b = abs($b);
if ($b === 0) {
return $a;
}
return gcdRecursive($b, $a % $b);
}
$number1 = 48;
$number2 = 18;
echo "GCD of $number1 and $number2 is: " . gcdRecursive($number1, $number2) . PHP_EOL;
?> Recursive calls follow the same remainder chain as iterative Euclid, then return the final nonzero value. Stack depth is O(log min(a, b)).
Reuse gcd to compute lcm with |ab|/gcd.
Reusable gcd helper plus the classic LCM identity.
<?php
function gcd(int $a, int $b): int
{
$a = abs($a);
$b = abs($b);
while ($b !== 0) {
[$a, $b] = [$b, $a % $b];
}
return $a;
}
function lcm(int $a, int $b): int
{
if ($a === 0 || $b === 0) {
return 0;
}
return intdiv(abs($a * $b), gcd($a, $b));
}
foreach ([[48, 18], [17, 13], [0, 21], [-12, 18]] as [$a, $b]) {
$g = gcd($a, $b);
echo "gcd($a, $b) = $g, lcm = " . lcm($a, $b) . PHP_EOL;
}
?> Prefer a tested gcd helper in real projects (normalize with abs first). In interviews, write Euclid yourself first, then mention GMP if needed and the LCM identity.
Set a = abs(a), b = 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 find_gcd(a, b).
Simplify p/q by dividing by gcd.
Example: 18/48 → 3/8.
Compute least common multiple safely.
Example: intdiv(abs(a*b), gcd(a,b)).
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 lcm/GMP 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 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.
→ Watch integer overflow on large products; use intdiv and abs carefully.
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.
Large integers can overflow; GMP helps for big values.
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 |
| LCM demo | 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 reuse gcd for lcm in production.
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 abs()
Guardlcm demo
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