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 might be a small typo in your request ("Nodx.js"), but I assume you meant "Node.js". If so, I can show you how to write a Node.js function to calculate the factorial of a number.
Here's a simple implementation in JavaScript that you can run in a Node.js environment:
javascript// 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; } // Test the function const number = 5; // You can change this number to test other values console.log(`Factorial of ${number} is: ${factorial(number)}`);
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.