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 you made a typo when mentioning Nodx.js; I assume you meant Node.js. Below is a simple Node.js function to calculate the factorial of a non-negative integer using recursion. The factorial of a number ( n ) is the product of all positive integers less than or equal to ( n ).
Here's the implementation:
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.