4
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.

0

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.