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 typo in your request, as "Nodx.js" doesn't appear to be a recognized JavaScript environment or library. I'll assume you meant Node.js, which is a popular JavaScript runtime.
Below, I'll provide you with a simple Node.js function that calculates the factorial of a number. For clarity, factorials are calculated as the product of an integer and all the integers below it down to 1 (e.g., the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120).
Here's a function to compute the factorial iteratively:
javascriptfunction factorialIterative(n) { if (n < 0) return -1; // Factorial is not defined for negative numbers if (n === 0 || n === 1) return 1; // 0! and 1! are both 1 let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } console.log(factorialIterative(5)); // Output: 120
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.