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 is a typo in your request. I assume you mean Node.js instead of "Nodx.js." Let's write a simple Node.js function that calculates the factorial of a number. Factorial of a non-negative integer
n, denoted asn!, is the product of all positive integers less than or equal ton. Here's how you can write such a function:function 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: try { console.log(factorial(5)); // Output: 120 console.log(factorial(0)); // Output: 1 console.log(factorial(-1)); // Throws error } 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.