Factorial of a number

Hi, why does the function below to find the factorial of a number not work?

function factorial (num) {
for (var i = 1; i < num; i++) {
num *= i;
}
return num;
}

Thanks for replying.
The statement num *= i is equivalent to num = num * 1. I think that num, therefore, will automatically get multiplied.

@P1xt, @taniatabz
Both solutions will crash the page.

for (var i = 1; i < num; i++) {
  num *= i; //bad
}

num is being multiplied by i at every iteration. Hence it will never be < or <= to i.

@IsaacAbrahamson, @P1xt Thank you.

i was stuck with the same code as you. took me a while to figure it out. here is my solution:

function factorialize(num) {
var solution = 1;
for (var i = 1; i <= num; i++) {
solution *= i;
}
return solution;
}

factorialize(5);

1 Like