Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

Write a function in JavaScript that calculates the factorial of a number.

  1. User

    Write a function in JavaScript that calculates the factorial of a number.

  2. Assistant

    Certainly! The factorial of a number n is the product of all positive integers less than or equal to n. It's denoted as n!. Here's 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 undefined; // Factorial is not defined for negative numbers
        }
        if (n === 0 || n === 1) {
            return 1; // Base case: 0! = 1! = 1
        }
        // Recursive case: n! = n * (n-1)!
        return n * factorial(n - 1);
    }
    
    // Example usage:
    console.log(factorial(5)); // Output: 120
    

    This function works by checking if n is less than 0, and returns undefined in such cases, as the factorial is not defined for negative numbers. It then checks if n is either 0 or 1, returning 1 if true, because the factorial of 0 or 1 is always 1. Otherwise, it recursively calls itself with n-1 and multiplies the result by n, thus calculating the factorial.

    If you prefer an iterative approach, here's an alternative implementation:

    function factorial(n) {
        if (n < 0) {
            return undefined; // 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
    

    This iterative approach uses a for loop to multiply numbers from 2 to n to calculate the factorial. Both versions will give you the correct result for any non-negative integer input n.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.