+ 1

Simple challenge explanation

Hi, can someone explain me please how do we get the result if the following code. I mean step by step instructions. function p (a, b) { if (b == 1) return a; else return a * p(a, --b); } console.log(p(2,3)); result: 8

21st Sep 2017, 4:23 PM
Pav
7 Antworten
+ 13
Step 1 : a = 2, b = 3 => p(2, 3) = 2 * p(2, 2) as --b is 2. Step 2 : a = 2, b = 2 => p(2, 2) = 2 * p(2, 1) as --b is 1. Step 3 : a = 2, b = 1 => p(2, 1) = 2 as b == 1. Final Result = 2 * p(2, 2) = 2 * (2 * p(2, 1)) = 2 * (2 * (2)) = 8
21st Sep 2017, 4:29 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 6
p(2,3) [ p(2,3) will return 2*p(2,2)] then 2*p(2,2) [ p(2,2) will return 2 * p(2,1)] then 2*2*p(2,1) [ p(2,1) will return 2 as b == 1 ] then 2*2*2 =8
21st Sep 2017, 4:26 PM
Kartikey Sahu
Kartikey Sahu - avatar
+ 6
Firstly, input to the function is (2,3). So, a==2 and b==3. Now, as if condition is not true, else statement is executed and we return 2*p(2,2) now p(2,2) calls the function itself [this is called recursion] and now p(2,2) returns 2*p(2,1) and now p(2,1) returns 2*1== 2. => 2*p(2,2) == 2*2*p(2,1) == 2*2*2 == 8
21st Sep 2017, 4:38 PM
Lakshay
Lakshay - avatar
+ 5
function p (2,3){ if( 3 == 1)//false return 2; else return 2 * p(2, 2)// p(2,2)= 4; 2*4=8 } function p(2,2){ if(2==1) return 2 else return 2 * p(2,1) //p(2,1) = 2; 2*2 =4 } function p (2,1){ if (1==1)//true return 2 ...... }
21st Sep 2017, 4:33 PM
Yaroslav Pieskov
Yaroslav Pieskov - avatar
+ 3
1)if a=2,b=3 then p(2,3) is 2*p(2,2) 2) we get p(2,2) which is 2*p(2,1) 3) we get p(2,1) so b== 1 then returns 2 4) final answer obtain is 2*2*2=8
22nd Sep 2017, 5:33 AM
Sameena Begum Moghul
Sameena Begum Moghul - avatar
0
thank you all for the clarification :)
21st Sep 2017, 5:48 PM
Pav
0
a = 2, b = 3 =p(2, 3) = 2 * p(2, 2) = 2 * (2 * p(2, 1)) = 2 * (2 * (2)) = 8
22nd Sep 2017, 12:30 AM
NAGANDLA.LEELA PAVAN KUMAR
NAGANDLA.LEELA PAVAN KUMAR - avatar