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 is the product of all positive integers less than or equal to that number. It's denoted by
n!and calculated asn! = n * (n - 1) * (n - 2) * ... * 1. Here is a JavaScript function that calculates the factorial of a number using a recursive approach:function factorial(n) { // Check if the input is a non-negative integer if (n < 0) { return "Factorial is not defined for negative numbers."; } if (n === 0 || n === 1) { return 1; // Base case: 0! = 1 and 1! = 1 } return n * factorial(n - 1); // Recursive case } // Example usage: console.log(factorial(5)); // Output: 120 console.log(factorial(0)); // Output: 1 console.log(factorial(3)); // Output: 6Alternatively, you can also compute the factorial using an iterative approach:
function factorialIterative(n) { // Check if the input is a non-negative integer if (n < 0) { return "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(factorialIterative(5)); // Output: 120 console.log(factorialIterative(0)); // Output: 1 console.log(factorialIterative(3)); // Output: 6
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.