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