Recursion

Solve this problem first.

What is the time complexity of the recursive function?

1
2
3
4
def func(n):
    if n < 1:
        return n
    return 1 + func(func(n-1))

O ( n 2 ) O(n^2) O ( n n ) O(n^n) O ( n ) O(n) O ( 2 n ) O(2^n)

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Ivan Koswara
Jun 10, 2016

By induction, clearly f u n c ( n ) = n func(n) = n for all n n . (The base case is n 0 n \le 0 ; the inductive case uses the inductive hypothesis twice to get f u n c ( f u n c ( n 1 ) ) = f u n c ( n 1 ) = n 1 func(func(n-1)) = func(n-1) = n-1 .)

Let T ( n ) T(n) be the running time of the function with argument n n . We obtain the recurrence T ( n ) = 2 T ( n 1 ) + O ( 1 ) T(n) = 2T(n-1) + O(1) , since f u n c ( f u n c ( n 1 ) ) func(func(n-1)) evaluates to f u n c ( n 1 ) func(n-1) in T ( n 1 ) T(n-1) time, and to n 1 n-1 in further T ( n 1 ) T(n-1) time, before adding a constant time for the addition. Thus we can use induction again to see that T ( n ) = O ( 2 n ) T(n) = \boxed{O(2^n)} .

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...