
1
Discrete Mathematical Structures
CS 2233 Lecture Nineteen
Prof. William Winsborough
April 14, 2009
14 April 2009 Winsborough CS 2233 Lecture 19 2
Business
• Recall: Homework 9 due Thursday 4/16
– 4.3: 4, 6, 12, 22
• Read
– 4.4, 7.3
14 April 2009 Winsborough CS 2233 Lecture 19 3
Recursive Programming
• Can write the same programs using
iteration
– Often algorithms are easier to design and
understand using a recursive formulation
• Classic programming paradigm:
Divide and Conquer
– Decompose problem into subproblems
– Solve each subproblem
– Combine the results
14 April 2009 Winsborough CS 2233 Lecture 19 4
A Simple Iterative Program
• Consider the following algorithm:
– power(n) takes a non-negative integer and returns 3
n
power(n)
power = 1
for i = 1 to n
power = power * 3
return power
• Cost (time complexity): O(n)
14 April 2009 Winsborough CS 2233 Lecture 19 5
Example Recursive Program
• Consider the following algorithm:
– power(n) takes a non-negative integer and r eturns 3
n
power(n)
if (n ≤0) return 1
return 3*power(n-1)
• Cost (time complexity): T(n)
– Defined by the following recurrence (basica lly a recursive
definition):
T(0) = 1
T(n) = T(n-1) + 3 (depending on which ops you count)
• Closed form solution: T(n) = 3n+1 = O(n)
14 April 2009 Winsborough CS 2233 Lecture 19 6
Improving the Example Program
• A faster version of power(n):
power(n)
if (n ≤0) return 1
temp = ⌊n/2⌋
if 2*temp = n return (power(temp))
2
return 3*(power(temp))
2
• Cost:
T(0) = 1
T(n) = T(
⌊n/2⌋
) + d, in which d is a small constant
• Claim: closed form solution is T(n) = O(lg n)