Salta al contenuto
Note per Studenti Correctness and Loop Invariants Report

Correctness and Loop Invariants

In questa pagina 3

Correctness analysis has two parts:

  1. Termination: all loops (including GOTO) and recursive calls eventually end.
  2. 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

  1. By example: shows a property can hold with a specific instance. Used for a lower bound v.1: to prove tA(n)∈Ω(n2)t_A(n) \in \Omega(n^2) it suffices to show that for large nn some instance needs ≥cn2\ge c n^2 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 →).
  2. By counterexample: disproves a universal claim with one violating instance. "2i−12^i - 1 is prime for all i≥1i \ge 1" is false: i=4i = 4 gives 24−1=152^4 - 1 = 15.
  3. By contradiction (absurdity): assume the opposite and reach a contradiction. If a⋅ba \cdot b is odd (with a,b≥1a, b \ge 1) then both are odd: if, say, aa were even, a=2ca = 2c, then ab=2cbab = 2cb would be even, contradiction.
  4. By induction (below).

Induction

To prove Q(n)Q(n) for all n≥n0n \ge n_0 (n0=1n_0 = 1 in the textbook):

  1. Choose an integer k≥0k \ge 0.
  2. Base cases: prove directly Q(n0),Q(n0+1),…,Q(n0+k)Q(n_0), Q(n_0+1), \dots, Q(n_0+k).
  3. Inductive step: fix an arbitrary n≥n0+kn \ge n_0 + k, assume Q(m)Q(m) for all mm with n0≤m≤nn_0 \le m \le n (inductive hypothesis) and prove Q(n+1)Q(n+1).

Remarks: the proof must hold for any n≥n0+kn \ge n_0 + k; usually k=0k = 0. Hint for choosing kk: if Q(n+1)Q(n+1) needs only Q(n)Q(n), take k=0k = 0; if it also needs Q(n−1),Q(n−2),…Q(n-1), Q(n-2), \dots, then k>0k > 0. 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 Q(n+1)Q(n+1) to the hypothesis so that it can be used.

Example: Gauss' formula

Claim: Q(n): ∑j=0nj=n(n+1)2Q(n):\ \sum_{j=0}^{n} j = \dfrac{n(n+1)}{2} for all n≥0n \ge 0 (so the sum is Θ(n2)\Theta(n^2)). Take k=0k = 0, n0=0n_0 = 0.

  • Base case n=0n = 0: ∑j=00j=0=0⋅12\sum_{j=0}^{0} j = 0 = \dfrac{0 \cdot 1}{2}. OK.
  • Inductive step: fix n≥0n \ge 0, assume Q(m)Q(m) for 0≤m≤n0 \le m \le n, prove Q(n+1)Q(n+1). Take out the last term, apply the hypothesis for m=nm = n, do the algebra:

∑j=0n+1j=∑j=0nj+(n+1)=n(n+1)2+(n+1)=(n+1)(n+2)2\sum_{j=0}^{n+1} j = \sum_{j=0}^{n} j + (n+1) = \frac{n(n+1)}{2} + (n+1) = \frac{(n+1)(n+2)}{2}

Example: Fibonacci

F0=0F_0 = 0, F1=1F_1 = 1, Fn+1=Fn+Fn−1F_{n+1} = F_n + F_{n-1} for n≥1n \ge 1. (It models rabbit pairs: no deaths, a pair is fertile after two months and then produces one pair per month; in month n+1n+1 there are all pairs of month nn plus one new pair for each pair of month n−1n-1.)

Claim: Fn=15(Φn−Φ^n)F_n = \dfrac{1}{\sqrt 5}\left(\Phi^n - \hat\Phi^n\right) for n≥0n \ge 0, with Φ=1+52\Phi = \dfrac{1+\sqrt5}{2} (golden ratio), Φ^=1−52\hat\Phi = \dfrac{1-\sqrt5}{2}.

