Algorithm gcd(m, n):
- Let divisors-of-m = divisors(m).
- Let divisors-of-n = divisors(n).
- Start with an empty list common-divisors.
- For each x in divisors-of-m: if x is also in divisors-of-n, add x to common-divisors.
- Report the rightmost element of common-divisors.
gcd(375, 825): of [1, 3, 5, 15, 25, 75, 125, 375], the numbers 1, 3, 5, 15, 25, 75 are in the second list; 125 and 375 are not. common-divisors = [1, 3, 5, 15, 25, 75], so gcd = 75.
Since both lists increase, the common list increases too, and the gcd is its last element. The list always contains 1.
For big numbers like 54000 and 81000 the lists are long (80 entries each), but the same steps give gcd = 27000.
A list is an example of a data structure: a way to organise intermediate values so an algorithm can use them.
Tap the diagram to enlarge it
📌 Remember these
- Keep the common ones
- gcd = rightmost common
- 1 is always common