// Factorialize a Number
function factorialize(num) {
if (num === 0) return 1;
return num * factorialize(num - 1);
}
factorialize(5);
// OR with Tail Call Optimization (https://stackoverflow.com/questions/33923/what-is-tail-recursion)
function factorialize(num, factorial = 1) {
if (num == 0) {
return factorial;
} else {
return factorialize(num - 1, factorial * num);
}
}
factorialize(5);
function factorialize(num) {
for (var product = 1; num > 0; num--) {
product *= num;
}
return product;
}
factorialize(5);
<?php
$num = 3;
$factorial = 1;
if($num != 0) {
for($i = $num; $i>=1; $i--) {
$factorial = $factorial * $i;
}
}
else {
$factorial = 1;
}
echo "Factorial of $num is $factorial";
?>
function factorialize(num) {
let product = 1;
for (let i = 2; i <= num; i++) {
product *= i;
}
return product;
}
factorialize(5);
function factorialize(num) {
if (num === 0) {
return 1;
}
return num * factorialize(num - 1);
}
factorialize(5);
function factorialize(num, factorial = 1) {
if (num === 0) {
return factorial;
} else {
return factorialize(num - 1, factorial * num);
}
}
factorialize(5);
function factorialize(num) {
return num < 0 ? 1 :
new Array(num)
.fill(undefined)
.reduce((product, _, index) => product * (index + 1), 1);
}
factorialize(5);