Basic Algorithm Scripting - Factorialize a Number

Tell us what’s happening:

I’m stuck, I’m finding this hard. With the code I’ve written, it’s a potential infinite loop. How can we fix this?

Your code so far

function factorialize(num) {
  while (num > 0) {
    return num * (num - 1);
  }
}

factorialize(5);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36

Challenge Information:

Basic Algorithm Scripting - Factorialize a Number

What’s the base case? When function should stop calling itself, but instead return some known result?

Hi @KoduFCC

You need a way to decrement num each pass of the loop.

Happy coding

I’m not sure which loop to use, whether it’s a for loop or while loop.

Either will work fine.

I tried decrementing num, but it’s not working. Here’s my code:

function factorialize(num) {
  let fact = 0;
  while (num > 0) {
    num--;
    fact = num * (num - 1);
  }
  return fact;
}

Two questions

  1. why do you immediately decrement num in the loop before using it?
  2. why is fact only ever the product of 2 numbers?
  1. I need to decrement num until it reaches 0.
  2. Due to the above point, I made fact the product of 2 numbers just to prevent over complexity.
  1. Ok, but why do you immediately decrement num before using it?
  2. I don’t see how only multiplying 2 numbers an 0 others helps you though? How many numbers are you supposed to multiply together?