I was doing a basic problem on coding a factorial \$n!\$:
function factorialize(num) {
if (num < 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.
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 > 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