Correctness and Loop Invariants
In questa pagina 3
Correctness analysis has two parts:
- Termination: all loops (including
GOTO) and recursive calls eventually end. - Solution of the problem: the algorithm produces what Computational Problems, Algorithms and Models of ComputationA computational problem is a relation between instances and solutions, an algorithm is a finite procedure that computes one valid solution for each instance in a model of computation (RAM), and a data structure organises the data the algorithm works on.Computational Problems, Algorithms and Models of Computation → requires, not just stops.
General approach for point 2: identify the initial state and the final state the algorithm must reach; split the algorithm into segments and define for each one the state at its end (a checkpoint); show that starting from the initial state each checkpoint is reached in turn, and that the last one coincides with (or implies) the desired final state. The most notable segments are loops (for, while, repeat-until).
Proof techniques
- By example: shows a property can hold with a specific instance. Used for a lower bound v.1: to prove it suffices to show that for large some instance needs operations (see Analysis of Algorithms and Asymptotic NotationThe worst-case time complexity t_A(n) counts elementary RAM steps on the hardest instance of size n; since it is hard to compute exactly, it is bounded asymptotically with O, Omega, Theta and o, ignoring constants and lower-order terms.Analysis of Algorithms and Asymptotic Notation →).
- By counterexample: disproves a universal claim with one violating instance. " is prime for all " is false: gives .
- By contradiction (absurdity): assume the opposite and reach a contradiction. If is odd (with ) then both are odd: if, say, were even, , then would be even, contradiction.
- By induction (below).
Induction
To prove for all ( in the textbook):
- Choose an integer .
- Base cases: prove directly .
- Inductive step: fix an arbitrary , assume for all with (inductive hypothesis) and prove .
Remarks: the proof must hold for any ; usually . Hint for choosing : if needs only , take ; if it also needs , then . Analogy: reach the first rung (base case), show you can go from one rung to the next (inductive step), so you can climb as high as you want.
Two delicate points: choosing the base cases, and reconnecting to the hypothesis so that it can be used.
Example: Gauss' formula
Claim: for all (so the sum is ). Take , .
- Base case : . OK.
- Inductive step: fix , assume for , prove . Take out the last term, apply the hypothesis for , do the algebra:
Example: Fibonacci
, , for . (It models rabbit pairs: no deaths, a pair is fertile after two months and then produces one pair per month; in month there are all pairs of month plus one new pair for each pair of month .)
Claim: for , with (golden ratio), .
Hints: and ; use (two base cases), .
- Base cases: : . : . OK.
- Inductive step: fix , assume the claim for :
with , and likewise . Hence .
A fallacious induction
Wrong claim: for all . "Proof": , base ; step: .
Where is the mistake? Choosing is formally allowed, but the step is stated for all , and for it reads , where is undefined. The recurrence needs two base cases ( and ), and then refutes the claim. Lesson: the inductive step must be valid for every .
Loop analysis and invariants
A loop executes iterations of its body. Loops are among the hardest segments to analyse because they implicitly define many operations, but together with recursion they are the essential tools to build meaningful algorithms.
To prove that when a loop ends a property (the state ) holds, starting from the state at the beginning, we use an invariant.
Definition. An invariant of a loop is a property, expressed through the variables used in the loop, that describes the state at the end of a generic iteration. It carries forward, iteration after iteration, the knowledge acquired so far. It does not describe what happens during iteration , but what holds after it, as if the algorithm were stopped just before iteration .
Proof scheme:
- Initialisation: the invariant holds at the beginning of the loop (before the first iteration), as a consequence of .
- Maintenance: if it holds before an arbitrary iteration (= at the end of the previous one), it holds at the end of that iteration. Usually proved by induction: .
- Termination: if it holds at the end of the last iteration, it implies , i.e. the loop is correct.
Example: arrayMax
Algorithm in PseudocodePseudocode is the rigorous, free-form way algorithms are specified in this course: a header with name, input and output, then a body that mixes programming constructs with natural language only where it helps.Pseudocode →. The idea: currMax always holds the maximum of the elements met so far.
- :
currMax = A[0]. - :
currMax = max{A[0], ..., A[n-1]}. - Invariant: :
currMax = max{A[0], A[1], ..., A[i]}at the end of iteration . Even if the loop starts at , represents .
Proof:
- Initialisation: :
currMax = A[0] = max{A[0]}. True. - Maintenance: hypothesis :
currMax. After iteration :currMax. True. - Conclusion: : is exactly ().
Example: arrayFind
Algorithm in PseudocodePseudocode is the rigorous, free-form way algorithms are specified in this course: a header with name, input and output, then a body that mixes programming constructs with natural language only where it helps.Pseudocode →. Two possible terminations: early exit because was found, or natural end of the loop. Both must be handled.
The invariant is anchored at the beginning of each iteration, just before testing x = A[i]: the prefix has been checked and contains no (whether is not yet known).
- : .
- : if then ; if then .
- Invariant : .
Proof:
- Initialisation: , the range is empty and cannot contain : the invariant holds by vacuity.
- Maintenance: holds and we are about to check . Two cases:
- match (): the algorithm returns without incrementing; there is no next iteration, so nothing more to show;
- no match (): is incremented, and now , i.e. is true.
- Conclusion: let be the last value of . If the loop exited because , and returning is correct. Otherwise and the invariant gives , so is correct. In both cases holds.
Exercise: maxSegment1
For PseudocodePseudocode is the rigorous, free-form way algorithms are specified in this course: a header with name, input and output, then a body that mixes programming constructs with natural language only where it helps.Pseudocode →'s maxSegment1, the invariant has two complementary properties. At the end of iteration :
max= maximum length of a contiguous segment of 1s in ;curr= length of the segment of 1s ending at (the suffix of 1s of ).
(Proof left as exercise on the slides.)
Complexity versus practice
Maximum executable size
Efficient = complexity at most polynomial (polynomial in , logarithmic, or any function not growing faster than a polynomial). Inefficient = exponential. Why exponential is so bad:
Measure directly as time with operation ns, and fix a time budget . The maximum executable size solves :
- Polynomial (or better): scalable; the larger the exponent, the faster the feasible size drops.
- Exponential: impractical. The largest solvable size grows only logarithmically with the time budget, so even massive increases in resources give minimal gains (going from 1 second to 1 hour, a factor 3600, barely changes it).
- A very high-degree polynomial (e.g. ) can also be impractical; up to cubic we still handle reasonably large instances.
Application (bonus slides): RSA. Public-key cryptography relies on problems easy in one direction and hard to invert. RSA: with large primes; the public key is , the private key , and computing requires and . Trivial factorisation of an -bit tries primes up to , about operations: exponential in the size . For RSA-1024: operations, about seconds on a computer doing operations per second, over years. Better factorisation algorithms exist but are still exponential; a polynomial-time method cannot be ruled out, and would break many security guarantees.
Caveats on asymptotic worst-case analysis
If then is asymptotically more efficient than , but could be very big. Two cautions:
- The worst case may be pathological or rare. Example: Quicksort has a quadratic worst case but runs in on average. Remedies: restrict the instance domain to exclude unrealistic cases, or do an average-case/probabilistic analysis.
- Neglected constants can matter in practice.
- and : asymptotically wins, but only for (far more than the atoms in the universe).
- and : wins only when , i.e. .
- Always estimate and report constants when they can be very large.
Versione ripasso
- Correctness = termination (all loops and recursive calls end) + the algorithm solves the problem. Method: initial state, checkpoints after each segment, last checkpoint implies the final state. Loops are the notable segments.
- Proof techniques: example (e.g. lower bound v.1), counterexample ( not prime), contradiction ( odd implies , odd), induction.
- Induction for , : choose ; base cases ; step: fix , assume for , prove . if the step needs only ; if it needs earlier values.
- Gauss: . Base ; step (isolate the last term to use the hypothesis).
- Fibonacci: , , ; two base cases (), using (and same for ).
- Fallacious induction (): the step at needs , undefined; two base cases are required.
- Invariant (property at the end of a generic iteration), proof in 3 steps:
- holds at the start (from );
- (induction);
- at the last iteration implies .
- arrayMax: : currMax ; from currMax ; step ; .
- arrayFind: : , anchored before the test; true by vacuity at ; step: match returns , no match gives ; end: gives , gives .
- maxSegment1 invariant: max = best segment in , curr = suffix of 1s ending at .
- Executable size from : , , , . Exponential: size grows only logarithmically with time, so inefficient.
- Caveats: worst case may be rare (Quicksort); constants may dominate ( vs ; vs ).
- Typical mistakes: invariant describing iteration instead of the state after it; forgetting the early-exit case; too few base cases; hiding that or the constants are huge.
- See Analysis of Algorithms and Asymptotic NotationThe worst-case time complexity t_A(n) counts elementary RAM steps on the hardest instance of size n; since it is hard to compute exactly, it is bounded asymptotically with O, Omega, Theta and o, ignoring constants and lower-order terms.Analysis of Algorithms and Asymptotic Notation → and Recursion and its AnalysisA recursive algorithm solves an instance by calling itself on smaller instances until a base case; its cost is the sum of node costs in the recursion tree and its correctness is proved by induction.Recursion and its Analysis →.