1

What is the time complexity to compute this function for n.

int rec(int n)
{
    if (n<=1) {
        return n ;
    }
    int i;
    int sum=0;
    for (i=1; i<n; i++) {
       sum=sum+rec(i); 
    }
    return sum ;
}
inhan
  • 7,394
  • 2
  • 24
  • 35
noPE
  • 601
  • 2
  • 8
  • 18

1 Answers1

9

well let's break this out

 (1)        f(n) = f(n-1) + f(n-2) + ... f(1) + 1

however,

 (2)        f(n-1) = f(n-2) + ... f(1) + 1

so plugging (2) into (1) gives

 (3)        f(n) = f(n-1) + f(n-1) = 2 f(n-1)

and f(2) = 1, so this is clearly 2n (for details: Can not figure out complexity of this recurrence). well, actually 2n-1 but in big O, it doesn't quite matter because the -1 is the same as /2.

Community
  • 1
  • 1
thang
  • 3,466
  • 1
  • 19
  • 31
  • Excellent answer I must say. Thanks a lot – noPE Jan 26 '13 at 10:37
  • Excellent, I like it, but isn't it actually a **non**-answer to the question? You just demonstrated that the O(n^2) recursive algorithm as written above blows and that a linear algorithm is possible. Don't get me wrong, this is actually better than an answer. – Ulrich Eckhardt Jan 26 '13 at 14:25
  • 1
    @doomster, that is a very astute observation. I suspect that OP used that function only to illustrate this particular type of run time, and that the *actual* function (not shown here) is one in which other work gets done at each recursive call. It's somewhat of a farce that the function returns its run time (number of + it uses). After all, why wouldn't you just analytically compute the run time and return it since a closed-form formula exists. That aside, there is a recursive coolness in this function despite being inefficient: *a function that returns its runtime*. – thang Jan 26 '13 at 15:21