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
nis the product of all positive integers less than or equal ton. It's denoted asn!. Here's a JavaScript function that calculates the factorial of a number using a recursive approach:function factorial(n) { // Check if the input is a non-negative integer if (n < 0) { return undefined; // Factorial is not defined for negative numbers } if (n === 0 || n === 1) { return 1; // Base case: 0! = 1! = 1 } // Recursive case: n! = n * (n-1)! return n * factorial(n - 1); } // Example usage: console.log(factorial(5)); // Output: 120This function works by checking if
nis less than 0, and returnsundefinedin such cases, as the factorial is not defined for negative numbers. It then checks ifnis either 0 or 1, returning 1 if true, because the factorial of 0 or 1 is always 1. Otherwise, it recursively calls itself withn-1and multiplies the result byn, thus calculating the factorial.If you prefer an iterative approach, here's an alternative implementation:
function factorial(n) { if (n < 0) { return undefined; // 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: 120This iterative approach uses a
forloop to multiply numbers from 2 tonto calculate the factorial. Both versions will give you the correct result for any non-negative integer inputn.
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 →