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 create a function that calculates the factorial of a number in Node.js, you can use a simple recursive approach or an iterative one. Here's how you can implement both approaches:
Recursive Approach
The factorial of a non-negative integer ( n ) is the product of all positive integers less than or equal to ( n ). It can be defined recursively as:
- ( 0! = 1 )
- ( n! = n \times (n-1)! ) for ( n > 0 )
Here is a recursive implementation:
javascriptfunction factorialRecursive(n) { if (n < 0) { throw new Error('Factorial is not defined for negative numbers'); } if (n === 0) { return 1; } return n * factorialRecursive(n - 1); } // Example usage: console.log(factorialRecursive(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.