DEV Community

Realised-Prophets
Realised-Prophets

Posted on

How to Factorialise a Number (and not end up in a spiralling void of zeros)

Hey! So we want our code to do this: 5! = 1 * 2 * 3 * 4 * 5 = 120.

This is how:

function factorialise(num) {
  let result = 1; 
  for (let i = num; i > 0; i--) {
    result *= i;
  }
  return result;
}
factorialise(5);
Enter fullscreen mode Exit fullscreen mode

This is how (I think) it works:

  • We start with a function that takes the number we want to factorialise as its argument.

  • Next, we need somewhere to store our result so we create a result variable and initialise it to 1. It's 1 because we want to start all factorialising from there, if it were 0 we would end up in a spiralling void of nothingness because we'd be multiplying our values by 0 :(

  • Next we make a for loop. 1) set i as num. 2) the condition is that if i is greater than 0 then we will 3) decrease the value of i (which has the same value as num in the first iteration) by 1 so that we can cycle through all the numbers until (but not including) 0.

  • Now if we console.log we get this:

5
4
3
2
1
Enter fullscreen mode Exit fullscreen mode

Great. So our loop is working. First it passes in the the original input number, then it decreases until 1. Now we need to find a way to multiply each value passed in.

  • So we do this: result *= i;. Remember that result is initialised to 1 so in the first iteration it's doing 1 * 5 = 5. In the next iteration our result variable is now 5 and i has undergone one negative iteration resulting in its value now being 4. So it's doing 5 * 4 = 20 (new result * corresponding decreased interation of i). If we console.log() here we can see how it works its way through.
5
20
60
120
120
Enter fullscreen mode Exit fullscreen mode

Note how the total is repeated twice. I think this is because the last iteration is 1, so it's essentially doing 120 * 1 = 120. This does't really matter or affect the result, but it's still an unnecessary iteration. If we wanted to get rid of it we could go back to the for loop and change the condition to i > 1.

  • Ok, so now we have our result stored in our er.. result variable. Next we just need to return our result.

This is an explanation for myself really, but if you found it useful then all the better. If you see a mistake somewhere be sure to let me know, I'd appreciate that very much!

Love,

Top comments (0)