# Factorialize a Number , strange output

can someone explain what is going on here,
for the following code , the output is 3125 but how
function factorialize(num) {
let fn=1
for(let i=num; i>0; i–){
fn *= num
}
return fn;
}
console.log(factorialize(5));

``````function factorialize(num) {
let fn=1
for(let i=num; i>0; i–){
fn *= num
console.log(fn)    //Debug here would give you the output of 5, 125, 25, 125,  625, 3125
}
return fn;
}
console.log(factorialize(5));
``````

When I debug complicated logic, I try to add console.log output in the middle of the code to get the intermediate value. In your case, I added the line console.log(fn) right after “fn *= num” to see what fn value is after each loop.

The loop shows that the calculation is actually like this:
1st loop: fn = 1 * 5 where fn = 1 and num = 5
2nd loop: fn = 5 * 5 where fn = 5 from the 1st loop and num is still = 5
3rd loop: fn = 25 * 5

So for factorial, it should be 5 * 4 * 3 * 2 * 1. The value decreasing in the loop is “i” so you should use it for the calculation.

If you want the final solution,
fn *= i

the factorial code is so confusing , if you can , please explain

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.