+ 3
Recursion question
Why is the answer to this challenge = 8? function p(a, b) { if(b == 1) return a; else return a * p(a, --b); } console.log(p(2, 3)); I used the online visualise tool and understood the code up till step 8, when p(2, 1) and b == 1 so it returns a, which is 2. but then it returns 4 and then returns 8. Please help
2 Answers
+ 2
Wow, thanks a lot. You couldn't have answered it any better.
+ 2
p is basically recursively defining the power function.
It does this by satisfying the following identities:
a^1=a
a^n=a*(a^[n-1])
Therefore, p(2,3)=2^3=8