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 is a simple JavaScript function that calculates the factorial of a number using an iterative approach:
javascriptfunction factorial(n) { // Check if n is a negative number, zero, or non-integer if (n < 0 || !Number.isInteger(n)) { return undefined; } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Example usage: console.log(factorial(5)); // Output: 120Alternatively, you can implement the factorial function using recursion:
javascript
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.