Chapter_04a-4up - b and I(k hold before executing c then after executing c I(k 1 holds for all k(3 if the loop terminates after N iterations

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
John Hannan - Comp Sci 360 - Fall 2009 Application m=A; n=B; while not(m=n) { if m>n then m=m-n else n=n-m } // gcd(m,n) = gcd(A,B), m>0,n>0 //A>0,B>0 // gcd(m,n) = gcd(A,B), m>0,n>0 // gcd(m,n) = gcd(A,B), m>0,n>0 // m=n, m=gcd(m,n) = gcd(A,B) John Hannan - Comp Sci 360 - Fall 2009 while (b) { c } // Post-Condition // Pre-Condition John Hannan - Comp Sci 360 - Fall 2009 Loop Invariants A predicate P is a loop invariant if: Given some while loop, (1) P is true before the loop (2) if P is true at the start of loop body then it is true at the end P must be true if (when) loop terminates P !" b should imply post-condition John Hannan - Comp Sci 360 - Fall 2009 Loop Invariant Theorem Let W be a while loop with condition b and body c , and conditions Pre and Post , and predicate I(n) (loop invariant) The loop is correct (with respect to Pre and Post ) if (1) Pre implies I(0) (2) if
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: b and I(k) hold before executing c then after executing c , I(k+1) holds, for all k ! (3) if the loop terminates after N iterations then " b and I(N) imply Post John Hannan - Comp Sci 360 - Fall 2009 Product while !(i=m) { prod = prod + x i = i+1 } // Post: prod=mx // Pre: m ! 0 " i=0 " prod=0 // I(k+1): i=(k+1) " prod=(k+1)x // I(0): i=0 " prod=nx // I(k): i=k " prod=kx John Hannan - Comp Sci 360 - Fall 2009 Quotient-Remainder while (r ! d) { r = r-d q = q+1 } //I(k): r=a-kd " k=q //Post: q>0 " r>0 " a=qd+r " 0 # r<d //Pre: a ! 0 " d>0 " r=a " q=0 //I(0): r=a-nd " n=q //I(k+1): r=a-(k+1)d " k+1=q John Hannan - Comp Sci 360 - Fall 2009 GCD while !(m=n) { if m>n then m=m-n else n=n-m } //I(k): gcd(m,n)=gcd(A,B) //Post: m=gcd(A,B) //Pre: A ! 0 " B ! //I(0): gcd(m,n)=gcd(A,B) //I(k+1): gcd(m,n)=gcd(A,B)...
View Full Document

This note was uploaded on 10/04/2009 for the course CMPSC 360 taught by Professor Haullgren during the Fall '08 term at Pennsylvania State University, University Park.

Page1 / 2

Chapter_04a-4up - b and I(k hold before executing c then after executing c I(k 1 holds for all k(3 if the loop terminates after N iterations

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online