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 meant Node.js, a JavaScript runtime built on Chrome's V8 JavaScript engine. Below is an example of a function in Node.js that calculates the factorial of a number both recursively and iteratively.
Recursive Approach
function factorialRecursive(n) { if (n < 0) { return 'Factorial is not defined for negative numbers'; } if (n === 0) { return 1; } return n * factorialRecursive(n - 1); } // Usage const number = 5; console.log(`Factorial of ${number} (recursive):`, factorialRecursive(number)); // Output: 120Iterative Approach
function factorialIterative(n) { if (n < 0) { return 'Factorial is not defined for negative numbers'; } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Usage const number = 5; console.log(`Factorial of ${number} (iterative):`, factorialIterative(number)); // Output: 120Both functions will calculate the factorial of a given non-negative integer. They handle negative input by returning a message that the factorial is not defined for negative numbers. You can choose either method based on your preference or constraints, such as call stack size when dealing with large numbers.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.