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 might be a small typo in your request. You probably meant "Node.js" instead of "Nodx.js." In Node.js, you can calculate the factorial of a number using a simple recursive function, or you can use an iterative approach. Here, I will demonstrate both methods:
Recursive Approach
javascriptfunction factorialRecursive(n) { if (n < 0) { throw new Error("Factorial is not defined for negative numbers."); } if (n === 0 || n === 1) { return 1; } return n * factorialRecursive(n - 1); } // Example usage console.log(factorialRecursive(5)); // Output: 120Iterative Approach
javascript
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.