Give it a name
Naming intermediate values
Say it without names
Try describing the divisor algorithm without names: "Check the first number, then the next one, and if that number divides the original number, put it with the ones you have found so far …"
What makes the book's version shorter and clearer?
What this lesson covers
The idea
Giving names such as j or list-of-divisors to the values being tracked lets an algorithm be described concisely.
Say it without names
Try describing the divisor algorithm without names: "Check the first number, then the next one, and if that number divides the original number, put it with the ones you have found so far …"
What makes the book's version shorter and clearer?
- It gives names, like j and list-of-divisors, to the values it tracks
- It leaves out the checks
- It uses bigger numbers
Follow j and the list
The book names two values: j, the number being checked next, and list-of-divisors, the divisors found so far. Run the algorithm for 135 (one of the book's Think and Reflect numbers) and watch both change.
Names make it short
Giving names to the values an algorithm keeps track of, such as j or list-of-divisors, lets us describe it concisely.
"For each number j in 1, 2, 3, …, n: if j divides n, add j to the list-of-divisors." Without the name j, it would be clumsy to say what to do each time we find a divisor. For 135: list-of-divisors ends as [1, 3, 5, 9, 15, 27, 45, 135].
Notes
Name the values an algorithm keeps track of, such as j and list-of-divisors, so the steps can be written concisely.
Check yourself
In the divisor algorithm, what does the name j stand for?
Running the algorithm for n = 135, what is the value of j at the last check?
Answer: 135
The last check is j = 135.
For 135, after j = 9 has been checked, list-of-divisors is …
- The number being checked next as a possible divisor — correct. Yes. j takes the values 1, 2, 3, …, n in turn.
- The number whose divisors we want. That is n.
- The number of divisors found so far. The algorithm does not count them; it keeps them in list-of-divisors.
- [1, 3, 5, 9] — correct. Yes. 1, 3, 5 and 9 are the divisors of 135 up to 9.
- [1, 3, 5, 9, 15]. 15 has not been checked yet.
- [9]. Earlier divisors stay in the list.