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's a small typo in your request, where "Nodx.js" might have been intended to be "Node.js." I'll assume you're asking for a Node.js function that calculates the factorial of a number. Below is a simple Node.js function that accomplishes this task:
javascriptfunction factorial(n) { if (n < 0) { throw new Error("Factorial is not defined for negative numbers."); } if (n === 0 || n === 1) { return 1; } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Example usage: console.log(factorial(5)); // Output: 120Explanation:
- The function
factorialtakes an integer as input.
- The function
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.