Negative factorial in JavaScript I was doing a basic problem on coding a factorial \$n!\$:

function factorialize(num) {
  if (num &lt; 0) {
 return undefined;
  } else if (num === 0) {
    return 1;
  }
  else {
    return num * factorialize(num - 1);
  }
}


The site I'm learning from accepted this solution, but they're only testing for nonnegative integers, i.e for \$n \ge 0\$, not negative integers.

So I got curious on how to compute a negative factorial \$(-n)!\$. Many pages say it's undefined, but I found two saying it could be defined.


Link 1
Link 2


The gist I got is that:

\$|n!| = |(-n)!|\$

Their absolute values are the same but the negative factorials change signs. 

Examples:

\$4! = (-4)! = 24\$

\$5! = 120\$ but \$(-5)! = -120\$

The formula that I gathered from the two linked pages is:

\$(-n)! =  |n|! * (-1)^n\$

And this reflects my code. From test cases, I think I've nailed it. I just want to ask if there's a better way of coding it. Someone from here
remarked that using recursion is memory-inefficient.

function factorialize(num) {
 if (num === 0) {
   return 1;
  } else if (num &gt; 0) {
     return num * factorialize(num - 1);
  } else {
     return Math.pow(-1, num) * Math.abs(num) * factorialize(Math.abs(num) - 1);  
    }
  }

// test cases below
    console.log(factorialize(-1)); // -1
    console.log(factorialize(1)); // 1
    console.log(factorialize(0)); // 1
    console.log(factorialize(-2)); // 2
    console.log(factorialize(2)); // 2
    console.log(factorialize(-3)); // -6
    console.log(factorialize(3)); // 6
    console.log(factorialize(-4)); // 24
    console.log(factorialize(4)); // 24
    console.log(factorialize(-5)); // -120
    console.log(factorialize(5)); // 120
Changing your function to something like this would work. I don't think you need to model your function after the mathematical equation.

function factorial(num) {
  if (num &lt; 0) {
    return num * factorial(num + 1);
  } else if (num == 0) {
    return 1;
  } else {
    return num * factorial(num - 1);
  }
}


Another solution that uses tail call optimization could be

function factorial(num) {
  function recur(n, acc) {
    if (n &lt; 0) {
      return recur(n + 1, n * acc);
    } else if (n == 0) {
      return acc;
    } else {
      return recur(n - 1, n * acc);
    }
  }
  return recur(num, 1);
}