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 might be a small typo in your request—assuming you meant
Node.jsrather thanNodx.js. If you're looking to write a function in Node.js to calculate the factorial of a number, you can do so using a simple recursive or iterative approach. Below is an example using both methods. Choose the one that fits best for your use case:Recursive Approach
function factorialRecursive(n) { if (n < 0) { throw new Error("Factorial is not defined for negative numbers."); } if (n === 0 || n === 1) { return 1; // Base case } return n * factorialRecursive(n - 1); // Recursive case } console.log(factorialRecursive(5)); // Output: 120
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.