gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
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 there's a small typo in your request. If you're referring to writing a function in Node.js (which is the correct spelling for the popular JavaScript runtime), here's a simple function to calculate the factorial of a number:
// 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; } // Example usage const number = 5; try { console.log(`Factorial of ${number} is: ${factorial(number)}`); } catch (error) { console.error(error.message); }Explanation:
- Error Handling: The function throws an error for negative inputs because the factorial is only defined for non-negative integers.
- Base Cases: If the input is
0or1, it returns1, as0!and1!are both .
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.