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. I'll assume you meant Node.js instead of "Nodx.js." Here's a simple Node.js function to calculate 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; } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Usage example const number = 5; console.log(`Factorial of ${number} is ${factorial(number)}`);Explanation:
-
Error Handling: The function first checks if the input
nis negative and throws an error because the factorial for negative numbers is undefined. -
Base Cases: If
nis 0 or 1, it returns 1 because the factorial of both 0 and 1 is 1.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.