Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity for recursion in for loop

func(n){
 if(n == 0){
   //print sth
   return;
 } 
 for(i=1;i<=6;i++){
   func(n-1)
 }
}   

Please help me understand time complexity of above pseudo code.

like image 340
nodus tollens Avatar asked Dec 25 '22 05:12

nodus tollens


1 Answers

Your recursive code has the following properties:

  • When you call the function with the argument 0, it does a constant amount of work and then returns.
  • When you call the function with an argument n > 0, it does a constant amount of work and makes six recursive calls on problems of size n - 1.

Mathematically, we can model the total work done as a recurrence relation, letting T(n) denote the amount of work done when you call func(n):

  • T(0) = 1
  • T(n) = 6T(n - 1) + 1

Let's play around with this and see what we find.

  • T(0) = 1.
  • T(1) = 6T(0) + 1 = 6 + 1 = 7.
  • T(2) = 6T(1) + 1 = 6(7) + 1 = 43.
  • T(3) = 6T(2) + 1 = 6(43) + 1 = 259.
  • T(4) = 6T(3) + 1 = 6(259) + 1 = 1555.

It might not be obvious just by looking at this, the numbers here are actually given by the formula

T(n) = (6n+1 - 1) / 5

We can check this briefly as follows:

  • T(0) = (61 - 1) / 5 = 5 / 5 = 1.
  • T(1) = (62 - 1) / 5 = 35 / 5 = 7.
  • T(2) = (63 - 1) / 5 = 215 / 5 = 43.

Asymptotically, this means that T(n) = Θ(6n), so the overall runtime is Θ(6n).

So... where did (6n+1 - 1) / 5 come from? Notice that

  • T(0) = 1
  • T(1) = 6 · 1 + 1
  • T(2) = 62 · 1 + 6 · 1 + 1
  • T(3) = 63 · 1 + 62 · 1 + 6 · 1 + 1

More generally, T(n) seems to have the form

6n + 6n-1 + ... + 61 + 60.

This is the sum of a geometric series, which simplifies to (6n+1 - 1) / 5.

like image 66
templatetypedef Avatar answered Apr 17 '23 19:04

templatetypedef