The best way to factorialize a number

Tell us what’s happening:
I pass the test but I am thinking a more efficient way to factorization. without the if (x == -1) to handle the 0 case.

Your code so far


function factorialize(num) {
  var x = num-1;
  if(x == -1){
    return 1;
  }
  while(x > 0){
  num *= x
  x--;
  }
  return num;
}

factorialize(5);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number

Try using recursion.

1 Like

There is a method called Stirling’s approximation, which approximates large factorials. Other than that, brute force seems like the way to go.

Be cautious about using a word like “efficient” without defining what it actually means to you. I usually think of it as less running time and less memory required. In this case, recursion is less efficient than iteration.

Your code can be simplified by tiny bit and that’s pretty much it.

// Assume n >= 0
function facto(n) {
    if (n <= 1) {
        return 1
    }
    
    for (let i = n-1; i > 1; --i) {
        n *= i
    }
    return n
}

Depending on the size of your number to be factored, use the plain for-loop function pattern, do not use recursion. The code will look cluttered but is lighter on execution. Otherwise, use a recursive function pattern, it will look cleaner and easier on the eyes of a reader. It all depends on the load!