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! The factorial of a number ( n ) (denoted as ( n! )) is the product of all positive integers less than or equal to ( n ). For example, the factorial of 5 (5!) is 5 × 4 × 3 × 2 × 1 = 120. Here's a JavaScript function to calculate the factorial of a given non-negative integer:
function factorial(num) { if (num < 0) { return undefined; // Factorial is not defined for negative numbers } let result = 1; for (let i = 1; i <= num; i++) { result *= i; } return result; } // Example usage: console.log(factorial(5)); // Output: 120 console.log(factorial(0)); // Output: 1 (0! is defined as 1)This function works as follows:
- It checks if the given number is negative, in which case it returns
undefinedsince factorials for negative numbers are not defined. - It initializes
resultas 1 because the factorial of 0 is 1, which acts as the multiplication identity. - It iterates from 1 to
num, multiplyingresultby the current integer in the loop. - Finally, it returns the calculated factorial value.
You can test this function with any non-negative integer to get its factorial.
- It checks if the given number is negative, in which case it returns
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.