Thursday, July 25, 2024

Nitheen Kumar

Write a Program to calculate the factorial of a number in Python

Calculating the factorial of a number involves multiplying all integers from 1 up to that number. Here's a Python program that calculates the factorial of a given number using both iterative and recursive approaches:

  1. Iterative Approach:
def factorial_iterative(n):
factorial = 1 for i in range(1, n + 1): factorial *= i return factorial
  1. Recursive Approach:
def factorial_recursive(n):
# Base case: factorial of 0 or 1 is 1 if n == 0 or n == 1: return 1 # Recursive case: factorial of n is n times factorial of (n-1) else: return n * factorial_recursive(n - 1)

Example Usage:

You can test the factorial functions with different values of n:

num = 5
# Using iterative approach factorial_iter = factorial_iterative(num) print(f"Factorial of {num} (iterative): {factorial_iter}") # Using recursive approach factorial_rec = factorial_recursive(num) print(f"Factorial of {num} (recursive): {factorial_rec}")

Write a Program to calculate the factorial of a number in Python

Explanation:

  • Iterative Approach (factorial_iterative function):

    • Initialize factorial to 1.
    • Use a loop to multiply factorial by each integer from 1 to n.
    • Return the final value of factorial.
  • Recursive Approach (factorial_recursive function):

    • Base case: if n is 0 or 1, return 1 (since 0! = 1 and 1! = 1).
    • Recursive case: multiply n by the factorial of (n-1) until n reaches the base case.

Both approaches are valid for calculating the factorial of a number. The recursive approach is more concise but might encounter recursion depth limitations for very large values of n. The iterative approach avoids this issue and is generally more straightforward for this particular problem.

Subscribe to get more Posts :