# SSE HW 12
# 1
- False, assuming that the program is run in python (does not terminate)
- True, the precondition is not met in the first place so it doesn't matter. This however is a valid Hoare Triple
- True
# 2

# 3
{$K > 0$ and $M > 0$ && $k == K$ && $m == M$}
```
while(k!=m) {
if (k > m) {k = k - m;}
else {m = m - k;}
}
return k;
```
{the returned value is GCD of the inputs}
The invariant would be:
$πΎ β₯ π$ πnd $π β₯ π$ && $πcd(πΎ,π) == πcd(π,π)$
1) [x] pre β inv:
- {$K > 0$ and $M > 0$ && $k == K$ && $m == M$} β $πΎ β₯ π$ πnd $π β₯ π$ && $πcd(πΎ,π) == πcd(π,π)$
- This property is satisfied.
2) [x] { inv && b } program { inv }:
{$πΎ β₯ π$ πnd $π β₯ π$ && $πcd(πΎ,π) == πcd(π,π)$ && $k != m$}
if (k > m) {k = k - m;}
else {m = m - k;}
{$πΎ β₯ π$ πnd $π β₯ π$ && $πcd(πΎ,π) == πcd(π,π)$}
- k > m β (m = oldm - k) || m > k β (k = oldk β m) && oldk != oldm && gcd(K,M) == gcd(k,m) && oldk = K && oldm = M (from the precondition)
- k > m β gcd(K, M) == gcd(oldk β m, m) || m > k β gcd(K,M) == gcd(k, oldmβ k)
- k > m β gcd(K, M) == gcd(K β m, m) || m > k β gcd(K,M) == gcd(k, M β k)
- { K β₯ k and M β₯ m && gcd(K,M) == gcd(k,m) }
> This property is satisfied as it follows Euclideanβs principle that gcd(A,B) = gcd(A-B, B).
3) [x] inv && !b β post:
{$πΎ β₯ π$ πnd $π β₯ π$ && $πcd(πΎ,π) == πcd(π,π)$ && $k == m$}
- K β₯ k and M β₯ k && gcd(K,M) == gcd(k,k)
- K β₯ k and M β₯ k && gcd(K,M) == k
- {the returned value is GCD of the inputs}
> The invariant and !b are strong enough to imply the postcondition.
Thus, as all three rules are satisfied, the program has partial correctness.
# 4
The program will halt when k == m.
We can use f(k,m) = k + m as a ranking function to test whether the program terminates.
{ $k + m = V$ }

{ $k + m = Vβ$ && $Vβ < V$ }
The Hoare triple is true after iterations of the while loop as the rank decreases after each loop.
- When k is greater than m, the value of k decreases by m. $f(k,m) = k$
- When m is greater than k, the value of m decreases by k. $f(k,m) = m$
Thus eventually, k and m will converge to the same value, and the program has total correctness.
# 5

The program has 2 loops (`while (x>=0)` and `while (y <x)` ) as such 2 checks are needed to check for termination
### `while (y <x)` loop
Assuming that x is β₯ 0, using the ranking function $f(y)=-y$
{ x-y = V }

{ x-y = Vβ && Vβ < V }
> This loop reaches termination
### `while (x>=0)` loop
Assuming no integer overflow and x > 0, using the ranking function $f(x)=x$
{x = V}


{ x = Vβ && Vβ < V }
> This loop reaches termination
As both loops reach termination, ther program will always reach termination and has total correctness.