Factorialize a number in JavaScript

ham_codes
2 min readFeb 28, 2021

While learning algorithms and data structures, I’ve come to find that there are many ways to approach each unique problem. Considering the time and space complexity of an algorithm is something to always keep in consideration. I have learned that one approach to accomplishing this is to try to figure out the solution first and then refactor the solution so that the time and space complexity is factored in.

For the following question I came across, I came up with a solution that might not have the best time and space complexity but it is an easy to understand way to complete the problem.

For this example I will be taking a look at factorializing a number. The challenge here is to take in a number and multiply that number by each consecutive number minus 1. So if the number provided is 5 it would essentially do this:

5! = 5 * 4 * 3 * 2 * 1

My approach to this was to set up a loop and set the initial value to 1 and then work my way up to that given number, multiplying each number on the way.

Just as an example of how many different ways there are to accomplish this, here is one more example using a while loop.

This way goes a little deeper in set up. First we are setting up a variable and having it equal num. We are then making sure if the number is 0 or 1 that it returns 1. If the number is bigger than 1 then we will decrement the number for each iteration and then take the result and multiply the number. This way was harder for me to understand than the first straight forward example. Below is a link for more ways to factorialize a number. Thanks for reading!

--

--