COL100 �Introduction to Computer Science
Lecture 24 – Correctness and Termination
April, 2024
Semester II
2024-2025
Vireshwar Kumar, Aaditeshwar Seth
CSE@IITD
Agenda
2
Disclaimer: The contents of these slides are taken from various publicly available resources such as books, talks and lectures. They are being used for the purpose of classroom teaching and academic dissemination only. The sources are acknowledged wherever possible.
Algorithm
3
Recall Long Multiplication Algorithm
4
9854
67
9854
67
XXXX
XXXX0
Can you prove its correctness?
Correctness Proof
5
9854
67
XXXX
XXXX0
Algorithm Validity
6
Algorithm Validity
7
Algorithm Validity
8
Algorithm Validity
9
Algorithm Validity
10
Another Example
11
Algorithms
12
Example: GCD
13
Proving Correctness
14
Proving Correctness
15
Proving Correctness
16
Proving Correctness
17
Both the cases are proved.
Hence, the mathematical definition is a correct algorithm
Proving Termination
18
Example: Fibonacci Sequence
19
More Efficient Fibonacci Computation
20
Comparison
21
def fib(n):
global ops
global calls
calls += 1
if n <= 1:
return n
else:
ops += 3
return fib(n - 1) + fib(n - 2)
def fiba(n, a, b):
global ops
global calls
calls += 1
if n == 0:
return a
elif n == 1:
return b
else:
ops += 2
return fiba(n - 1, b, a + b)
for n in range(4, 25):
calls = 0
ops = 0
print(fib(n), calls, ops)
calls = 0
ops = 0
print(fiba(n, 0, 1), calls, ops)
print()
Comparison
22
def fib_avoid_duplication(n):
global fib_vals
global ops
global calls
calls += 1
if n <= 1:
return n
else:
if (n - 1) not in fib_vals.keys():
fib_vals[n - 1] = fib_avoid_duplication(n - 1)
if (n - 2) not in fib_vals.keys():
fib_vals[n - 2] = fib_avoid_duplication(n - 2)
ops += 3
fib_vals[n] = fib_vals[n - 1] + fib_vals[n - 2]
return fib_vals[n]
for n in range(4, 25):
calls = 0
ops = 0
fib_vals = {}
print(fib_avoid_duplication(n), calls, ops)
print()
Proving Correctness of Efficient Version
23
Proving Correctness of Efficient Version
24
Proof Attempt by Induction
25
Intuitive Understanding
26
Intuitive Understanding
27
Claim
28
Proving the Claim by Induction
29
Using Induction Hypothesis
Rearranging terms
Take Home Message
30
Take Home Message
31