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
Certainly! Here's a JavaScript function that calculates the factorial of a number using an iterative approach:
function 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; } // Example usage: console.log(factorial(5)); // Output: 120Here's a breakdown of the function:
- The function
factorialtakes an integernas an argument. - It throws an error if
nis negative, as factorials are not defined for negative numbers. - It initializes a variable
resultto 1, as the factorial of 0 is 1 (0! = 1) and it's the multiplicative identity. - A for loop is used to multiply
resultby each integer from 2 up ton. - Finally, it returns the computed
result.
If you prefer a recursive approach, you can also define the function like this:
function factorial(n) { if (n < 0) { throw new Error("Factorial is not defined for negative numbers."); } if (n === 0 || n === 1) { return 1; } return n * factorial(n - 1); } // Example usage: console.log(factorial(5)); // Output: 120In the recursive version, the function calls itself with
n - 1until it reaches the base casen === 0orn === 1, at which point it returns 1. - The function
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →
- gpt-4o-2024-08-06Compare side by side →