Would you show me how can we calculate a recursive value?
for example the following recursive function:
int rec (int n)
{
if (n==1) return (1);
else
return (rec(n-1) + rec(n-1));
}
Is there any general clue to solve these type of problems?
Well lets start by writing this as
As
a+a = 2aNext we see that is multiplying 2 together
n-1times and on the nth time it is returning 1.Therefore this is equivalent to 2^(n-1)
This means that
rec(5) = 2^(5-1) = 2^4 = 16Note: the form that I have above is also far more efficient than the one you had since I only calculate
rec(n-1)rec(n-2)and so on only once (linear recursion). Where as with your function each is calculated exponentially many times (exponential recursion). This means that while my function scales fairly well, yours is basically unusable for anything larger than 100.