Browse by Domains

Python Program to Find the Factorial of a Number

What is Factorial?

In simple words, if you want to find the factorial of a positive integer, keep multiplying it with all the positive integers less than that number. The final result that you get is the factorial of that number. So if you want to find the factorial of 7, multiply 7 with all positive integers less than 7, and those numbers would be 6,5,4,3,2,1. Multiply all these numbers by 7, and the final result is the factorial of 7.

If you are looking to build your expertise in Python factorial program, consider getting certified. This free course on Factorial Program in Python offers you complete guidance on the subject and also a certificate on completion which is sure to make your CV stand out.

Formula of Factorial

Factorial of a number is denoted by n! is the product of all positive integers less than or equal to n:
n! = n*(n-1)*(n-2)*…..3*2*1

10 Factorial

So what is 10!? Multiply 10 with all the positive integers which are less than 10.
10! =10*9*8*7*6*5*4*3*2*1=3628800

Factorial of 5

To find ‘5!’ again, do the same process. Multiply 5 with all the positive integers less than 5. Those numbers would be 4,3,2,1
5!=5*4*3*2*1=120

Factorial of 0

Since 0 is not a positive integer, as per convention, the factorial of 0 is defined to be itself.
0!=1

Factorial program in python
Factorial of a number

Computing this is an interesting problem. Let us think about why simple multiplication would be problematic for a computer. The answer to this lies in how the solution is implemented.

1! = 1
2! = 2
5! = 120
10! = 3628800
20! = 2432902008176640000
30! = 9.332621544394418e+157

The exponential rise in the values shows us that factorial is an exponential function, and the time taken to compute it would take exponential time.

Factorial Program in Python

We are going to go through 3 ways in which we can calculate factorial:

  • Using a function from the math module
  • Iterative approach(Using for loop)
  • Recursive approach

Factorial program in Python using the function

This is the most straightforward method which can be used to calculate the factorial of a number. Here we have a module named math which contains several mathematical operations that can be easily performed using the module.

import math
num=int(input("Enter the number: "))
print("factorial of ",num," (function): ",end="")
print(math.factorial(num))

TEST THE CODE

Input – Enter the number: 4
Output – Factorial of 4 (function):24

Factorial program in python using for loop

def iter_factorial(n):
    factorial=1
    n = input("Enter a number: ")
    factorial = 1
    if int(n) >= 1:
        for i in range (1,int(n)+1):
            factorial = factorial * i
        return factorial
  
num=int(input("Enter the number: "))

print("factorial of ",num," (iterative): ",end="")
print(iter_factorial(num))

TEST THE CODE

Input – Enter the number: 5
Output – Factorial of 5 (iterative) : 120

Consider the iterative program. It takes a lot of time for the while loop to execute. The above program takes a lot of time, let’s say infinite. The very purpose of calculating factorial is to get the result in time; hence, this approach does not work for huge numbers.

Factorial program in Python using recursion

def recur_factorial(n):
    """Function to return the factorial
    of a number using recursion"""
    if n == 1:
        return n
    else:
        return n*recur_factorial(n-1)

num=int(input("Enter the number: "))

print("factorial of ",num," (recursive): ",end="")
print(recur_factorial(num))

TEST THE CODE

Input – Input – Enter the number : 4
Output – Factorial of 5 (recursive) : 24

On a 16GB RAM computer, the above program could compute factorial values up to 2956. Beyond that, it exceeds the memory and thus fails. The time taken is less when compared to the iterative approach. But this comes at the cost of the space occupied.

What is the solution to the above problem?
The problem of computing factorial has a highly repetitive structure.

To compute factorial (4), we compute f(3) once, f(2) twice, and f(1) thrice; as the number increases, the repetitions increase. Hence, the solution would be to compute the value once and store it in an array from where it can be accessed the next time it is required. Therefore, we use dynamic programming in such cases. The conditions for implementing dynamic programming are

  1. Overlapping sub-problems
  2. optimal substructure 

Consider the modification to the above code as follows:

def DPfact(N):
    arr={}
    if N in arr:
        return arr[N]
    elif N == 0 or N == 1:
        return 1
        arr[N] = 1
    else:
        factorial = N*DPfact(N - 1)
        arr[N] = factorial
    return factorial
    
num=int(input("Enter the number: "))

print("factorial of ",num," (dynamic): ",end="")
print(DPfact(num))

TEST THE CODE

Input – Enter the number: 6
Output – factorial of 6 (dynamic) : 720

A dynamic programming solution is highly efficient in terms of time and space complexities.

Count Trailing Zeroes in Factorial using Python

Problem Statement: Count the number of zeroes in the factorial of a number using Python

num=int(input("Enter the number: "))
  
# Initialize result 
count = 0
# Keep dividing n by 
# powers of 5 and 
# update Count 
temp = 5
while (num / temp>= 1):
    count += int(num / temp) 
    temp *= 5

# Driver program  
print("Number of trailing zeros", count)

Output
Enter the Number: 5
Number of trailing zeros 1

Learn how to find if a string is a Palindrome.

Learn how to print the Fibonacci Series in Python. Also, learn artificial intelligence online with the help of this AI Course.

Frequently asked questions

1. What is factorial in math?

Factorial of a number, in mathematics, is the product of all positive integers less than or equal to a given positive number and denoted by that number and an exclamation point. Thus, factorial seven is written 4! meaning 1 × 2 × 3 × 4, equal to 24. Factorial zero is defined as equal to 1. The factorial of Real and Negative numbers do not exist.

2. What is the formula of factorial?

To calculate the factorial of a number N, use this formula:
Factorial=1 x 2 x 3 x…x N-1 x N

3. Is there a factorial function in Python?

Yes, we can import a module in Python known as math which contains almost all mathematical functions. To calculate factorial with a function, here is the code:

import math
num=int(input(“Enter the number: “))
print(“factorial of “,num,” (function): “,end=””)
print(math.factorial(num))

Found this blog interesting? Learn Artificial Intelligence Online with the help of Great Learning’s PGP Artificial Intelligence and Machine Learning course, and upskill today! While you’re at it, check out the python course for beginners to learn more about the basic Python.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top