3 Recurrence Relation
3 Recurrence Relation
Recurrence Relation
A recurrence relation is an equation that recursively defines a
sequence where the next term is a function of the previous terms.
For example, Fibonacci series
Fn = Fn-1+Fn-2
Recurrence Relation
void fun(int n) fun (3)
{
if (n > 0) {
cout << n << " "; 3 fun(2)
fun(n - 1);
}
} 2 fun(1)
int main()
{
fun(3); 1 fun(0)
return 0;
} stop
Recursion Tree
Time=?
It can be observed from the recursion tree that there are 3 self call, and, in each call, it
takes 1 unit of time for printing. So, time taken for n=3 will 3 and for n=n, it will be n,
i.e., O(n).
Recurrence Relation
void fun(int n) T(n)
{
if (n > 0) {
cout << n << " "; 1
fun(n - 1); T(n-1)
}
}
int main()
{
fun(3);
return 0;
}
Recurrence relation
Recurrence relation
n+ T(n-1) if n>0
T(n)= 1 n=0
Solving Recurrence Relation
Recurrence relation
n+ T(n-1) if n>0
T(n)= 1 n=0
Recursion tree method
T(n) n
n T(n-1) n-1
n-1 T(n-2) n-3
n-2 T(n-3)
.
T(2) 2
Time taken 2 T(1) 1
1 T(0)
0+1+2+3+…+n-1+n
= n(n+1)/2 stop
= O(n2)
Solving Recurrence Relation
Recurrence relation
Use back substitution method
n+ T(n-1) if n>0 T(n-1) = T(n-2) + n-1 -(ii)
T(n)= 1 n=0 T(n-2) = T(n-3)+ n-2 -(iii)
T(n)= [T(n-2)+n-1]+n
= T(n-2)+n-1+n
Replace value of T(n-2) in eq. (i)
T(n) = T(n-3)+n-2+n-1+n
.
T(n) = T(n-k)+(n-(k-1))+ (n-(k-2))+ … + (n-1) + n
Recurrence relation
Time taken
log n-1 T(n-2)
0+log1+log2+log3+…+logn-1+logn
= log[1x2x3x…xn-1xn]
= log (n!) log n-2 T(n-3)
The upper bound for n! is nn .
= log (nn) T(2)
= nlog n
log 2 T(1)
It can be observed from the above that first recurrence is repeated n times
so, time will be O(n). Similarly, for the third one log n is repeated n times
so, time taken will be n log n.
T(n) = T (n-1) + n2 ?
T(n) = T (n-2) + 1 ?
T(n) = T (n-100) + n ?
2T(n-1)+1 if n>0
T(n)= 1 n=0
T(n) = 22 [2T(n-3)+1]+2+1
= 23 T(n-3)+ 22+2+1 (iii)
T(n)= O(nlog n)
Recurrence Relation
Masters Theorem for Dividing Functions
T(n) = aT(n/b) +f(n), where a>=1, b>1, and f(n)= O(nk logpn), where k>=0
Determine values of logba and k. Based on the values of k and logba, there
will be three cases.
9. T(n)= T(n/2)+n2
Recurrence Relation
Use Masters Theorem and find time complexity
1. T(n)= 2T(n/2)+1 T(n) = aT(n/b) +f(n), where a>=1, b>1, and
Here a=2, b=2, f(n)= O(n0 log0n) f(n)= O(nk logpn), where k>=0
So, k=0, p=0
Case 1: if logba > k, then O(nlogba)
Log22=1 and k=0, case 1 is satisfied
T(n)= O(nlog22)= O(n1) Case 2: if logba = k, and
(i) if p>-1, then O(nk logp+1n)
2. T(n)= 4T(n/2)+n
(ii) if p=-1, then O(nk loglogn)
Here a=4, b=2, f(n)= O(n1 log0n)
So, k=1, p=0
(iii) if p<-1, then O(nk)
T(√n)+1 if n>2
T(n)= 1 n=2
Recurrence Relation
T(√n)+1 if n>2
T(n)= 1 n=2