Hints: 3+52=Φ2\dfrac{3+\sqrt5}{2} = \Phi^2 and 3−52=Φ^2\dfrac{3-\sqrt5}{2} = \hat\Phi^2; use k=1k = 1 (two base cases), n0=0n_0 = 0.

  • Base cases: n=0n = 0: 15(1−1)=0=F0\frac{1}{\sqrt5}(1 - 1) = 0 = F_0. n=1n = 1: 15(Φ−Φ^)=15⋅252=1=F1\frac{1}{\sqrt5}(\Phi - \hat\Phi) = \frac{1}{\sqrt5} \cdot \frac{2\sqrt5}{2} = 1 = F_1. OK.
  • Inductive step: fix n≥1n \ge 1, assume the claim for 0≤m≤n0 \le m \le n:

Fn+1=Fn+Fn−1=15[(Φn+Φn−1)−(Φ^n+Φ^n−1)]F_{n+1} = F_n + F_{n-1} = \frac{1}{\sqrt5}\left[(\Phi^n + \Phi^{n-1}) - (\hat\Phi^n + \hat\Phi^{n-1})\right]

with Φn+Φn−1=Φn−1(Φ+1)=Φn−1 3+52=Φn−1Φ2=Φn+1\Phi^n + \Phi^{n-1} = \Phi^{n-1}(\Phi + 1) = \Phi^{n-1}\,\frac{3+\sqrt5}{2} = \Phi^{n-1}\Phi^2 = \Phi^{n+1}, and likewise Φ^n+Φ^n−1=Φ^n+1\hat\Phi^n + \hat\Phi^{n-1} = \hat\Phi^{n+1}. Hence Fn+1=15(Φn+1−Φ^n+1)F_{n+1} = \frac{1}{\sqrt5}(\Phi^{n+1} - \hat\Phi^{n+1}).

A fallacious induction

Wrong claim: Fn=0F_n = 0 for all n≥0n \ge 0. "Proof": k=0k = 0, base F0=0F_0 = 0; step: Fn+1=Fn+Fn−1=0+0=0F_{n+1} = F_n + F_{n-1} = 0 + 0 = 0.

Where is the mistake? Choosing k=0k=0 is formally allowed, but the step is stated for all n≥0n \ge 0, and for n=0n = 0 it reads F1=F0+F−1F_1 = F_0 + F_{-1}, where F−1F_{-1} is undefined. The recurrence needs two base cases (F0F_0 and F1F_1), and then F1=1≠0F_1 = 1 \ne 0 refutes the claim. Lesson: the inductive step must be valid for every n≥n0+kn \ge n_0 + k.

Loop analysis and invariants

A loop executes ≥0\ge 0 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 SendS_{end}) holds, starting from the state SinitS_{init} 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 ii, but what holds after it, as if the algorithm were stopped just before iteration i+1i+1.

Proof scheme:

  1. Initialisation: the invariant holds at the beginning of the loop (before the first iteration), as a consequence of SinitS_{init}.
  2. 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: Inv(i−1)⇒Inv(i)\text{Inv}(i-1) \Rightarrow \text{Inv}(i).
  3. Termination: if it holds at the end of the last iteration, it implies SendS_{end}, 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.

  • SinitS_{init}: currMax = A[0].
  • SendS_{end}: currMax = max{A[0], ..., A[n-1]}.
  • Invariant: Inv(i)\text{Inv}(i): currMax = max{A[0], A[1], ..., A[i]} at the end of iteration ii. Even if the loop starts at i=1i = 1, i=0i = 0 represents SinitS_{init}.

