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's a small typo in your request: you mentioned "Nodx.js," which I'm assuming is meant to be "Node.js." I'll provide you with a Node.js function that calculates the factorial of a number.
In Node.js, one common way to calculate the factorial of a number is by using a simple recursive function, as in JavaScript. Here's how you can write such a function:
// Factorial function using recursion function 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); } console.log(factorialRecursive(5)); // Output: 120You can also implement it iteratively, which can be more efficient for larger values due to potential stack size limitations in recursion:
// Factorial function 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; } console.log(factorialIterative(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.