Download Formal Semantics Problem Set 4 Solutions: GCD Algorithm and Loop Invariants and more Assignments Computer Science in PDF only on Docsity!
CPSC 430 : Formal Semantics Paul Hudak Date: October 18, 2007
Problem Set 4 Solution
Problem 3.
- y = x^2
- y = z ∧ x = w
- (a ≥ b ∧ y = x × b) ∨ (a < b ∧ y = x × a)
- true
- false
Problem 3.
Consider the program:
newvar x:=a in newvar y:=b in (while y > 0 do newvar t:=x rem y in (x:=y; y:=t); c:=x)
The proof of total correctness is:
- (a ≥ 0 ) ∧ (b ≥ 0 ) ⇒ (a ≥ 0 ) ∧ (b ≥ 0 ) ∧ (gcd(a, b) = gcd(a, b))
- [(a ≥ 0 ) ∧ (b ≥ 0 )] x := a; y := b [(x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b))] (RAS 2 , 1)
- (x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b)) ∧ (y > 0 ) ∧ (y = m) ⇒ (y ≥ 0 ) ∧ (x rem y ≥ 0 ) ∧ (gcd(y, x rem y) = gcd(a, b)) ∧ (x rem y < m)
- [(x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b)) ∧ (y > 0 ) ∧ (y = m)] t := x rem y; x := y; y := t [(x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b)) ∧ (y < m)] (RAS 3 , 3)
- [(x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b)) ∧ (y > 0 ) ∧ (y = m)] newvar t:=x rem y in (x:=y; y:=t) [(x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b)) ∧ (y < m)] (DC, 4)
- (x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b)) ∧ (y > 0 ) ⇒ (y ≥ 0 )
- [(x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b))] while y>0 do newvar t:=x rem y in (x:=y; y:=t) [(x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b)) ∧ ¬(y > 0 )] (W HT, 5, 6)
- (x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b)) ∧ ¬(y > 0 ) ⇒ (x = gcd(a, b))
- [(x ≥ 0 ) ∧ (y ≥ 0 ) ∧ (gcd(x, y) = gcd(a, b))] while y > 0 do newvar t:=x rem y in (x:=y; y:=t) [x = gcd(a, b)] (WC, 7, 8)
- [x = gcd(a, b)] c:=x [c = gcd(a, b)] (AS)
- [(a ≥ 0 ) ∧ (b ≥ 0 )] x:=a; y:=b; while y > 0 do newvar t:=x rem y in (x:=y; y:=t); c:=x [c = gcd(a, b)] (MSQ 3 , 2, 9, 10)
- [(a ≥ 0 ) ∧ (b ≥ 0 )] x:=a; newvar y:=b; in (while y > 0 do newvar t:=x rem y in (x:=y; y:=t); c:=x) [c = gcd(a, b)] (DC, 11)
- [(a ≥ 0 ) ∧ (b ≥ 0 )] newvar x:=a in newvar y:=b; in (while y > 0 do newvar t:=x rem y in (x:=y; y:=t); c:=x) [c = gcd(a, b)] (DC, 12)
Problem 3.
- [x > 0 ∧ y = y 0 + (x 0 − x) × (x 0 + x − 1 ) ÷ 2 ∧ x = cnt] (x := x - 1; y := y + x) [x ≥ 0 ∧ y = y 0 + (x 0 − x) × (x 0 + x − 1 ) ÷ 2 ∧ x + 1 = cnt] (RAS 2 )
- x ≥ 0 ∧ y = y 0 + (x 0 − x) × (x 0 + x − 1 ) ÷ 2 ∧ x 6 = 0 ∧ x = cnt ⇒ x > 0 ∧ y = y 0 + (x 0 − x) × (x 0 + x − 1 ) ÷ 2 ∧ x = cnt
- x ≥ 0 ∧ y = y 0 + (x 0 − x) × (x 0 + x − 1 ) ÷ 2 ∧ x + 1 = cnt ⇒ x ≥ 0 ∧ y = y 0 + (x 0 − x) × (x 0 + x − 1 ) ÷ 2 ∧ x < cnt]