Proof:

  1. Initialisation: Sinit⇒Inv(0)S_{init} \Rightarrow \text{Inv}(0): currMax = A[0] = max{A[0]}. True.
  2. Maintenance: hypothesis Inv(i−1)\text{Inv}(i-1): currMax =max⁡{A[0],…,A[i−1]}= \max\{A[0], \dots, A[i-1]\}. After iteration ii: currMax =max⁡{currMaxi−1,A[i]}=max⁡{A[0],…,A[i−1],A[i]}= \max\{\text{currMax}_{i-1}, A[i]\} = \max\{A[0], \dots, A[i-1], A[i]\}. True.
  3. Conclusion: i=n−1i = n-1: Inv(n−1)\text{Inv}(n-1) is exactly SendS_{end} (Send≡Inv(n−1)S_{end} \equiv \text{Inv}(n-1)).

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 xx 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 A[0..i−1]A[0..i-1] has been checked and contains no xx (whether A[i]=xA[i] = x is not yet known).

  • SinitS_{init}: i=0i = 0.
  • SendS_{end}: if i<ni < n then x=A[i]x = A[i]; if i=ni = n then x∉Ax \notin A.
  • Invariant Inv(i)\text{Inv}(i): x∉{A[0],…,A[i−1]}x \notin \{A[0], \dots, A[i-1]\}.

Proof:

  1. Initialisation: i=0i = 0, the range 0≤j<00 \le j < 0 is empty and cannot contain xx: the invariant holds by vacuity.
  2. Maintenance: Inv(i)\text{Inv}(i) holds and we are about to check A[i]A[i]. Two cases:
    • match (x=A[i]x = A[i]): the algorithm returns ii without incrementing; there is no next iteration, so nothing more to show;
    • no match (x≠A[i]x \ne A[i]): ii is incremented, and now x∉{A[0],…,A[i]}x \notin \{A[0], \dots, A[i]\}, i.e. Inv(i+1)\text{Inv}(i+1) is true.
  3. Conclusion: let kk be the last value of ii. If k<nk < n the loop exited because x=A[k]x = A[k], and returning kk is correct. Otherwise k=nk = n and the invariant gives x∉Ax \notin A, so −1-1 is correct. In both cases SendS_{end} 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 ii:

  • max = maximum length of a contiguous segment of 1s in S[1..i]S[1..i];
  • curr = length of the segment of 1s ending at S[i]S[i] (the suffix of 1s of S[1..i]S[1..i]).

(Proof left as exercise on the slides.)

Complexity versus practice

Maximum executable size

Efficient = complexity at most polynomial (polynomial in nn, logarithmic, or any function not growing faster than a polynomial). Inefficient = exponential. Why exponential is so bad:

Measure tA(n)t_A(n) directly as time with 11 operation =1= 1 ns, and fix a time budget τ\tau. The maximum executable size nτn_\tau solves tA(nτ)=τt_A(n_\tau) = \tau:

