Professional Documents
Culture Documents
• Loop Invariants
• Induction
The Coffee Can Problem
Given a coffee can that contains some white beans and
some black beans, do:
n k (f(n) c g(n)).
f(n) O(g(n)).
O
n3 + 2n + 3 O(n3), since:
•k = 2,
•c = 2, and
•For all n 2, n3 + 2n + 3 2n3.
O
P(s: string) =
count = 0.
For i = 1 to length(s) do:
If the ith character of s is a, count = count + 1.
Print (count).
Let n = length(s).
Let n = length(v).
2 + 4n O(n).
2 + 4n O(n2).
2 + 4n O(2n),
Define :
So:
2 + 4n (n), but
2 + 4n (n2) because n2 O(n).
Exercises
• Prove each of the following:
((A B) → C) (A B C).
• List the elements of each of the following sets:
a) P({apple, pear, banana}).
b) P({a, b}) - P({a, c}).
c) {x ℕ: (x 7 x 7}.
d) {x ℕ: y ℕ (z ℕ ((x = y + z) (y < 5)
(z < 4)))}.
Exercises
• Prove that the following program computes the function
double(s) where, for any string s, double(s) = True if s
contains at least one pair of adjacent characters that are
identical and False otherwise. Clearly state the loop
invariant that you are using.
double(s: string) =
found = False.
for i = 1 to length(s) - 1 do
if s[i] = s[i + 1] then found = True.
return(found).