I’m trying to make a general formula for factorial and implement the same here.
its n! = n((n-1)(n-2)…(n-(n-1)).I can’t proceed any further. Your code so far
function factorialize(num) {
for(var i = 0; i < num;i--){
num * (num -1)*(num -2) .......(I'm stuck here
}
return num;
}
factorialize(5);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.
Unless n is less than 0 to start off with, that loop will run infinitely (and will not run in FCC due to it being an infinite loop)
Once you’ve fixed that, what is i on each iteration of the loop? The loop runs over and over again, so you definitely don’t want to write (n - 1) * (n - 2) ... Etc on every iteration else it’s going to run that a bunch of times. n = n * ?;
In the case of factorialize(5); you want this calculation
5((5-1)(5-2)(5-3)(5-4)) which is
5 * 4 * 3 * 2 * 1
or
5 * 4 = 20
20 * 3 = 60
60 * 2 = 120 and
120 * 1 = 120
Counting up by one (or down by one) is what a for loop does best. Of course if you start at 0 and count down you’ll be getting negative values for i and i will always be < num and your loop will run forever.
This worked but I’m still not sure about few things.
-Why var product = 1;
-Can’t we declare var product globally?
function factorialize(num) {
var product=1;
for(var i = 0; i < num;i++){
product = product * (num -i);
when you run the tests, if you use a global variable then you will be updating that variable every test. So the first test will work, but then say the first test is factorial of 3, for the next test the start value will be 6 (instead of 1) and so on. Always avoid global variables if you don’t need them because then your functions become unpredictable: they then depend on things that are not under the control of the function.
You would get the first test correct but the second test would start with product = 120. Clearly not going to get the correct answer for other tests.
Avoid the potential for mistakes. Usually with functions best if all input is parameters, all output is return value and any temporary values should be variables local to function.