JS, как рассчитать фактор
// @ts-check
/* ---------------------------------- using a loop --------------------------------- */
(() => {
function factorial(n) {
if (n < 0) return;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(4)); // => 24
console.log(factorial(0)); // => 1
console.log(factorial(-2)); // => undefined
})();
/* ------------------------------ recursive way----------------------------- */
(() => {
function factorial(n) {
if (n < 0) return;
if (n == 0) return 1;
return n == 1 ? 1 : n * factorial(n - 1);
}
console.log(factorial(5)); // => 120
console.log(factorial(0)); // => 1
})();
Condemned Corncrake