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! The 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 both iteratively and recursively:
Iterative Approach
function 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
function factorialRecursive(n) { if (n < 0) { return "Factorial is not defined for negative numbers."; } if (n === 0 || n === 1) { return 1; } return n * factorialRecursive(n - 1); } // Example Usage: console.log(factorialRecursive(5)); // Output: 120Both implementations will calculate the factorial of a non-negative integer ( n ). Note that the factorial of 0 is defined to be 1, which is handled in each function. The recursive version is more elegant, while the iterative version is generally more efficient for large ( n ) because it avoids the overhead of repeated function calls.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.