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 given non-negative integer using a recursive approach:
javascriptfunction factorial(n) { // Check if n is a non-negative integer if (n < 0) { throw new Error("Factorial is not defined for negative numbers"); } // Base case: 0! = 1 if (n === 0) { return 1; } // Recursive case: n! = n * (n-1)! return n * factorial(n - 1); } // Example usage: console.log(factorial(5)); // Output: 120 console.log(factorial(0)); // Output: 1
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.