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 there might be a small typo in your request. Did you mean Node.js instead of "Nodx.js"? Assuming you meant Node.js, I can help you write a simple function to calculate the factorial of a number. The factorial of a number ( n ) is the product of all positive integers less than or equal to ( n ). It is typically denoted as ( n! ).
Here is a function in Node.js that calculates the factorial of a given number using both iterative and recursive approaches:
// Iterative approach function factorialIterative(n) { if (n < 0) return -1; // Factorial is not defined for negative numbers if (n === 0) return 1; // 0! is 1 let result = 1; for (let i = 1; i <= n; i++) { result *= i; } return result; } // Recursive approach function factorialRecursive(n) { if (n < 0) return -1; // Factorial is not defined for negative numbers if (n === 0) return 1; // 0! is 1 return n * factorialRecursive(n - 1); } // Example usage const number = 5; console.log(`Factorial of ${number} (Iterative): `, factorialIterative(number)); console.log(`Factorial of ${number} (Recursive): `, factorialRecursive(number));
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.