int e(int x, int n)
{
static int f=1, p=1; // f for factorial evaluation & p for power evaluation
int r;
if(n==0){
return 1;
}
else {
r = e(x, n-1);
p = p*x;
f = f*n;
return r + p/f;
}
}
void main(){
// Just for example
int n = 4;
int x = 1;
int r = e(1, 4);
}
Trying to find the Taylor series of e^x using recursion (involving static variables) Now, when we count the number of multiplications here, then mathematically we count it by writing the series and adding the total number of multiplications involved, which gives a total of n(n+1)/2 multiplications, i.e. O(n^2) multiplications and so is the time complexity
But if I try to count the number of multiplications by tracing this recursion, then I get 2*n - 1 multiplications, i.e. O(n) multiplications only,
So, now I'm starting to think that this happened because of the static variables. If I'm wrong by any means, then please explain me step by step to find the time complexity of this recursive function by tracing its recursion tree.
To say the result, there's nothing related with the static values. And your mathematically counting is wrong.
I have tried your code with python. This is the code what I have tried.
And I get this result.
As you see the result, the recursion is just called for n+1 times. The recursion tree is simple: It calls the params as (x, n-1), (x,n-2), ... (x,0). And at each call, the multiplications are not done n times. It is just done 2 times. So total count is 2*n times. Your mistake was that in every call the multiplication is done for n times (n - given parameter, not original n).