gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
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's a typo in your request, and you probably meant to ask for a function in Node.js, which utilizes JavaScript. Here's a simple function to calculate the factorial of a number in Node.js:
// Function to calculate factorial function factorial(n) { // Check if the number is less than 0, reject it. if (n < 0) { throw new Error('Factorial is not defined for negative numbers'); } // Base case: factorial of 0 is 1 if (n === 0) { return 1; } // Recursive call to calculate the factorial return n * factorial(n - 1); } // Example usage const num = 5; // Change this number to test with other inputs try { console.log(`Factorial of ${num} is ${factorial(num)}`); } catch (error) { console.error(error.message); }Here's how the function works:
- The function first checks if the input number is negative. Factorial is not defined for negative numbers, so it throws an error in this case.
- The base case for the recursion is defined: the factorial of 0 is 1.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.