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 was a small typo in your request mentioning "Nodx.js." I assume you meant "Node.js." Here's a simple function in Node.js that calculates 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: try { const number = 5; console.log(`Factorial of ${number} is:`, factorial(number)); } catch (error) { console.error(error.message); }Explanation:
-
Base Case: If the input number
nis0or1, the factorial is1. This acts as the base case for our recursive function. -
Recursive Case: For numbers greater than
1, the factorial ofnisnmultiplied by the factorial ofn-1. -
Error Handling: The function throws an error if a negative number is input, as factorial is not generally defined for negative numbers.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.