Write a function in Nodx.js that calculates the factorial of a number.
- User
Write a function in Nodx.js that calculates the factorial of a number.
- Assistant
It looks like there's a small typo in your request. I assume you meant to refer to Node.js, a popular JavaScript runtime. Here’s how you can write a function in Node.js to calculate the factorial of a number:
The factorial of a non-negative integer
nis the product of all positive integers less than or equal ton. It is denoted byn!. Ifnis 0, the factorial is defined as 1.Here's a simple synchronous function to calculate the factorial using recursion in Node.js:
function factorial(n) { if (n < 0) { throw new Error('Factorial is not defined for negative numbers'); } if (n === 0 || n === 1) { return 1; } return n * factorial(n - 1); } // Example usage: try { const number = 5; console.log(`Factorial of ${number} is ${factorial(number)}`); } catch (error) { console.error(error.message); }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.