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". Here's a simple function to calculate the factorial of a number in Node.js:
javascriptfunction factorial(n) { if (n < 0) { throw new Error('Factorial is not defined for negative numbers'); } if (n === 0 || n === 1) { return 1; } return n * factorial(n - 1); } // Usage example console.log(factorial(5)); // Output: 120Explanation:
-
Base Case: The factorial function includes a base case that checks if the number
nis 0 or 1. In both cases, the function returns 1 because the factorial of 0 and 1 is 1. -
Recursion: If
nis greater than 1, the function returnsn * factorial(n - 1), which repeatedly calls the function with decremented values ofnuntil it reaches the base case.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.