Find the Factorial of a Number in Python

The factorial of a number n (written as n!) is the product of all positive integers up to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.

Using Recursion

def factorial_recursive(n):
    if n == 0 or n == 1:
        return 1
    return n * factorial_recursive(n - 1)

print(factorial_recursive(5))  # Output: 120

Using a Loop (Iterative)

def factorial_iterative(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

print(factorial_iterative(5))  # Output: 120

Using Python’s Built-in math Module

import math

print(math.factorial(5))  # Output: 120

Key Takeaway

For interviews, demonstrate the recursive approach to show understanding of base cases. In production, prefer math.factorial() as it is optimized and handles edge cases.

(Visited 1 times, 1 visits today)