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.
Tap the diagram to enlarge it
- Scan once, not twice
- Stop at min(m, n)
- Keep one value, not a list