Python Program to Find Factorial of a Number


Python Program to Find Factorial of a Number

Factorial of a number can be calculated in various ways. These include using a for loop, a recursive function, or a while loop. Each method has its advantages, and this tutorial covers all three approaches along with additional cases.

Factorial is commonly used in mathematical computations, such as permutations, combinations, and series expansions.


Problem Statement - Factorial of a Number

Factorial of a number n is given by:

n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1

For example:

0! = 1
1! = 1
2! = 2 * 1 = 2
3! = 3 * 2 * 1 = 6
4! = 4 * 3 * 2 * 1 = 24

Examples

1. Factorial using For Loop and Range

In this example, we use a for loop to calculate the factorial by iterating through a range from 1 to n+1, multiplying elements along the way.

Python Program

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

n = 4
result = factorial(n)
print(n, '! = ', result, sep="")

Explanation:

  1. The range range(1, n+1) generates numbers from 1 to n.
  2. On each iteration, the current number i is multiplied with result.
  3. After the loop, result contains the factorial of n.

Output:

4! = 24

2. Factorial using Recursive Function

Recursion allows a function to call itself to compute factorial, but it is less efficient for larger numbers due to Python's recursion limit.

Python Program

# Recursive function to find factorial
def factorial(n):
    if n < 0:
        raise ValueError('Factorial is not defined for negative numbers.')
    elif n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

# Test the function
n = 5
result = factorial(n)
print(n, '! = ', result, sep="")

Explanation:

  1. The base cases n == 0 and n == 1 return 1.
  2. For other values, the function calls itself with n-1 and multiplies n with the result of the recursive call.
  3. The recursion terminates once it reaches the base case.

Output:

5! = 120

3. Factorial using While Loop

Using a while loop, the factorial is calculated by iteratively multiplying numbers up to n.

Python Program

def factorial(n):
    if n < 0:
        raise ValueError('Factorial is not defined for negative numbers.')
    result = 1
    i = 1
    while i <= n:
        result *= i
        i += 1
    return result

n = 6
result = factorial(n)
print(n, '! = ', result, sep="")

Explanation:

  1. Initialize result to 1 and i to 1.
  2. In the while loop, multiply result with i, then increment i.
  3. Stop the loop when i exceeds n.

Output:

6! = 720

4. Factorial using Math Library

Python's math library provides a built-in function for calculating factorial.

Python Program

import math

n = 7
result = math.factorial(n)
print(n, '! = ', result, sep="")

Explanation:

  1. Import the math module.
  2. Use math.factorial(n) to compute the factorial of n.

Output:

7! = 5040

5. Factorial of Large Numbers

This example demonstrates calculating factorials for large numbers efficiently.

Python Program

import math

n = 100
result = math.factorial(n)
print(f"The factorial of {n} has {len(str(result))} digits.")

Explanation:

  1. The math.factorial() method handles large integers efficiently.
  2. The length of the result's string gives the number of digits in the factorial.

Output:

The factorial of 100 has 158 digits.

YouTube Video

https://youtu.be/mG0AvSGdOEo?si=ABoQdiRMSv8rKEiF

Summary

In this tutorial, we covered different methods to calculate the factorial of a number:

  • Using a for loop
  • Using recursion
  • Using a while loop
  • Using Python's built-in math library
  • Handling large numbers efficiently

Each method has its use case depending on the problem requirements. For large numbers, using the math.factorial() function is recommended for efficiency.


Python Libraries