Why doesn't my attempt at factorialize work?

I’m up to the lesson"Basic Algorithm Scripting: Factorialize a Number."

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.

1 Like

for (var i = num; i > 0; i-- )
Here i is your “incrimentor”. It counts down from num to zero.

i = 1;
} else {
i = i*(i-1)i; 
}
}
return i;

Here you are using i as the calculated factorial result.

FCC stops execution if your code runs for too long. If it didn’t you would find yourself crashing your browser with an infinite loop.

1 Like

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.

1 Like

Both these explanations make sense. Thank you!

1 Like