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! A factorial of a non-negative integer ( n ), denoted as ( n! ), is the product of all positive integers less than or equal to ( n ). Here's a simple function in JavaScript to calculate the factorial of a number using recursion, as well as an iterative approach:
Recursive Approach
javascriptfunction factorialRecursive(n) { if (n < 0) { return "Invalid input: factorial is not defined for negative numbers."; } if (n === 0 || n === 1) { return 1; } return n * factorialRecursive(n - 1); }Iterative Approach
javascript
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.