Only if
Conditional steps
Is every step done?
Euclid's algorithm says: "If m < n, reverse the numbers." "If n = 0, report the answer." "Otherwise, reduce."
Is every step carried out every time round?
What this lesson covers
The idea
A step in an algorithm may be conditional, carried out only if a test holds.
Is every step done?
Euclid's algorithm says: "If m < n, reverse the numbers." "If n = 0, report the answer." "Otherwise, reduce."
Is every step carried out every time round?
- No: some steps happen only if a test holds
- Yes, all three steps every time
- Only Step 3 ever happens
Which test held?
Run Euclid's algorithm for gcd(60, 16) (the book's example). For each line, notice which test held: m < n (Step 1), n = 0 (Step 2) or neither (Step 3).
Conditional steps
A step in an algorithm may be conditional: it is carried out only if a test holds.
In the divisor algorithm: add j to the list only if j divides n. In Euclid's algorithm: reverse the numbers only if m < n; report the answer only if n = 0; otherwise reduce. For gcd(60, 16) the reverse step is used 3 times, the reduction 7 times and the report once.
Notes
A conditional step is carried out only if its test holds, such as "add j to the list only if j divides n".
Check yourself
Finding divisors(18), when is j added to the list?
Euclid's algorithm reaches gcd(16, 44). Which step is carried out?
- Only if j divides 18 — correct. Yes. The test decides.
- Every time. Then the list would be [1, 2, …, 18].
- Only if j is even. 3 and 9 are odd divisors of 18.
- Step 1: 16 < 44, so reverse — correct. Yes. The test m < n holds.
- Step 2: report 16. n is 44, not 0.
- Step 3: reduce to gcd(44, −28). We must first make m ≥ n.