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 you meant to say Node.js, which is a popular runtime for executing JavaScript on the server side. Below is a simple function in JavaScript that calculates the factorial of a number. You can use this function in a Node.js application.
// Factorial function using recursion function 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 try { const number = 5; console.log(`Factorial of ${number} is ${factorial(number)}`); } catch (error) { console.error(error.message); }Explanation:
-
Recursion: The function uses recursion to calculate the factorial. The factorial of a number
nis the product of all positive integers less than or equal ton. -
Base Case: The base cases are handled for
n = 0andn = 1, both of which return .
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.