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 ). The factorial of 0 is defined to be 1. Here is a JavaScript function that calculates the factorial of a non-negative integer using an iterative approach:
function factorial(n) { if (n < 0) { throw new Error("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: 1This function includes a basic error check to ensure the input is non-negative, as factorials are only defined for non-negative integers. The factorial calculation itself is performed using a simple loop that multiplies the numbers from 2 to ( n ). The special case of 0 is handled naturally, since initializing to 1 will correctly return 1 when the loop does not execute for ( n = 0 ).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.