factorial iterative Algorithm

The factorial iterative algorithm is an approach used to calculate the factorial of a given non-negative integer, which is the product of all positive integers less than or equal to that number. Factorial is commonly denoted by an exclamation mark (n!), and it has various applications in mathematics, including permutations and combinations, power series, and calculus. The iterative algorithm uses a loop, such as for or while, to repeatedly multiply the integer by decreasing positive integers until it reaches 1. In the iterative approach, the algorithm initializes a variable, typically called 'result' or 'factorial,' with the value of 1. Then, a loop is executed that starts with the given number (n) and decrements at each iteration until it reaches 1. At every step, the loop multiplies the current value of the result variable by the loop's counter variable. By the end of the loop, the result variable holds the final factorial value of the given number (n!). This method is generally faster and more efficient in terms of memory usage compared to its counterpart, the recursive factorial algorithm, as it does not require the overhead of function calls and stack frames.
# factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial


def factorial(n: int) -> int:
    """
    >>> import math
    >>> all(factorial(i) == math.factorial(i) for i in range(20))
    True
    >>> factorial(0.1)
    Traceback (most recent call last):
        ...
    ValueError: factorial() only accepts integral values
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: factorial() not defined for negative values
    """
    if n != int(n):
        raise ValueError("factorial() only accepts integral values")
    if n < 0:
        raise ValueError("factorial() not defined for negative values")
    value = 1
    for i in range(1, n + 1):
        value *= i
    return value


if __name__ == "__main__":
    n = int(input("Enter a positive integer: ").strip() or 0)
    print(f"factorial{n} is {factorial(n)}")

LANGUAGE:

DARK MODE: