Video lecture
Watch on YouTube(opens in a new tab)Sub topic 3
Problems, Algorithms and Programs Are Different Things
This chapter assumes you can read simple Python, know what a function and a loop are, and are comfortable with the remainder operator (% in Python, mod in pseudocode). It builds on the definition of an algorithm and its properties from the previous chapters.
People often say "the GCD algorithm" when they mean a Python function, or "the sorting problem" when they mean quicksort. In casual talk that does little harm. When you are designing, debugging or judging a solution, though, you need to keep three things apart:
- A problem says what is wanted. It relates each allowed input to the outputs that count as correct.
- An algorithm says how to get a correct output. It is a finite, definite, effective method that works for every allowed input.
- A program is one algorithm written in a particular language, so that a particular kind of machine can run it.
Three levels, three questions
Each level answers a different question, and each has its own way to fail.
| Level | Question it answers | Example | Typical way it goes wrong |
|---|---|---|---|
| Problem | What output is correct for each input? | "Given non-negative integers a and b, not both zero, return their greatest common divisor." | Vague or incomplete: nobody said what happens when both inputs are zero. |
| Algorithm | What steps produce a correct output? | Euclid's method: replace (a, b) with (b, a mod b) until b is 0. | Wrong idea: it gives incorrect answers or never stops on some inputs. |
| Program | How are those steps written for a real machine? | A Python `while` loop using `%`. | Implementation faults: typos, off-by-one errors, overflow, wrong types, recursion limits. |
The problem stays the same no matter how you solve it. The algorithm stays the same no matter which language you write it in. The program is the only level that a computer actually runs.
One problem, many algorithms
The GCD problem has several quite different algorithms. Two of them:
- Consecutive integer checking. Start with d = min(a, b). If d divides both a and b, return d. Otherwise decrease d by 1 and try again.
- Euclid's algorithm. If b is 0, return a. Otherwise replace (a, b) with (b, a mod b) and repeat.
Both solve the same problem, but they are not the same algorithm. They take different steps, they need different amounts of work, and they accept slightly different inputs. Here they are as Python programs, side by side:
def gcd_checking(a, b):
# Algorithm: consecutive integer checking.
# Requires a > 0 and b > 0 (stricter than the problem demands).
d = min(a, b)
steps = 0
while True:
steps += 1
if a % d == 0 and b % d == 0:
return d, steps
d -= 1
def gcd_euclid(a, b):
# Algorithm: Euclid's method.
# Requires a >= 0, b >= 0, not both zero.
steps = 0
while b != 0:
steps += 1
a, b = b, a % b
return a, steps
for a, b in [(48, 18), (1071, 462), (1_000_000, 999_999)]:
print((a, b), "checking:", gcd_checking(a, b), "euclid:", gcd_euclid(a, b))The output is:
(48, 18) checking: (6, 13) euclid: (6, 3)
(1071, 462) checking: (21, 442) euclid: (21, 3)
(1000000, 999999) checking: (1, 999999) euclid: (1, 2)Both algorithms agree on the answer every time, so both solve the problem on these inputs. They differ a lot in the work they do: for the last pair, checking needs 999,999 iterations and Euclid needs 2. This difference comes from the method. Rewriting gcd_checking in a faster language would not fix it, because no program can be better than the algorithm it implements in this sense.
Algorithms can narrow the problem's preconditions
Look at the comments in the code. The problem allows gcd(0, 5), which equals 5. Consecutive integer checking cannot handle it: d starts at 0, and a % 0 raises ZeroDivisionError. Euclid's algorithm handles it correctly. So the checking method, as written, solves only a restricted version of the problem. That is legitimate, but you have to state it, and anyone using the algorithm has to check that their inputs meet the stricter requirement. When you compare algorithms for one problem, compare the inputs they accept as well as their speed.
One algorithm, many programs
Going the other way, one algorithm can be written as many programs. Here is Euclid's algorithm three times in Python:
import math
def gcd_loop(a, b):
while b != 0:
a, b = b, a % b
return a
def gcd_recursive(a, b):
if b == 0:
return a
return gcd_recursive(b, a % b)
for a, b in [(48, 18), (0, 7), (1071, 462)]:
print(gcd_loop(a, b), gcd_recursive(a, b), math.gcd(a, b))The output is:
6 6 6
7 7 7
21 21 21gcd_loop and gcd_recursive look different: one uses a loop and the other uses recursion. Both carry out the same sequence of states, (48, 18) → (18, 12) → (12, 6) → (6, 0), so they are the same algorithm. math.gcd is a library program written in C. You can't see its steps from Python, and for very large integers CPython may use a faster variant of Euclid's method. Whether two programs are "the same algorithm" depends on whether they go through essentially the same steps, not on whether they produce the same output.
Faults that belong to only one level
Deciding which level a fault belongs to tells you how to fix it.
Program-level faults
A program can fail even though its algorithm is correct. Common causes:
- Typos and off-by-one errors. Writing
a, b = b, b % abreaks a correct algorithm. - Machine limits. In a language with 32-bit integers, an intermediate result can overflow. In Python, deep recursion hits the default recursion limit of about 1000 frames. Euclid's recursion is shallow, so this is not a risk for it, but the same algorithm written recursively for something like a linear scan of a long list would crash.
- Type mismatches.
gcd_loop(48.0, 18)returns6.0, and float inputs with fractional parts give results that have nothing to do with the mathematical GCD. The problem said "integers". The program never checks this.
print(gcd_loop(48.0, 18)) # 6.0 (wrong type, right value)
print(gcd_loop(0, 0)) # 0 (input outside the problem's domain)The second line shows another point. gcd(0, 0) is outside the problem as stated, so no answer is "correct", and the program quietly returns 0. Deciding how a program should respond to invalid input, whether by raising an error or by returning a conventional value, is a program design decision. The algorithm does not make it for you.
Algorithm-level faults
If the method itself is wrong, no amount of careful coding will help. Suppose someone suggests: "replace (a, b) with (b, a − b) until b is 0." With (48, 18) you get (18, 30), then (30, −12), and the numbers never settle. Writing this in another language or adding tests won't save it. The idea itself has to change: the subtraction-based GCD algorithm always subtracts the smaller number from the larger.
Problem-level faults
Sometimes the code and the method are both fine, and the problem statement is wrong. "Return the largest number dividing a and b" leaves out whether negative inputs are allowed and what happens with zero. Two careful programmers can write programs that disagree, and both can claim to be correct. You fix this by tightening the specification, which is the subject of the next chapter.
Why the separation pays off
- Reuse. One correctness argument for Euclid's algorithm covers every faithful program of it, in any language.
- Comparison. You can compare algorithms by step counts without writing or benchmarking any code.
- Portability. Switching languages means rewriting the program. The algorithm and the problem stay the same.
- Communication. A specification tells a teammate what to build without dictating how, and an algorithm description tells them how without tying them to a language.
Exercise
A colleague writes a GCD function in C that returns wrong answers for inputs above about 2.1 billion, while the identical logic in Python works. Is this a problem-, algorithm-, or program-level fault, and why?
Show answer
It is a program-level fault. The same algorithm gives correct results in Python, so the method is sound. The C version almost certainly uses a 32-bit int, and values above 2,147,483,647 overflow. The fix is a wider integer type or a check on the input range.
Exercise
Are gcdloop and gcdrecursive in this chapter two algorithms or two programs of one algorithm? Justify your answer using the states each passes through for (1071, 462).
Show answer
They are two programs of one algorithm. Both go through the states (1071, 462), (462, 147), (147, 21), (21, 0) and return 21. Loop versus recursion is a choice of how to write the program. The step-by-step method is the same.
Exercise
State a precondition under which consecutive integer checking correctly solves the GCD problem, and give one input allowed by the original problem that it fails on.
Show answer
It requires a > 0 and b > 0. It fails on (0, 5): d starts at min(0, 5) = 0, and computing a mod 0 is undefined (Python raises ZeroDivisionError), but the correct answer is 5.
Exercise
Someone proposes the algorithm "replace (a, b) with (b, a - b) until b is 0" for GCD. Trace it from (48, 18) for three steps and say at which level the fault lies.
Show answer
(48, 18) becomes (18, 30), then (30, -12), then (-12, 42). The values never reach b = 0 in a useful way and go negative, so the method does not solve the problem. This is an algorithm-level fault. Writing it as a different program cannot fix it.