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'm assuming you meant "Node.js" instead of "Nodx.js". Below is an example of a simple function in Node.js that calculates the factorial of a non-negative integer using a recursive approach:
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); } // Example usage: try { const number = 5; console.log(`Factorial of ${number} is ${factorial(number)}`); // Output: Factorial of 5 is 120 } catch (error) { console.error(error.message); }This code defines a
factorialfunction that recursively calculates the factorial of a given numbern. Note a few key points:- The function checks if
nis negative and throws an error because factorials are only defined for non-negative integers. - It handles the base cases where
nis 0 or 1, both returning a factorial of 1. - For other cases, it calls itself with the argument and multiplies the result by .
- The function checks if
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.