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 create a simple function. Factorial of a non-negative integer ( n ) is the product of all positive integers less than or equal to ( n ). Here’s a basic implementation using both iterative and recursive approaches:
Iterative Approach
javascriptfunction factorialIterative(n) { if (n < 0) { throw new Error('Factorial is not defined for negative numbers'); } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } console.log(factorialIterative(5)); // Output: 120
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.