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! Below is a JavaScript function that calculates the factorial of a number using a simple iterative approach. The factorial of a number
nis the product of all positive integers less than or equal ton.javascriptfunction 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: 120 console.log(factorial(0)); // Output: 1Explanation:
- Error Handling: The function checks if
nis negative. If it is, an error is thrown because factorials are not defined for negative numbers. - Iterative Calculation: We initialize
resultto 1. Then we loop from 2 up to , multiplying by each number in the loop. This accumulates the product of all integers up to .
- Error Handling: The function checks if
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.