Recursion size

Consider the recursive functions below which output the same value:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def rec1(n):
    if n <=1:
        return 1
    else:
        return 2*rec1(n-1)
def rec2(n):
    if n<=1:
        return 1
    else:
        return rec2(n-1) + rec2(n-1)

What is the running time of the algorithms?

O ( n ) O(n) for the first and O ( 2 n ) O(2^{n}) for the second O ( 2 n ) O(2^{n}) for the first and O ( n ) O(n) for the second O ( n ) O(n) for the first and O ( n 2 ) O(n^{2}) for the second Both in O ( 2 n ) O(2^{n}) Both in O ( n ) O(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

rec1 has linear descent to n=1. rec2 bifurcates at each level of descent to n=1. ( i = 0 n 1 2 i ) (\sum _{i=0}^{n-1} 2^i) + 1 for the original call gives 2 n 2^n .

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...