Open In App

Master Theorem For Subtract and Conquer Recurrences

Master theorem is used to determine the Big – O upper bound on functions which possess recurrence, i.e which can be broken into sub problems. 
Master Theorem For Subtract and Conquer Recurrences
Let T(n) be a function defined on positive n as shown below: 
 



for some constants c, a>0, b>0, k>=0 and function f(n). If f(n) is O(nk), then
1. If a<1 then T(n) = O(nk
2. If a=1 then T(n) = O(nk+1
3. if a>1 then T(n) = O(nkan/b)
Proof of above theorem( By substitution method ):
From above function, we have: 
T(n) = aT(n-b) + f(n) 
T(n-b) = aT(n-2b) + f(n-b) 
T(n-2b) = aT(n-3b) + f(n-2b)
Now, 
T(n-b) = a2T(n-3b) + af(n-2b) + f(n-b) 
T(n) = a3T(n-3b) + a2f(n-2b) + af(n-b) + f(n) 
T(n) = ?i=0 to n ai f(n-ib) + constant, where f(n-ib) is O(n-ib) 
T(n) = O(nk ?i=0 to n/b ai )

 
Where, 
If a<1 then ?i=0 to n/b ai = O(1), T(n) = O(nk)
If a=1 then ?i=0 to n/b ai = O(n), T(n) = O(nk+1
If a>1 then ?i=0 to n/b ai = O(an/b), T(n) = O(nkan/b)
Consider the following program for nth fibonacci number
 






#include<stdio.h>
int fib(int n)
{
   if (n <= 1)
      return n;
   return fib(n-1) + fib(n-2);
}
  
int main ()
{
  int n = 9;
  printf("%d", fib(n));
  getchar();
  return 0;
}




# Python3 code for the above approach
def fib(n):
    if (n <= 1):
        return n
    return fib(n - 1) + fib(n - 2)
 
# Driver code
n = 9
print(fib(n))
 
# This code is contributed
# by sahishelangia




//Java code for above the approach.
class clg
{
 static int fib(int n)
{
if (n <= 1)
    return n;
return fib(n-1) + fib(n-2);
}
// Driver Code
public static void main (String[] args)
{
int n = 9;
System.out.println( fib(n));
}
}
// This code is contributed by Mukul Singh.




// C# code for above the approach.
using System;
     
class GFG
{
    static int fib(int n)
    {
        if (n <= 1)
            return n;
        return fib(n - 1) + fib(n - 2);
    }
     
    // Driver Code
    public static void Main(String[] args)
    {
        int n = 9;
        Console.WriteLine(fib(n));
    }
}
 
// This code has been contributed
// by Rajput-Ji




<?php
// PHP code for the above approach
function fib($n)
{
    if ($n <= 1)
        return $n;
    return fib($n - 1) +
           fib($n - 2);
}
 
// Driver Code
$n = 9;
echo fib($n);
 
// This code is contributed
// by Akanksha Rai
?>




<script>
    // Javascript code for above the approach.
     
    function fib(n)
    {
        if (n <= 1)
            return n;
        return fib(n - 1) + fib(n - 2);
    }
     
    let n = 9;
      document.write(fib(n));
     
</script>

Output 
 

34

Time complexity Analysis: 
The recursive function can be defined as, T(n) = T(n-1) + T(n-2) 
 

 

More Examples:

 

 


Article Tags :