Write a function in JavaScript that calculates the factorial of a number.
- User
Write a function in JavaScript that calculates the factorial of a number.
- Assistant
To calculate the factorial of a number in JavaScript, you can write a function that uses either an iterative approach or a recursive approach. I'll show you both methods.
Iterative Approach
This method uses a simple loop to multiply the numbers from the given number down to 1.
javascriptfunction factorialIterative(n) { if (n < 0) { return "Factorial is not defined for negative numbers."; } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Example usage: console.log(factorialIterative(5)); // Output: 120Recursive Approach
This method involves the function calling itself to perform the calculation, reducing the problem size at each step.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.