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 ;
}
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 ;
}
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.