T TestsWorld
Lesson 5 of 8 Improving and analysing algorithms ⏱ 5 min

Making the gcd algorithm faster

🤔
Think first
Do we really need to remember every common divisor to find the greatest?
🎯 In this lesson you'll learn
  • ✓Improve an algorithm step by step
  • ✓Trace an algorithm by hand

The first algorithm checks 1 to m, then starts again and checks 1 to n: m + n checks.

Improvement 1: one scan. Run j from 1 to max(m, n) once, adding j to whichever list(s) it divides.

Improvement 2: common divisors directly. For j from 1 to max(m, n), if j divides both, add it to common-divisors. A common divisor can't exceed the smaller number, so scan only to min(m, n).

Improvement 3: no list at all. Every new common divisor makes the old ones useless. Keep one value, most-recent-common-divisor, starting at 1. For k from 2 to min(m, n): if k divides both, set it to k. At the end it is the gcd.

✏️

Example m = 6, n = 12: start 1 → k = 2 ✓ (2) → k = 3 ✓ (3) → k = 4 ✗ → k = 5 ✗ → k = 6 ✓ (6). gcd(6, 12) = 6.

Each version computes the same thing as the original, so all are correct. But even the last one checks every number up to min(m, n): 10 times the work for one more digit.

start: most-recent-common-divisor = 1k = 2✓ bothvalue 2k = 3✓ bothvalue 3k = 4✗ not 6value 3k = 5✗ not 6value 3k = 6✓ bothvalue 6scan complete: gcd(6, 12) = 6

Tap the diagram to enlarge it

Only the latest common divisor is kept; at the end it is the gcd.
📌 Remember these
  1. Scan once, not twice
  2. Stop at min(m, n)
  3. Keep one value, not a list
✅ Quick check
← →