Saturday, January 4, 2025

Factorial of a number

 

Recursive Approach

def factorial(n):
if n == 0 or n == 1:
return 1 ;
else:
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

Iterative Approach

def factorial(n):
    result = 1
    for i in range(1, n + 1):    -- for and return statements are in same indent
      result *= i
    return result

print(factorial(5))  # Output: 120

No comments:

Post a Comment