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 you've mentioned "Nodx.js," which seems to be a typo if you meant "Node.js." I’ll provide you with a JavaScript function to calculate the factorial of a number, which you can use in a Node.js environment.
Here's a simple recursive implementation of a factorial function:
// Function to calculate factorial of a number function factorial(n) { // Base case: if n is 0 or 1, return 1 if (n === 0 || n === 1) { return 1; } // Recursive case: n * factorial of (n-1) return n * factorial(n - 1); } // Example usage: const num = 5; console.log(`Factorial of ${num} is ${factorial(num)}`); // Output: Factorial of 5 is 120This function works fine for small values of
n. However, for large values, the recursive approach may cause a stack overflow. To handle larger numbers, you can use an iterative approach:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.