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), math.gcd, a live preview, worked Python 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.
Builtin
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 |
math.gcd | Builtin | Best for production code |
| Goal | Pattern |
|---|---|
| Normalize | a, b = abs(a), abs(b) |
| Euclid step | a, b = b, a % b |
| Stop | while b != 0 then return a |
| Builtin | math.gcd(a, b) |
| LCM | 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
math.gcdShip this in real projects
write EuclidThen mention math.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 Python programs — iterative Euclid, recursive Euclid, and math.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.
def find_gcd(num1: int, num2: int) -> int:
num1, num2 = abs(num1), abs(num2)
while num2 != 0:
num1, num2 = num2, num1 % num2
return num1
number1 = 48
number2 = 18
g = find_gcd(number1, number2)
print(f"GCD of {number1} and {number2} is: {g}") 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).
def gcd_recursive(a: int, b: int) -> int:
a, b = abs(a), abs(b)
if b == 0:
return a
return gcd_recursive(b, a % b)
number1 = 48
number2 = 18
print(f"GCD of {number1} and {number2} is: {gcd_recursive(number1, number2)}") 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 the standard library when you do not need to reinvent Euclid.
math.gcd and LCMBuiltin gcd plus the classic LCM identity.
import math
def lcm(a: int, b: int) -> int:
if a == 0 or b == 0:
return 0
return abs(a * b) // math.gcd(a, b)
for a, b in ((48, 18), (17, 13), (0, 21), (-12, 18)):
g = math.gcd(a, b)
print(f"gcd({a}, {b}) = {g}, lcm = {lcm(a, b)}") Prefer math.gcd in real projects (it also handles negatives). In interviews, write Euclid yourself first, then mention the builtin 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: |ab| // 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 math.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 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 Python ints grow; still prefer abs(a // g * b) patterns when careful.
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.
Python supports them; runtime 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 |
math.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 math.gcd 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()
Guardmath.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