Visualize

Pattern visualizer

GCD of Two Numbers

The key insight: the greatest common divisor (GCD) of two numbers does not change if we replace the larger number with its remainder upon division by the smaller. Euclidean algorithm repeatedly replaces (a, b) with (b, a % b) — the last non-zero remainder is the GCD. This reduces the problem size rapidly because the remainder is always smaller than the divisor, guaranteeing termination. We show each (a, b) pair transition step by step. Animated on: Compute the greatest common divisor of a = 48 and b = 18 using the Euclidean algorithm. Answer: 6..

Math

time O(log(min(a,b)))space O(1)step 1 / 9
48
[0]
18
[1]
line 1

Initial values: a = 48, b = 18. We'll compute GCD(48, 18) using the Euclidean algorithm. The algorithm repeatedly replaces (a, b) with (b, a % b).

Pseudocode
1FUNCTION gcd(a, b):
2 WHILE b > 0:
3 temp = remainder of a divided by b
4 a = b
5 b = temp
6 RETURN a

← / → step · space play · Home restart

Where to practice Math