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
To calculate the factorial of a number in Node.js, you can write a simple function using either iterative or recursive approaches. Below, I'll demonstrate both methods.
Recursive Approach
The recursive approach is straightforward as it calls the function within itself to solve smaller subproblems.
function factorialRecursive(n) { if (n < 0) { throw new Error("Factorial is not defined for negative numbers"); } if (n === 0 || n === 1) { return 1; } return n * factorialRecursive(n - 1); } // Example usage const number = 5; console.log(`Factorial of ${number} is ${factorialRecursive(number)}`); // Output: 120Iterative Approach
The iterative approach uses a loop to calculate the factorial, which can be more efficient in terms of stack space.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.