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 write a function in Node.js that calculates the factorial of a number, you first need to decide whether you want to implement it using a recursive or iterative approach. Here, I'll show you both methods:
Recursive Approach
function factorialRecursive(n) { if (n < 0) { throw new Error('Factorial is not defined for negative numbers'); } if (n === 0 || n === 1) { return 1; } return n * factorialRecursive(n - 1); } try { console.log(factorialRecursive(5)); // Output: 120 } catch (error) { console.error(error.message); }Iterative Approach
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; } try { console.log(factorialIterative(5)); // Output: 120 } 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.