+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/18/2020 10:35:40 PM

Chuks AJ

3 Answers

New Answer

+7

p(2,3) - initial call In function a = 2 b= 3. b == 1? No, so call return a * p(a, --b) = return 2 * p(2, 2) - (1) in fun a = 2 b = 2 b == 1? no so call return 2 * p(2, 1) - (2) in fun a = 2 b = 1 b == 1? yes return 2 code return to (2) which return 2 * 2 = 4 code return to (1) which return 2 * 4 = 8 final value

+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