I failed to find out reason of the output: 337
function mlt(a, b){
if(!(a&&b)) {
return 0;
}else if(b==1){
return a;
} else {
return (a mlt(a, b-1));
}
}
document.write(mlt(3, 11));
document.write(mlt(7, 1));
CodePudding user response:
lets do this in simple way:
mlt(3,11) :
false false true => return 3 mlt(3, 10)
false false true => return 3 3 mlt(3 , 9)
false false true => return 3 3 3 mlt(3 , 8)
false false true => return 3 3 3 3 mlt(3 , 7)
false false true => return 3 3 3 3 3 mlt(3 , 6)
false false true => return 3 3 3 3 3 3 mlt(3 , 5)
false false true => return 3 3 3 3 3 3 3 mlt(3 , 4)
false false true => return 3 3 3 3 3 3 3 3 mlt(3 , 3)
false false true => return 3 3 3 3 3 3 3 3 3 mlt(3 , 2)
false false true => return 3 3 3 3 3 3 3 3 3 3 mlt(3 , 1)
summation of the 3 equal to 30 mlt(3,1)
mlt(3,1) : false true false So equal to a = 3
First output is 33
mlt(7,1) : false true false So equal to a = 7
Final output is 337
33 for mlt(3,11)
7 for mlt(7,1)
Happy codding :)
CodePudding user response:
You're getting 337 simply because the results of your two function calls are 33 and 7 respectively. Since you're writing this with document.write its simply appending the 7 to the end of the 33 resulting in 337
document.write(mlt(3, 11));
returns 33
document.write(mlt(7, 1));
returns 7