factorial python Algorithm

The factorial Python algorithm is a computational method used to calculate the factorial of a non-negative integer. A factorial, denoted as n!, is defined as the product of all positive integers less than or equal to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. The factorial function plays a vital role in various mathematical concepts, including combinatorics, algebra, and calculus. In Python, the algorithm can be implemented using various techniques, such as iterative loops, recursion, or even by leveraging the built-in math library. An iterative approach to calculating the factorial involves using a loop to multiply integers from 1 to n. This method initializes a result variable to 1, then iterates through the range of numbers from 1 to n, updating the result variable at each step by multiplying it with the current number in the loop. On the other hand, a recursive approach defines the factorial function as a base case (n = 0 or n = 1) and a recursive case, where the function calls itself with the argument n-1. This method breaks down the problem into smaller subproblems until it reaches the base case. Python's math library also provides a built-in factorial function, which can be imported and used directly. Regardless of the implementation, the factorial algorithm is an essential tool in various mathematical and computational applications.
def factorial(input_number: int) -> int:
    """
    Calculate the factorial of specified number

    >>> factorial(1)
    1
    >>> factorial(6)
    720
    >>> factorial(0)
    1
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: factorial() not defined for negative values
    >>> factorial(0.1)
    Traceback (most recent call last):
        ...
    ValueError: factorial() only accepts integral values
    """

    if input_number < 0:
        raise ValueError("factorial() not defined for negative values")
    if not isinstance(input_number, int):
        raise ValueError("factorial() only accepts integral values")
    result = 1
    for i in range(1, input_number):
        result = result * (i + 1)
    return result


if __name__ == "__main__":
    import doctest

    doctest.testmod()

LANGUAGE:

DARK MODE: