I tried to write my own solution, and I thought it was pretty sound, but it didn’t work. I’ve seen the provided solution to the problem, but now I’m wondering if someone can help me understand why my initial attempt wouldn’t work.Thanks in advance.
function factorialize(num) {
for (var i = num; i > 0; i-- ) {
if (num == 0) {
i = 1;
} else {
i = i*(i-1)i;
}
}
return i;
}
Edit: Oops! Updated one of the lines to "i = i*(i-1)i; " as it was previously i *= i which is totally wrong.
I’m not quite sure what you’re trying to do here, but this is wrong:
i*(i-1)i
So if i is 4, you’re saying 4 * (4 - 1)4, it’s not a sum, you’ve just got that extra number shoved on the end there.
Putting that aside, you’re changing the value you’re looping over while you loop over it, so it’s just getting bigger and bigger and bigger long before it gets smaller. Use another variable to store the result, I think you’re overcomplicating things in your head here.