tA(n)t_A(n) nτn_\tau
log⁡2n\log_2 n 2τ2^\tau
nn τ\tau
n2n^2 τ\sqrt{\tau}
2n2^n log⁡2τ\log_2 \tau
  • 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. n100n^{100}) 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: N=p×qN = p \times q with large primes; the public key is (N,e)(N, e), the private key (N,d)(N, d), and computing dd requires pp and qq. Trivial factorisation of an nn-bit NN tries primes up to N\sqrt N, about 2n/22^{n/2} operations: exponential in the size nn. For RSA-1024: 2512≥101542^{512} \ge 10^{154} operations, about 1013610^{136} seconds on a computer doing 101810^{18} operations per second, over 1012810^{128} 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 tA(n)∈o(tB(n))t_A(n) \in o(t_B(n)) then AA is asymptotically more efficient than BB, but n0n_0 could be very big. Two cautions:

  1. The worst case may be pathological or rare. Example: Quicksort has a quadratic worst case but runs in O(nlog⁡n)O(n \log n) on average. Remedies: restrict the instance domain to exclude unrealistic cases, or do an average-case/probabilistic analysis.
  2. Neglected constants can matter in practice.
    • tA(n)=10100n∈Θ(n)t_A(n) = 10^{100} n \in \Theta(n) and tB(n)=n2t_B(n) = n^2: asymptotically AA wins, but tA(n)<tB(n)t_A(n) < t_B(n) only for n>10100n > 10^{100} (far more than the atoms in the universe).
    • tA(n)=400log⁡2nt_A(n) = 400 \log_2 n and tB(n)=(log⁡2n)2t_B(n) = (\log_2 n)^2: AA wins only when log⁡2n>400\log_2 n > 400, i.e. n>2400>10100n > 2^{400} > 10^{100}.
    • 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 (24−1=152^4 - 1 = 15 not prime), contradiction (abab odd implies aa, bb odd), induction.
  • Induction for Q(n)Q(n), n≥n0n \ge n_0: choose kk; base cases Q(n0),…,Q(n0+k)Q(n_0), \dots, Q(n_0+k); step: fix n≥n0+kn \ge n_0 + k, assume Q(m)Q(m) for n0≤m≤nn_0 \le m \le n, prove Q(n+1)Q(n+1). k=0k=0 if the step needs only Q(n)Q(n); k>0k>0 if it needs earlier values.
  • Gauss: ∑j=0nj=n(n+1)/2\sum_{j=0}^{n} j = n(n+1)/2. Base n=0n = 0; step ∑j=0n+1j=∑j=0nj+(n+1)=(n+1)(n+2)/2\sum_{j=0}^{n+1} j = \sum_{j=0}^{n} j + (n+1) = (n+1)(n+2)/2 (isolate the last term to use the hypothesis).
  • Fibonacci: Fn=(Φn−Φ^n)/5F_n = (\Phi^n - \hat\Phi^n)/\sqrt5, Φ=(1+5)/2\Phi = (1+\sqrt5)/2, Φ^=(1−5)/2\hat\Phi = (1-\sqrt5)/2; two base cases (k=1k=1), using Φ2=Φ+1\Phi^2 = \Phi + 1 (and same for Φ^\hat\Phi).
  • Fallacious induction (Fn=0F_n = 0): the step at n=0n=0 needs F−1F_{-1}, undefined; two base cases are required.
  • Invariant (property at the end of a generic iteration), proof in 3 steps:
    1. holds at the start (from SinitS_{init});
    2. Inv(i−1)⇒Inv(i)\text{Inv}(i-1) \Rightarrow \text{Inv}(i) (induction);
    3. at the last iteration Inv\text{Inv} implies SendS_{end}.
  • arrayMax: Inv(i)\text{Inv}(i): currMax =max⁡{A[0..i]}= \max\{A[0..i]\}; Inv(0)\text{Inv}(0) from currMax =A[0]= A[0]; step max⁡{currMax,A[i]}\max\{\text{currMax}, A[i]\}; Inv(n−1)≡Send\text{Inv}(n-1) \equiv S_{end}.
  • arrayFind: Inv(i)\text{Inv}(i): x∉A[0..i−1]x \notin A[0..i-1], anchored before the test; true by vacuity at i=0i=0; step: match returns ii, no match gives Inv(i+1)\text{Inv}(i+1); end: k<nk<n gives x=A[k]x=A[k], k=nk=n gives x∉Ax \notin A.
  • maxSegment1 invariant: max = best segment in S[1..i]S[1..i], curr = suffix of 1s ending at S[i]S[i].
  • Executable size nτn_\tau from tA(nτ)=τt_A(n_\tau) = \tau: log⁡n→2τ\log n \to 2^\tau, n→τn \to \tau, n2→τn^2 \to \sqrt\tau, 2n→log⁡2τ2^n \to \log_2 \tau. Exponential: size grows only logarithmically with time, so inefficient.
  • Caveats: worst case may be rare (Quicksort); constants may dominate (10100n10^{100}n vs n2n^2; 400log⁡n400 \log n vs log⁡2n\log^2 n).
  • Typical mistakes: invariant describing iteration ii instead of the state after it; forgetting the early-exit case; too few base cases; hiding that n0n_0 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 →.

Teoria collegata