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 Theory

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. Repeating this shrinks the problem quickly until the remainder is 0, at which point the other number is the GCD.

How GCD Works

  1. Given two numbers a and b, if b is 0, then a is the GCD — stop.
  2. Otherwise, compute the remainder of a divided by b (a mod b).
  3. Replace a with b, and replace b with that remainder.
  4. Repeat the process with the new a and b values.
  5. 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.

Number Theory: GCDO(log min(a,b))
Euclid: replace (a,b) with (b, a mod b) until b = 0.
48
0
18
1
steps0
Step 1 / 5
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
GCD(48, 18) via Euclid: replace (a, b) with (b, a mod b) until b = 0.
Python · Number Theory in Code
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

Behind 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

BestO(1)
AverageO(log(min(a,b)))
WorstO(log(min(a,b)))
SpaceO(1) iterative, O(log(min(a,b))) if implemented recursively

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.