Home Education Python Program to Find the Factorial of a Number

Python Program to Find the Factorial of a Number

0
Python Program to Find the Factorial of a Number

What’s Factorial?

In easy words, if you ought to find the factorial of a positive integer, keep multiplying it with all of the positive integers lower than that number. The that you simply get is the factorial of that number. So if you ought to find the factorial of seven, multiply 7 with all positive integers lower than 7, and people numbers can be 6,5,4,3,2,1. Multiply all these numbers by 7, and the is the factorial of seven.

Formula of Factorial

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

10 Factorial

So what’s 10!? Multiply 10 with all of the positive integers that are lower than 10.
10! =10**8**6**4**2*1=3628800

Factorial of 5

To search out ‘5!’ again, do the identical process. Multiply 5 with all of the positive integers lower than 5. Those numbers can be 4,3,2,1
5!=5**3*1=120

Factorial of 0

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

Factorial of a number

Computing that is an interesting problem. Allow us to take into consideration why easy multiplication can be problematic for a pc. The reply to this lies in how the answer is implemented.

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

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

Factorial Program in Python

We’re going to undergo 3 ways wherein we are able to calculate factorial:

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

Factorial program in Python using the function

That is essentially the most straightforward method which may be used to calculate the factorial of a number. Here we’ve a module named math which accommodates several mathematical operations that may 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 whole lot of time for the while loop to execute. The above program takes a whole lot of time, let’s say infinite. The very purpose of calculating factorial is to get the lead to time; hence, this approach doesn’t 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 as much as 2956. Beyond that, it exceeds the memory and thus fails. The time taken is less when put next to the iterative approach. But this comes at the price of the space occupied.

What’s the answer to the above problem?
The issue of computing factorial has a highly repetitive structure.

To compute factorial (4), we compute f(3) once, f(2) twice, and f(1) thrice; because the number increases, the repetitions increase. Hence, the answer can be to compute the worth once and store it in an array from where it could actually be accessed the following time it’s required. Due to this fact, 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 very efficient by way of time and space complexities.

Count Trailing Zeroes in Factorial using Python

Problem Statement: Count the variety of zeroes within 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("Variety of trailing zeros", count)

Output
Enter the Number: 5
Variety of trailing zeros 1

Learn find out how to find if a string is a Palindrome.

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

Steadily asked questions

1. What’s factorial in math?

Factorial of a number, in mathematics, is the product of all positive integers lower 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 don’t exist.

2. What’s 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 are able to import a module in Python generally known as math which accommodates just about 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 assistance of Great Learning’s PGP Artificial Intelligence and Machine Learning course, and upskill today! When you’re at it, try the python course for beginners to learn more concerning the basic Python.

LEAVE A REPLY

Please enter your comment!
Please enter your name here