Recursive Algorithm Analysis
- L’Hopital’s rule
If limn→∞f(n)=limn→∞g(n)=∞ and the derivatives f′ and g′ exist, then
n→∞limg(n)f(n)=n→∞limg′(n)f′(n)
- Stirling’s formula
n!≈2πn(en)n
where e is the base of natural logarithm, e≈2.718. π≈3.1415
A recurrence relation is an equation that recursively defines a sequence of values given some initial terms.
Reviewish Examples:
-
Fibonacci Sequence
(0,1,1,2,3,5,8,...)
- an=an−1+an−2 for n≥2
a0=0
a1=1
-
Geometric Progression
(3,6,12,24,48,...) Find a recurrence relation!
-
an=2an−1 for n≥1
a0=3
-
But how do we find out what a667?
- We want a formula to solve this
- an=?
- an=3(2n)
-
if an=dan−1 where a0=k then an=k(dn)
Geometric Progressions: suppose some relation an=dan−1 and a0=k for some constant d and n≥1 then an=k(dn) for n≥0
-
Another sequence
(0,2,6,12,20,30,42,...)
-
(a1−a0=2)
(a2−a1=4)
(a3−a2=6)
...
+(an−an−1=2n)
--
an−a0=2+4+6+8+...+2n
=2(1+2+...+n)
=2∑i=1ni
=2(2n(n+1))
=n(n+1)
So, an−a0=n(n+1)
an=n(n+1)
-
Check if it works!
- a6=6(6+1)=42
-
If an−an−1=k and a0=c for n≥1 then an=c+∑i=1nk
- Applied to example: an=0+∑i=1n2n=2∑i=1nn=22(n)(n+1)=n(n+1)
Example: Find n!
NonRecursiveFindFactorial(n):
result = 1
for i <- 1 ... n
result = result * i
return result
Recurrence: f(n) = n * f(n - 1)
RecursiveRecursiveFindFactorial(n):
if n = 0
return 1
else
return n * RecursiveFindFactorial(n - 1)
Analysis of Recursive Algorithms (3 methods):
- Iteration Method
- Expand (iterate) the recurrence and express it as a summation of terms depending only on n and the initial conditions.
Example: n!
T(n)=T(n−1)+1
T(n)=T(n−1)+1
=(T(n−2)+1)+1
=T(n−2)+2
...
=T(n−i)+i
...
=T(0)+n=O(n)
- Substitution Method
Example:
Let T(1)=4
T(n)=2T(2n)+4n
Build solution by substituting scratch work |
Scratch pad |
T(n)=2T(2n)+4n |
T(2n=2T(22n)+4(2n) |
=2[2T(22n)+42n]+4n =22T(22n)+4n+4n |
T(22n)=2T(23n+4(22n)) |
=22[2T(23n)+422n]+4n+4n =23T(n3n)+4n+4n+4n |
Pattern?? T(23n)=2T(24n)+4(23n) |
=23[2T(24n)+4(23n)]+4n+4n+4n =24T(24n)+4n+4n+4n+4n |
|
=2iT(2in)+i(4n) |
We need to get to the base case: 2in=1 i.e. n=2i →log2n=i |
Substitute into equation above: 2log2nT(1)+(log2n)(4n) =n(4)+4nlog2n =4n+4nlog2n∈O(nlog2n) |
T(1)=4 and 2log2n=nlog22=n1=n |
- Master Theorem
- We'll see this next week when we take a look at chapter 5.1
Useful Recurrence Types:
Linear: One (constant) operation reduces problem size by one.
- T(n)=T(n−1)+c
- T(1)=d
- Solution: T(n)=(n−1)c+d
Quadratic: A pass through input reduces problem size by one.
- T(n)=T(n−1)+cn
- T(1)=d
- Solution: T(n)=[2n(n+1)–1]c+d
Logarithmic: One (constant) operation reduces problem size by half.
- T(n)=T(n/2)+c
- T(1)=d
- Solution: T(n)=clogn+d
n log n: A pass through input reduces problem size by half.
- T(n)=2T(n/2)+cn
- T(1)=d
- Solution: T(n)=cnlogn+dn