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 seems like there is a slight typo in your request, as "Nodx.js" is not a known programming language or library. However, I assume you meant Node.js, which is a popular JavaScript runtime. I can show you how to write a function in JavaScript that calculates the factorial of a number. This function can be run in a Node.js environment.
Here's a simple recursive function to calculate the factorial of a number:
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: const number = 5; try { const result = factorial(number); console.log(`Factorial of ${number} is ${result}`); } catch (error) { console.error(error.message); }Alternatively, you can use an iterative approach:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.