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
Sure, I'll provide a simple implementation of a function in Node.js to calculate the factorial of a number. The factorial of a non-negative integer
nis the product of all positive integers less than or equal ton. It is denoted byn!. Here is a basic implementation:// factorial.js // Function to calculate the factorial of a number function factorial(n) { if (typeof n !== 'number' || n < 0 || !Number.isInteger(n)) { throw new Error('Input must be a non-negative integer.'); } if (n === 0 || n === 1) { return 1; } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Example usage: try { const number = 5; // Replace with any non-negative integer console.log(`Factorial of ${number} is: ${factorial(number)}`); } catch (error) { console.error(error.message); } module.exports = factorial;
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.