WHAT will be time complexity of relation T(n)=nT(n-1)+n in my prog something like this
f(int n)
{
c++;
if(n>0)
for(i=1;i<=n;i++)
f(n-1);
}
i took a counter to count how many time function called it gives answer between n to n! thanks.
The function is called
times. Replacing
f(n-1)
with this definition givesReplacing again gives:
Removing brackets:
This gives:
which is
n!
.We can list out a few terms
We can note a couple of things. First, the function grows more quickly than n!; it starts out smaller than it (at n=0), catches up (at n=1) and surpasses it (at n>=2). So we know that a lower bound is n!.
Now, we need the upper bound. We can notice one thing: T(n) = nT(n-1) + n < nT(n-1) + nT(n-1) for all sufficiently large n (n >= 2, I think). But we can easily show that T(n) = nT(n-1) is a recurrence relation for n!, so we know that a recurrence relation for T(n) = nT(n-1) + nT(n-1) = 2nT(n-1) is (n!)(2^n). Can we do better?
I propose that we can. We can show that for any c > 0, T(n) = nT(n-1) + n < nT(n-1) + cnT(n-1) for sufficiently large values of n. We already know that T(n-1) is bounded below by (n-1)!; so, if we take c = n/(n-1)! we recover exactly our expression and we know that an upper bound is (c^n)(n!). What is the limit of c as n goes to infinity? 0. What is the maximum value assumed by [n/(n-1)!]^n?
Good luck computing that. Wolfram Alpha makes it fairly clear that the maximum value assumed by this function is around 5 or 6 for n ~ 2.5. Assuming you are convinced by that, what's the takeaway?
n! < T(n) < ~6n! for all n. n! is the Theta-bound for your recurrence.
Your code lacks the
+n
part of the recursion, so I assume that the code is wrong and the recursionis correct.
Let
f(n)=T(n)/n!
, thenThus
T(n) ~ e*n!
.