gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
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
Sure! Below 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; }Recursive 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); }Usage
You can use either of these functions to calculate the factorial of a non-negative integer. Here's how you might use them:
console.log(factorialIterative(5)); // Output: 120 console.log(factorialRecursive(5)); // Output: 120Notes
- Both implementations handle the base case of
0!being1. - I've included a check for negative numbers, as the factorial is not defined for negative integers.
- Both implementations handle the base case of
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.