Video lecture
Watch on YouTube(opens in a new tab)Sub topic 2
The Properties Every Algorithm Must Have
This chapter assumes you can read simple Python, follow a while loop, and compute remainders with %. It also assumes you have seen Euclid's algorithm for the greatest common divisor (GCD), which runs through the whole tutorial.
Not every list of instructions is an algorithm. A recipe that says "season to taste" or "bake until done" works for a cook, but a machine cannot follow it. Donald Knuth's widely used definition names five properties that separate an algorithm from an arbitrary procedure: finiteness, definiteness, input, output, and effectiveness. This chapter covers each one, tests Euclid's algorithm against it, and shows the ways real descriptions fail it.
The Running Example
Here is Euclid's algorithm again in Python. A step counter is added so you can see how much work it does.
def gcd_with_steps(a, b):
steps = 0
while b != 0:
a, b = b, a % b
steps += 1
return a, steps
print(gcd_with_steps(48, 18)) # (6, 3)
print(gcd_with_steps(17, 5)) # (1, 3)
print(gcd_with_steps(7, 0)) # (7, 0)Each section below checks this procedure against one property.
Finiteness
Finiteness means the algorithm always stops after a finite number of steps, for every valid input. Stopping on the inputs you happened to try is not enough.
Euclid's algorithm is finite. Each pass replaces b with a % b, which is always smaller than b and never negative. A non-negative integer cannot keep shrinking forever, so b reaches 0. A later chapter, "Does It Stop? Arguing Termination", turns this argument into a general technique.
Gotcha: finiteness depends on the allowed inputs
A closely related GCD method repeatedly subtracts the smaller number from the larger one. It works for positive integers. If either input is zero, it never stops:
def gcd_subtract(a, b, max_steps=1000):
steps = 0
while a != b:
if steps >= max_steps:
return None, steps # gave up: no sign of stopping
if a > b:
a = a - b
else:
b = b - a
steps += 1
return a, steps
print(gcd_subtract(48, 18)) # (6, 4)
print(gcd_subtract(5, 0)) # (None, 1000): a stays 5 foreverWith b = 0, the step a = a - b leaves a unchanged, so the loop makes no progress. The max_steps guard exists only so the demonstration can finish. The procedure is an algorithm for positive integers and fails finiteness for non-negative integers. This is why a precise statement of the allowed inputs, covered in the chapter on specifications, is part of the algorithm itself.
Edge case: "finite" is not "fast"
Finiteness says nothing about speed. A procedure that tries every possible password until one works is finite, even if it would take longer than the age of the universe. Efficiency is a separate question, covered in "How Much Work? Counting Steps and Big-O".
Edge case: procedures nobody can classify
The Collatz procedure goes like this: while n is not 1, halve it if it is even, otherwise replace it with 3n + 1. Every positive integer anyone has tested reaches 1, but nobody has proved that all of them do. So nobody knows whether this procedure has the finiteness property. For a correct description, "it stopped on my tests" is not evidence of finiteness. You need an argument.
Definiteness
Definiteness means every step is stated exactly, with only one way to interpret it. Two people, or a person and a machine, following the steps on the same input must do exactly the same thing.
"Compute r, the remainder of a divided by b" is definite for non-negative integers. These steps are not:
- "Choose a suitable divisor." Suitable by what rule?
- "Repeat until the numbers are close enough." How close?
- "Sort the list if it is large." Large compared to what?
Gotcha: hidden ambiguity in "obvious" operations
Some operations look definite but are not, because languages disagree on what they mean. The remainder of a negative number is the classic example:
print(-7 % 3) # 2 (Python: result has the sign of the divisor)
import math
print(math.fmod(-7, 3)) # -1.0 (C-style: result has the sign of the dividend)Euclid's precondition, that inputs are non-negative, avoids the problem. If you widen the inputs to all integers, you must say which remainder you mean. Otherwise the description is no longer definite.
Edge case: randomized algorithms
An instruction like "pick a random element as the pivot" seems to break definiteness. The usual answer is to treat the random choices as an extra input: given the same input and the same sequence of random bits, the steps are fully determined. Randomized algorithms such as randomized quicksort are standard and respectable. What they need is an exact statement of the distribution being sampled. "Pick any element you like" does not give one.
Input
Input means the algorithm takes zero or more values, drawn from a clearly stated set, before or while it runs. Euclid takes two inputs: non-negative integers a and b, not both zero.
Zero inputs is allowed. A procedure that prints the first 100 primes takes no input. What matters is that the input set is stated. As the subtraction example showed, the same steps can be an algorithm for one input set and not for another.
Output
Output means the algorithm produces one or more values that have a specified relationship to the inputs. Euclid outputs one value: the GCD of a and b.
Gotcha: "no result" is still an output
Linear search returns -1 when the target is absent. That value is a deliberate output that means "not found". A procedure that quietly does nothing in that case has no stated output for that input, and its description is incomplete. If every input does not lead to a defined output, failure included, the description has a hole.
Effectiveness
Effectiveness means each step is basic enough to be carried out exactly, in finite time, by someone working with pencil and paper. Integer remainder, comparison, and assignment all qualify.
Steps that fail effectiveness include:
- "Let x be the exact decimal expansion of √2." It is infinite.
- "If this program would eventually halt, do A, otherwise do B." No general method for this exists. This is the halting problem.
- "Find the largest prime." There isn't one.
Gotcha: effectiveness depends on the level of description
"Sort the list" is not a basic step for a person following instructions by hand, but in a high-level description it is a reasonable step, because sorting is itself a known algorithm. A step is effective if it is basic or if it can be expanded into effective steps. "Decide whether the program halts" can never be expanded that way. The chapter "Choosing the Right Level of Detail" returns to this.
Checking All Five at Once
| Property | Question it answers | Euclid's algorithm | Typical violation |
|---|---|---|---|
| Finiteness | Does it always stop? | Yes, `b` strictly decreases toward 0 | Subtraction GCD with a zero input |
| Definiteness | Does each step have one meaning? | Yes, for non-negative integers | "Repeat until close enough" |
| Input | What does it receive, from what set? | Two non-negative integers, not both zero | Input set never stated |
| Output | What does it produce? | The GCD of the inputs | No result defined when the search fails |
| Effectiveness | Can each step be done exactly? | Yes, remainder and assignment | "Compute √2 exactly" |
Common Errors
- Testing instead of arguing finiteness. Trying a few inputs never shows that the procedure stops on all of them.
- Leaving the input set implicit. The same steps can be finite on one set and loop forever on another.
- Hiding ambiguity in a familiar word. "Remainder", "round", and "largest" each need a precise meaning at the edge cases: negatives, halfway values, ties.
- Forgetting the failure output. Every input needs a defined result, including "not found" or "invalid".
- Treating an impossible step as a basic one. A step that looks short can still be impossible to carry out.
Exercise
A student describes this procedure: "Input: a positive integer n. While n is greater than 1, if n is even set n to n/2, otherwise set n to n + 1. Output the number of steps taken." Which of the five properties does it satisfy, and how would you justify finiteness?
Show answer
It has a stated input (positive integers) and a stated output (the step count). Each step is definite and effective, since it uses only parity tests, halving, and adding 1. For finiteness: an odd n greater than 1 becomes the even number n + 1, and the next step halves it to (n + 1)/2, which is less than n whenever n > 1. So every two steps at most, n strictly decreases, and a positive integer cannot decrease forever. The loop therefore stops, and the procedure is an algorithm.
Exercise
The description "Input: a list of numbers. Output: the median. Step: sort the list and return the middle element" fails one property for some inputs. Which one, and how would you fix it?
Show answer
It fails definiteness and output for even-length lists, which have no single middle element, and for the empty list, which has no median at all. Fix it by stating the input set (a non-empty list) and defining the even case exactly, for example "return the mean of the two middle elements" or "return the lower of the two middle elements".
Exercise
Explain why "Input: a Python function f. Output: True if calling f() eventually returns, False otherwise" cannot be turned into an algorithm, even though its input and output are clearly stated.
Show answer
This is the halting problem. It has been proved that no procedure built from effective steps can answer this correctly for every function. Any description has to contain a step like "determine whether f() halts", which cannot be expanded into basic steps. The description therefore fails effectiveness. It also fails finiteness, because simply running f() and waiting may never stop.