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 might have meant to refer to Node.js instead of "Nodx.js," as Node.js is the popular JavaScript runtime. Below is a simple example of how to write a function in Node.js to calculate the factorial of a number. The factorial of a number
nis the product of all positive integers less than or equal ton.function factorial(n) { if (n < 0) { throw new Error('Factorial is not defined for negative numbers.'); } if (n === 0 || n === 1) { return 1; } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Example usage: const number = 5; console.log(`Factorial of ${number} is ${factorial(number)}`);This function uses an iterative approach. Here's a breakdown of how it works:
- It first checks if the input number is negative and throws an error because factorials are not defined for negative numbers.
- It then checks if the number is 0 or 1, returning 1 in those cases, as factorial(0) = 1 and factorial(1) = 1.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.