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 looks like there might be a small typo in your request. I assume you meant "Node.js" instead of "Nodx.js." Below is a simple function in Node.js to calculate the factorial of a number. The factorial of a number ( n ) (denoted as ( n! )) is the product of all positive integers less than or equal to ( n ).
Here's how you can write this in Node.js:
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; // You can change this number to test with other values console.log(`Factorial of ${number} is ${factorial(number)}`);Explanation:
- The function
factorialtakes an integernas input. - It first checks if
nis negative and throws an error if so, because factorials are not defined for negative numbers.
- 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.