Skip to content
The Chat Archive
o3-mini· OpenAI LMArena Human Preference 140K

Implement a factorial function in Python.

  1. User

    Implement a factorial function in Python.

  2. Assistant

    Here's a simple implementation of a factorial function in Python using both a recursive and an iterative approach.

    Recursive Implementation

    def factorial_recursive(n):
        if n < 0:
            raise ValueError("Factorial is not defined for negative numbers.")
        if n == 0 or n == 1:
            return 1
        return n * factorial_recursive(n - 1)
    
    # Example usage:
    print(factorial_recursive(5))  # Output: 120
    

    Iterative Implementation

    def factorial_iterative(n):
        if n < 0:
            raise ValueError("Factorial is not defined for negative numbers.")
        result = 1
        for i in range(1, n + 1):
            result *= i
        return result
    
    # Example usage:
    print(factorial_iterative(5))  # Output: 120
    

    Both functions check for negative inputs and raise a ValueError if a negative number is provided, since the factorial is only defined for non-negative integers. You can use either version based on your preference or requirements.

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