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
Certainly! Below is a JavaScript function that calculates the factorial of a number. The factorial of a non-negative integer
n, denoted asn!, is the product of all positive integers less than or equal ton. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.Here's the function using an iterative approach:
javascriptfunction 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: console.log(factorial(5)); // Output: 120Recursive Approach
Alternatively, you can calculate the factorial using a recursive approach:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.