Factorial Program in Python: Explained with Examples
Table of Contents
- jaro education
- 24, May 2024
- 4:26 pm
Factorials can be used in several programming languages, including Python, to solve various mathematical problems. They help generate output for critical calculations quickly within a few seconds, saving time from repetitive calculations and avoiding the risk of manual calculation errors.
Factorial programs in Python have several applications in permutation, combination, data science, cryptography and more. Now, in this blog, you will learn about different techniques for finding factorials with Python programs.
What is a Factorial?
Factorials are useful concepts in mathematics and computer science. It’s a mathematical operation and is denoted with the ‘!’ symbol. You can calculate a factorial by multiplying all positive integers up to ‘n’, the given non-negative integer. Suppose you have to calculate the factorial of 3, then you should denote it as 3! The result of 3! = 1*2*3 = 6 or 3! = 3*2*1.
The factorial has these properties –
- 0! = 1
- 1! = 1
- n! = n * (n-1)!
- The factorial functions grow quickly. So, if ‘n’ incorporates a large value, then the factorial will cause an overflow of standard capacity.
- Factorial operations do not exist for negative integers.
In the Python programming language, there are several factorial applications. Some of these are –
- Probability: You have to use factorials to calculate the possible outcomes for an event using the probability theorem.
- Statistics: By using factorials, you can calculate the possible ways to arrange your data in a dataset.
- Combinatorics: You can find the possible permutations or combinations of a set of objects by using combinatorics.
- Cryptography: You can generate large prime numbers using factorials in cryptography. Large prime numbers become helpful for the encryption algorithms. For this, you can use factorial programs.
- Data science: Factorial becomes useful in Euler problems in data science.
Factorial Program in Python
A factorial program in Python helps you to calculate the factorial of a number. Now, there are different approaches to finding factorials in Python. In this section, you will learn about those different approaches. But you have to remember two things –
- Always take a positive integer as input.
- The iteration starts from 1 and ends with ‘n’ (the number you have chosen to calculate the factorial).
Now, let’s uncover the approaches to find the factorials using Python programming –
1. Using Built-in Function
You can create a factorial program in Python using the factorial function, and it is available in the Python library. The syntax for this function is –
factorial()
Here, you will learn a factorial Python program using a simple if Else Loop. The function will return the value 1 when n = 1 or 0 (as 1! = 1 and 0! = 1). Otherwise, the function will return the factorial of n. Here, we have taken the value of n = 4. So, the function will return 4 * factorial (4-1). That is 24.
So, let’s compute this coding –
# Python program to find the factorial of a number using built-in function factorial()
def factorial(n):
# single line to find factorial
return 1 if (n==1 or n==0)
else n * factorial(n – 1)
# Driver Code
num = 4
print (“Factorial of”,num,”is”, factorial(num))
Output: The factorial of 4 is 24.
2. Using Recursion
Python uses a recursion function to calculate the factorial of a number. A recursion function is one of those functions that call itself. It’s a repeated application of a process or a definition. That means the function calls itself within its body until the targeted task is completed. That’s why the function is called a recursive function, and the process is known as recursion.
Here, factorial() is a recursive function which calls itself. By calling itself, it decreases the value of x. So, it returns the value as a form of x * factorial(x-1).
# Factorial program in Python using recursion
def factorial(x):
if x == 1:
return 1
else:
# recursive call to the
function
return (x * factorial(x-1))
# You can change this value
for a different result
num = 5
# Give the input
num = int(input(“Enter a number: “))
# Call the factorial function
result = factorial(num)
print (“The factorial of”, num, “is”, result)
Output: The factorial of 5 is 120.
3. Using for Loop
In this case, you have to store the number for which you are supposed to find the factorial in the ‘num’ variable. Then, this variable initialises the factorial from 1. To enter within the ‘for loop’, the value of the number must be 1 or greater than 1. After entering into the ‘for loop’, the value of num will be iterated from 1 to n. In each iteration, the ‘for loop’ multiplies each number with the previous result. This multiplication will be continued from 1 to n numbers.
The iteration for 1 to 10 will be gone in this way –
Iteration | Factorial (factorial*i) |
---|---|
i = 1 | 1 * 1 = 1 |
i = 2 | 1* 2 = 2 |
i = 3 | 2 * 3 = 6 |
i = 4 | 6 * 4 = 24 |
i = 5 | 24 * 5 = 120 |
i = 6 | 120 * 6 = 720 |
i = 7 | 720 * 7 = 5040 |
i = 8 | 5040 * 8 = 40320 |
i = 9 | 40320 * 9 = 362880 |
i = 10 | 362880 * 10 =3628800 |
So, create the program –
# Factorial Python to find the factorial of a number using for loop
# Here, we will find the factorial of 10. Similarly, you can experiment with the code by finding factorials for other numbers
num = int (input (“Enter a number: “))
factorial = 1
if num >= 1:
# Use for loop
for i in range (1, num+1):
factorial=factorial *i
print(“Factorial of the given number is: “, factorial)
Output: The factorial of 10 is 3628800.
Otherwise, you can choose a different approach to find factorial using a ‘for loop’. In this case, first, you have to use if, elif and else statements to check if the number is positive, negative or zero. If the number is positive, then it will go through the ‘for loop’. Here, you will calculate factorial using the range().
# Python program to find the factorial of a number using a ‘for loop’.
# change the value for a different result
num = 10
# To take input from the user
#num = int(input(“Enter a number: “))
factorial = 1
# Check if the given number is positive, negative or zero
if num < 0:
print(“There is no factorial for negative numbers”)
elif num == 0:
print(“The factorial of 0 is 1”)
else:
for i in range(1,num + 1):
factorial = factorial*i
print(“The factorial of”,num,”is”,factorial)
Output: The factorial of 10 is 3628800.
4. Using While Loop
A while loop multiplies the numbers from 1 to n. Also, it follows an iteration to generate the final output. Here, you will find the factorial of 6 by using the following code –
#Factorial program in Python using while loop
def factorial(n):
result = 1
while n > 0:
result *= n
n -= 1
return result
# Driver code
number = 6
result = factorial(number)
print(“Factorial of”, number, “is”, factorial(number))
Output: The factorial of 6 is 720.
Otherwise, you can compute the program using if, elif, else and while loop. Here, first, you have to check if the target number is positive, negative or zero using the if and elif loops. Then, use else and while loops to find the factorial.
# Python program to find the factorial of a given number
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
# Driver Code
num = 6
print(“Factorial of”,num,”is”, factorial(num))
Output: The factorial of 6 is 720.
*ximera.osu.edu
5. Using Math Module – Factorial()
The math module in Python allows access to the in-built mathematical functions which are defined by the standard of C programming language. But remember that this module can’t support complex numbers.
Now, to compute code for factorial in Python, you need to use this syntax –
math.factorial (n)
Here, this function returns ‘n’ as a form of integer. If ‘n’ is a non-integer or negative number, then the math.factorial function will generate a ValueError.
#Factorial using math module with Python 3
import math
def factorial(n):
return(math.factorial(n))
# Driver Code
num = 7
print(“Factorial of”, num, “is”, factorial(num))
Output: The factorial of 7 is 5040.
Final Words
Hopefully, you have learned the different techniques for finding factorials in Python and their applications. These techniques help you efficiently compute factorials of integers. Factorials are a critical part of computer science, and you will be able to learn more about them through the Online M.Sc. (Computer Applications) – Symbiosis School for Online and Digital Learning (SSODL).
To learn more about the course and all its details, contact Jaro Education.
Frequently Asked Questions
First, factorials for negative numbers don’t exist, so calculating them is impossible. Now, if you try to compute a factorial program in Python for a negative number, then the code will generate an output error.
In Python programming, when there is a loop such as ‘for loop’ and ‘while loop’, it is known as an iterative approach. But, when a function calls itself to produce a target result, it is called a recursive approach. So, iteration and recursion are completely different approaches in Python. Also, the computing code for factorial in Python is different for each approach.
The time complexity of a recursive factorial program in Python is O(n). This time, complexity happens when the factorial grows based on the size of the given number.
Factorials are supported for positive integers. Thus, you can’t calculate the factorial of the decimal numbers in Python. If you try to calculate the factorial with other types of numbers like decimal, octal or binary, then that is impossible. Again, if you’re using other data types in Python like float, string and complex, then you have to convert the type into an integer. And, you can calculate the factorial.
Yes, you can optimise the performance of Python factorial programs using memorisation. In this case, you can store the previously computed factorials for future usage. It will help you avoid redundancy in the calculation.
You can review the performance of your factorial code in Python using the Timeit module. It helps you measure the execution time of your Python code using a command-line interface as well as a Python interface.