Factorial of a number

Factorial of a number
0

#1

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;
}


#3

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


#4

@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.


#6

@IsaacAbrahamson, @P1xt Thank you.


#7

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);