T TestsWorld
Lesson 4 of 8 Divisors and a first gcd algorithm ⏱ 4 min

A first gcd algorithm and data structures

🤔
Think first
Two long lists of factors: how do you find the biggest number they share without missing one?
🎯 In this lesson you'll learn
  • ✓Find gcd from two divisor lists
  • ✓Know what a data structure is

Algorithm gcd(m, n):

  1. Let divisors-of-m = divisors(m).
  2. Let divisors-of-n = divisors(n).
  3. Start with an empty list common-divisors.
  4. For each x in divisors-of-m: if x is also in divisors-of-n, add x to common-divisors.
  5. 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.

divisors(375)135152575125375divisors(825)135111525335575165275825common: [1, 3, 5, 15, 25, 75] → gcd = 75

Tap the diagram to enlarge it

The largest number in both divisor lists is the gcd.
📌 Remember these
  1. Keep the common ones
  2. gcd = rightmost common
  3. 1 is always common
✅ Quick check
← →