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

An algorithm to list divisors

🤔
Think first
How would you tell a robot, step by step, to find all the factors of 18?
🎯 In this lesson you'll learn
  • ✓Write and run divisors(n)
  • ✓Use names to track values

The gcd (greatest common divisor), also called the hcf, of two numbers is the largest number dividing both. Plan: list the divisors of each number, then find the largest one in both lists.

Algorithm divisors(n):

  1. Start with an empty list-of-divisors.
  2. For each j in 1, 2, 3, …, n: if j divides n, add j to the end of the list.

Executing it for n = 18 (square brackets mean a list):

[ ] → 1 divides: [1] → 2: [1, 2] → 3: [1, 2, 3] → 4, 5 don't → 6: [1, 2, 3, 6] → 7, 8 don't → 9: [1, 2, 3, 6, 9] → 10 to 17 don't → 18: [1, 2, 3, 6, 9, 18]

Because we test j in order, the list comes out in increasing order.

  • divisors(375) = [1, 3, 5, 15, 25, 75, 125, 375]
  • divisors(825) = [1, 3, 5, 11, 15, 25, 33, 55, 75, 165, 275, 825]

Names like list-of-divisors and j let us describe each step clearly.

123456789101112131415161718j = 1, 2, 3, … 18: keep j if it divides 18[ ] →[1] →[1, 2] →[1, 2, 3] →[1, 2, 3, 6] →[1, 2, 3, 6, 9] →list-of-divisors = [1, 2, 3, 6, 9, 18]

Tap the diagram to enlarge it

Testing j = 1 to 18 in order builds the divisor list in increasing order.
📌 Remember these
  1. Start with [ ]
  2. Test every j from 1 to n
  3. The list comes out in order
✅ Quick check
← →