recategorized by
2,555 views
5 votes
5 votes
double foo(int n)
{
    int i;
    double sum;
    if(n == 0)
    {
        return 1.0;
    }
    else
    {
        sum = 0.0;
        for(i = 0; i < n; i++)
        {
            sum += foo(i);
        }
        return sum;
    }

}

The time complexity of the above code is?

recategorized by

2 Answers

Best answer
11 votes
11 votes
Answer is $O(2^n)$

$T(n) = \displaystyle \sum_{i=0}^{n-1} T(i) + cn$

The last $cn$ is for the $n$ times the for loop is executing.

T(0) = 1
T(1) = 2
T(2) =  5
T(3) = 11
T(4) = 23
T(5) = 47

So,  $$T(n) = 2^n + 2^{n-1} - 1 = O(2^n)$$
selected by
0 votes
0 votes

With each addition to the input (n), the growth rate doubles, and the algorithm iterates across all subsets of the input elements. When an input unit is increased by one, the number of operations executed is doubled. O(2^n).

Related questions

1.0k
views
1 answers
2 votes
Narasimhan asked Nov 7, 2017
1,033 views
// func() is any constant root functionfor (int i = n; i 0; i = func(i)){ // some O(1) expressions or statements}"In this case, i takes values n, n1/k, (n1/k)1/k = n1/...
2.0k
views
0 answers
1 votes
sripo asked Nov 6, 2018
2,032 views
What is the time complexity for infinite loopsQuestion 1 what is T(n) for this caseWhile(1){a=a+b;} Question 2 for this caseif(1){for i to na=a+b}else{for i to nfor j to...
931
views
2 answers
0 votes
$ourav asked May 20, 2016
931 views
Consider the following pseudo code written in C style:bool fun(int arr[],int n,int X) { if(X == 0) return true; if(n == 0 && X !=0) return false; if(arr[n-1]*arr[n-1] X)...
6.1k
views
2 answers
9 votes
vineet.ildm asked Nov 7, 2016
6,051 views
Why space complexity of heapsort is O(1)....and why not O(logn)..because of space required by recursion calls which is equivalent to height of the tree...where am i getti...