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
Certainly! Below is a simple implementation of a function in Node.js that calculates the factorial of a given number. You can either use an iterative approach or a recursive approach to solve the problem. Here is the recursive version, which is more elegant and concise for calculating factorials:
// Factorial function using recursion function factorial(n) { if (n < 0) { throw new Error("Factorial is not defined for negative numbers."); } if (n === 0 || n === 1) { return 1; } return n * factorial(n - 1); } // Example usage try { const number = 5; // Change this to test other numbers const result = factorial(number); console.log(`Factorial of ${number} is ${result}`); } catch (error) { console.error(error.message); }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.