Working with Factorials

Working with Factorials
0

#1

Hello all! I’ve started the Java Script challenges which are a fresh break from constant lessons. My current problem is with creating a factorial function. I decided to use a for loop for it, and it makes sense to me but I’m just not sure where I’m going wrong here. Maybe someone can help me out, so here is my function on factorializing any num values inputed to my factorialize function:

function factorialize(num) {
var finishedProduct;
for (i=num-1; i>0; i--) {
finishedProduct = num * i;
}
return finishedProduct;
}

factorialize(5);

#2

First, why num-1?
Second, you are just assigning num * i to finishedProduct four times (it’ll always be equal to num at the end).

#3

You reset the value of finishedProduct always. At the end you’ll have the value of num, as num*1=num

#4

I’m not entirely sure what I’m trying to do here as for loops still confuse me a bit. What I can tell you I’m trying to do with the for loop is to say, Ok, i starts out as num-1 and will go to num-2, num-3, num-4... until i reaches num-(num+1) or 1, which is obviously the last integer before 0. And then the finishedProduct statement underneath is supposed to basically multiply num * i which in long hand would look like num * num-1 * num-2 ... num-(num+1) (forgive me for the weird math this is the best way I can describe it. Maybe a for loop just isn’t the right way to do it but that’s at least what I’m going for maybe I’m doing something wrong.

#5

To be clear, factorial of 5 is 1 * 2 * 3 * 4 * 5

actually i starts as 4 (num-1) and goes to 1 (i > 0). You see that there is no 5

it won’t, because each time you do finishedProduct = num * i; which assigns new value to finishedProduct.

To correct your code you should start with num and instead of assigning you should multiply previous value like this:
finishedProduct = finishedProduct * i; (or shorthand version finishedProduct *= i;)