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
I believe you meant to ask for the implementation in Node.js. Here is an example of a function to calculate the factorial of a number using Node.js:
// factorial.js // Function to calculate factorial using recursion 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); } // Function to calculate factorial using iteration function 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; } // Example usage: const number = 5; console.log(`Factorial of ${number} using recursion is:`, factorialRecursive(number)); console.log(`Factorial of ${number} using iteration is:`, factorialIterative(number)); module.exports = { factorialRecursive, factorialIterative };
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.