+ 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
2 Respuestas
+ 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
+ 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