Javascript for loop factorial

function FirstFactorial(num) {

// code goes here
for(var i=num;i>=1;i–){

var num1=num-1;
num=num1*num;
}
return num;

}

// keep this function call here
console.log(FirstFactorial(5));

result:430214650034342660000

Hey guys i am trying to find the factorial of a number using for loop and a function. Even though i skimmed and rechecked the algo of the program I couldnt understand why It is generating wrong results. please help here

Write down, by hand, (or log it out to the console) the value of num at the start of each loop and the error will jump out at you :slight_smile:

hahaha mate I tried it still cant get it :confused:

Alright, let me guide you a wee bit more then…

Say num = 5 when you call the function. Then num1 = 5-1 = 4 at the first iteration of the loop. Then you set num = num1 * num = 4 * 5 = 20.

The loop body ends, so the loop condition is checked - is i >= 1? Yes, since it started at 5. So then i becomes 4 and the loop starts again.

The second time around, num1 is set to num - 1 = 20 - 1 = 19…are you starting to see the problem?

2 Likes

Basically, you pass a small number to your function, and your function is returning a much bigger number. Therefore, every iteration your function returns a bigger and a bigger number. Since the number is ALWAYS > 1, your program never ends.

1 Like

thanks mate actually there was some problem with my understanding of for loop working :slight_smile:

Actually, the program does end, because the check is against the variable i which is behaving like it should. It’s just that the multiplication is being done incorrectly.

Glad I could help! Your algorithm is pretty close to working, I can think of making just three little changes to get it to do what you want :slight_smile: