Hi. I`ve solved the proplem but I have no idea the logic behind it. Can somebody please explain to me how the code (myNum = myNum *i) gives me the answer when Mynum is equal to 1.
Thank you.
Your code so far
function factorialize(num) {
var myNum = 1;
for(i = 1; i <= num; i++){
myNum = myNum * i;
}
return myNum;
}
factorialize(5);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36.
For this question you are trying to find the value of 5! (5 factorial)
if you wrote it down it would look something like this
5! = 5 * 4 * 3 * 2 * 1 = 120
Your solution sort of computes it backwards (in relevance to the order in which I wrote it down). Lets try to go through the loop (loop will iterate from 1 to 5) and look at the values that are produced at each iteration
L1 (i = 1): myNum = 1 * i = 1
L2 (i = 2): myNum = 1 * i = 2
L3 (i = 3): myNum = 2 * i = 6
L4 (i = 4): myNum = 6 * i = 24
L5 (i = 5): myNum = 24 * i = 120
mathmatically you have
(((((1*1)*2)*3)*4)*5)
which is equivalent to writing
1*1*2*3*4*5
which is equivilent to the factorial of 5
1*1*2*3*4*5 = 5*4*3*2*1 = 5!
I hoped that helped a little bit and wasn’t too confusing…