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 using an iterative approach:
javascriptfunction factorial(n) { if (n < 0) { throw new Error("Negative numbers do not have a factorial."); } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Example usage: console.log(factorial(5)); // Output: 120This function works as follows:
- It first checks if the input number
nis less than 0, in which case it throws an error because factorials for negative numbers are not defined. - It initializes
resultto 1 because the factorial of 0 is 1 and acts as an identity element for multiplication. - It then iterates from 2 to
n, multiplying theresultby each number in this range to compute the factorial. - Finally, it returns the computed factorial.
You can use this function to calculate the factorial of any non-negative integer by passing the integer as the argument to the function.
- It first checks if the input number
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.