+ 2

why ? 24

What is the output of this code? function p(m) { if (m==1) { return m; } else { return m * p(m-1); } } alert(p(4)); answer 24

23rd Aug 2018, 7:53 AM
ŠŠ»Š¼Š°Ń‚ ŠŠ¹Ń‚Š±Š°ŠµŠ²
ŠŠ»Š¼Š°Ń‚ ŠŠ¹Ń‚Š±Š°ŠµŠ² - avatar
2 Answers
+ 2
Replace m with 4: function p(m) { //m=4 if (m==1) { // 4==1 is false return m; } else { //else block is executed return m * p(m-1); //4 * p(3) } } Now replace m with 3 so you should get p(3) = 3 * p(2) And p(2) = 2 * p(1) . Now in p(1) m==1 is true and it returns 1 so p(1) = 1 Putting it together you get p(4) = 4 * p(3) = 4 * 3 * p(2) = 4*3*2*p(1)= 4*3*2*1= 24
23rd Aug 2018, 8:05 AM
Chrizzhigh
Chrizzhigh - avatar
+ 2
Its a recursive function for calculate factorial of a number... It call recursively itself multply param m with factorial of m-1 while m==1 then: p(4) = 4 * p(3) p(3)= 3 * p(2) p(2)= 2 * p(1) p(1)= 1 thats: 4*3*2*1= 24
23rd Aug 2018, 8:00 AM
KrOW
KrOW - avatar