Recursion question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

18th Feb 2020, 10:35 PM
Chuks AJ
Chuks AJ - avatar
2 Answers
+ 2
Wow, thanks a lot. You couldn't have answered it any better.
18th Feb 2020, 11:03 PM
Chuks AJ
Chuks AJ - avatar
+ 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
19th Feb 2020, 2:53 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar