Algorithms · Visualized
Number Theory: GCD
Number Theory
Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.
Finds the greatest common divisor of two numbers using the insight that gcd(a, b) = gcd(b, a mod b), because any number that divides both a and b also divides their remainder. Time: O(log(min(a,b))) average, O(log(min(a,b))) worst; space: O(1) iterative, O(log(min(a,b))) if implemented recursively.
Big-O: GCD O(log min(a,b)); sieve O(n log log n).
GCD (Euclidean Algorithm)
Number TheoryFinds the greatest common divisor of two numbers using the insight that gcd(a, b) = gcd(b, a mod b), because any number that divides both a and b also divides their remainder. Repeating this shrinks the problem quickly until the remainder is 0, at which point the other number is the GCD.
How GCD Works
- Given two numbers a and b, if b is 0, then a is the GCD — stop.
- Otherwise, compute the remainder of a divided by b (a mod b).
- Replace a with b, and replace b with that remainder.
- Repeat the process with the new a and b values.
- Continue until b becomes 0; the final value of a is the greatest common divisor.
GCD Worked Example
Input: {a: 48, b: 18}
gcd(48,18): 48 mod 18 = 12 → gcd(18,12). 18 mod 12 = 6 → gcd(12,6). 12 mod 6 = 0 → gcd(6,0). b is now 0, so GCD = 6.
def gcd(a, b):
while b:
a, b = b, a % b
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
GCD Time & Space Complexity
When to Use GCD
- Simplifying fractions to lowest terms, cryptography (RSA key computations), and computing LCM.
- One of the oldest and most efficient algorithms in computer science, still used everywhere today.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.