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 number ( n ) (denoted as ( n! )) is the product of all positive integers less than or equal to ( n ). Here is a JavaScript function that calculates the factorial of a number using an iterative approach:
javascriptfunction factorial(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; }You can also calculate the factorial using a recursive approach. Here is how it would look:
javascriptfunction factorialRecursive(n) { if (n < 0) { throw new Error("Factorial is not defined for negative numbers"); } else if (n === 0 || n === 1) { return 1; } else { return n * factorialRecursive(n - 1); } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.