+ 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
7 Respostas
+ 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
+ 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
+ 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
+ 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
......
}
+ 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
0
thank you all for the clarification :)
0
a = 2, b = 3
=p(2, 3)
= 2 * p(2, 2)
= 2 * (2 * p(2, 1))
= 2 * (2 * (2))
= 8