Home Icon Home Resource Centre Factorial Program In Python | 8 Ways & Complexity Analysis (+Codes)

Factorial Program In Python | 8 Ways & Complexity Analysis (+Codes)

The factorial of a number is the product of all preceding non-negative integers and itself in descending order. Ways to find the factorial of a number in Python include loops, recursion, built-in functions, etc.
Shivani Goyal
Schedule Icon 0 min read
Factorial Program In Python | 8 Ways & Complexity Analysis (+Codes)
Schedule Icon 0 min read

Table of content: 

  • What Is A Factorial?
  • Algorithm Of Program To Find Factorial Of A Number In Python
  • Pseudocode For Factorial Program in Python
  • Factorial Program In Python Using For Loop
  • Factorial Program In Python Using Recursion
  • Factorial Program In Python Using While Loop
  • Factorial Program In Python Using If-Else Statement
  • The math Module | Factorial Program In Python Using Built-In Factorial() Function
  • Python Program to Find Factorial of a Number Using Ternary Operator(One Line Solution)
  • Python Program For Factorial Using Prime Factorization Method
  • NumPy Module | Factorial Program In Python Using numpy.prod() Function
  • Complexity Analysis Of Factorial Programs In Python
  • Conclusion
  • Frequently Asked Questions
expand icon

Factorial is a mathematical operation representing the product of all positive integers up to a given number. It is denoted by an exclamation mark (!). For example, the factorial of 5 (denoted as 5!) is calculated as 5 × 4 × 3 × 2 × 1 = 120. Factorials are widely used in permutations, combinations, and other mathematical computations.

There are many techniques you can use to write a factorial program in Python language. These include the iterative approach, recursion, and other optimized approaches using libraries like math and NumPy. In this article, we will explore various methods to calculate factorials in Python, starting with the basics.

What Is A Factorial?

The process of calculating the factorial of a number involves multiplying a sequence of descending positive integers from the respective number. That is, the factorial of a non-negative integer n is the product of all positive integers less than or equal to

n!=n×(n−1)×(n−2)×…×1
For n=0, by convention:
0!=1

Why 0!=1? The definition of 0!=1 is a convention that simplifies various mathematical expressions, particularly in combinatorics and series expansions. This definition ensures that formulas and equations work correctly even when n=0.

Algorithm Of Program To Find Factorial Of A Number In Python

Flowchart of algorithm to write the factorial program in Python language.

The algorithm to find the factorial of a number can be implemented in various ways, but a common and straightforward method is to use an iterative approach. Below are the steps (as also illustrated in the flowchart) to find the factorial of a number in Python:

  1. Initialize the Result: Start by initialising a variable, say the result with the value 1. This will store the final factorial value.
  2. Iterate Through Numbers: Use a loop to iterate through all numbers from 1 to the given number n.
  3. Multiply and Update Result: In each iteration, multiply the current value of the result by the current number in the loop.
  4. Return the Result: After the loop completes, the variable result will hold the factorial of the number n.

Pseudocode For Factorial Program in Python

The pseudocode provides a high-level description of the algorithm without the syntax of a specific programming language. Below is the pseudocode for finding the factorial of a number using an iterative approach:

function factorial(n):
# Step 1: We begin by initializing the variable result with value 1.
#It will be the accumulator of products
result = 1

# Step 2: We create a for loop to iterate over the range 1 to n (inclusive) 
for i from 1 to n:
# Step 3: Multiply the result by the current number and update its value
result = result * i
# Step 4: When loop completes iteration, the result variable contains the factorial, which it returns
return result

Factorial Program In Python Using For Loop

To find the factorial of a number using a for loop in Python, we start by initializing a result variable to 1. This variable will store the cumulative product of numbers from 1 to the given number . We then use a for loop to iterate through each integer from 1 to , multiplying the current value of the result by the loop counter in each iteration.

This iterative multiplication effectively computes the factorial by successively updating the result. Once the loop completes, the result variable contains the factorial of . The Python program example below illustrates this approach to calculate and print the factorial.

Code Example:

Output:

The factorial of 6 is 720

Explanation:

In the Python code example-

  1. We define a function named factorial_iterative, which calculates the factorial of a given number n iteratively.
  2. We first initialize a variable result inside the function with the value 1. This variable will hold the final factorial value.
  3. Then, we use a for loop to iterate over the range from 1 to n inclusive. In each iteration, we multiply the result variable by the current value of i (the loop variable).
  4. After the loop completes iterations, the variable result contains the factorial of n, which the function returns.
  5. In the main part, we initialize a variable number with the value 6.
  6. Next, we call the factorial_iterative() function inside the print() function, passing the variable number as an argument.
  7. This function call and print() function displays the factorial of number with a descriptive message.

Time Complexity: O(n)
Space Complexity: O(1)

Factorial Program In Python Using Recursion

Flow diagram showing the recursive approach to find factorial of a number in Python.

Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem. To find the factorial of a number using recursion, we define a function that calls itself with a smaller argument until it reaches the base case, which is when the argument becomes 0.

In the recursive approach to find the factorial of a number, we define:

  1. Base Case: The factorial of 0 is defined as 1.
  2. Recursive Case: For any other number n, the factorial is calculated as n×(n−1)

Syntax for Recursive Function in Python:

def factorial_recursive(n):
# Base case
if n == 0:
return 1
# Recursive step
else:
return n * factorial_recursive(n - 1)

Here,

  • The def keyword marks the beginning of the function with the name factorial_recursive and takes a parameter n.
  • The if-else statement condition n==0 uses the relational operator to check if n is equal to 0. This is the base case. 
  • The return statements stipulate what the function will return given if the condition is met.
  • The expression n*factorial_recursive(n-1) is the recursive step, which returns n multiplied by the result of calling itself with n - 1, reducing the problem size with each call until reaching the base case.

Let's look at a simple Python program example to understand how to use recursion for factorial calculations. 

Code Example:

Output:

The factorial of 5 is 120

Explanation:

In the simple Python code example-

  1. We define a function named factorial_recursive that takes n as a parameter and calculates its factorial recursively.
  2. In the function, we have an if-else statement that defines the base case and the recursive step.
  3. The if condition (base case) checks if n equals 0, i.e., n==0. If true, the function returns 1. This is because the factorial of 0 is defined as 1.
  4. If the condition is false, we proceed to the recursive step where the function returns the product of n and the factorial of n-1, achieved by calling factorial_recursive(n - 1).
  5. The function keeps calling itself with decreasing values of n until it reaches the base case.
  6. Once the base case is reached, the function returns values back up the call stack, each time multiplying n with the result of the factorial of n-1.
  7. In the main segment of the code, we initialize a variable n with the value 5 and then call the factorial_recursive function.
  8. The function calculates the factorial of the number 5, which we then print using the print() function.

Time Complexity: O(n)
Space Complexity: O(n)

Factorial Program In Python Using While Loop

To find the factorial of a number using a while loop in Python, we initialize a result variable to 1 to store the cumulative product of the numbers. We also initialize a counter variable to 1, which will be used to iterate through the numbers from 1 to the given number .

Using a while loop, we repeatedly multiply the result by the counter variable and then increment the counter until it exceeds n. The example Python program below showcases this approach.

Code Example:

Output:

The factorial of 5 is 120

Explanation:

In the example Python code-

  1. We define a function named factorial_while that takes a parameter n and calculates its factorial using a while loop.
  2. Inside the function, we initialize variables result and i to value 1. The former will store the final factorial value and the latter will serve as a counter for the loop.
  3. Then, we use a while loop that continues as long as i is less than or equal to n.
  4. In every iteration, we multiply the result variable by the current value of i, and then increment i by 1 to move to the next number.
  5. When the loop completes its iterations, the result variable will contain the factorial of n, which the function returns.
  6. In the main part, we initialize a variable number with the value 5 and call the factorial_while() function, passing the number as an argument.
  7. This function calculates the factorial, which we print using the print() function and f-strings.

Time Complexity: O(n)
Space Complexity: O(1)

Factorial Program In Python Using If-Else Statement

The if-else statement helps execute one of the two code blocks depending upon whether the if-condition is met. Using an if-else statement to find the factorial of a number typically involves a recursive approach.

In this method, the function calls itself with a decremented value of the original number until it reaches the base case. The base case is when the input number is zero, and the factorial of zero is defined as one. Each recursive call multiplies the current number by the result of the factorial of the previous number. The Python program sample below illustrates this approach for a better understanding.

Code Example:

Output:

The factorial of 4 is 24

Explanation:

In the Python code sample-

  1. We begin by defining a function named factorial_recursive , that takes a number n as parameter and calculates its factorial recursively.
  2. Inside the function, we use an if-else statement to check the base case. In case the if-condition n==0 is true, the function returns 1 because the factorial of 0 is defined as 1.
  3. If the condition is false, we proceed to the recursive step. Here, we return the product of n and the factorial of n-1, achieved by calling factorial_recursive(n - 1).
  4. The function keeps calling itself with decreasing values of n until it reaches the base case where n is 0.
  5. Once the base case is reached, the function returns values back up the call stack, each time multiplying n with the result of the factorial of n-1.
  6. For the example usage in the main part, we initialize a variable number with the value 4.
  7. Then, we call the factorial_recursive() function that calculates the factorial of the number 4.
  8. We print this result with a descriptive string message using the print() function.

Time Complexity: O(n)
Space Complexity: O(n)

The math Module | Factorial Program In Python Using Built-In Factorial() Function

The Math library in Python contains a built-in function for computing factorials called the factorial() function. Naturally, in this method we must import the math module and use the function math.factorial().

This is one of the most straightforward and efficient ways to calculate the factorial of a number, as it abstracts away the implementation details and is highly optimized. The sample Python program presents how this approach works.

Code Example:

Output:

The factorial of 5 is 120

Explanation:

We begin the sample Python code by importing the math module, which provides access to mathematical functions. Then-

  1. We define a function named factorial_builtin that takes a number n as a parameter and calculates its factorial using the built-in math.factorial function.
  2. Inside the function, we simply return the result of calling the math.factorial() function passing the parameter n as an argument.
  3. The math.factorial function handles the calculation of the factorial internally.
  4. To showcase, in the main part, we initialize a variable number with value 5 and then call the factorial_builtin() function.
  5. We then print the factorial calculated to the output console using the print() function.

Time Complexity: O(n)
Space Complexity: O(1)

Python Program to Find Factorial of a Number Using Ternary Operator(One Line Solution)

In Python, a ternary operator provides a way to condense an if-else statement into a single line. This technique can be utilized to create a concise recursive function for calculating the factorial of a number. The ternary operator will handle the base case and the recursive step within one line of code. The syntax for this operator is given below, followed by a basic Python program example.

Syntax:

def factorial_ternary(n):
return 1 if n == 0 else n * factorial_ternary(n - 1)

Here,

  • def factorial_ternary(n):: Defines a function named factorial_ternary with an input parameter n.
  • return 1 if n == 0 else n * factorial_ternary(n - 1): Uses the ternary operator to return 1 if n is equal to 0; otherwise, returns n multiplied by the result of factorial_ternary(n - 1).

Code Example:

Output:

The factorial of 3 is 6

Explanation:

In the basic Python code example-

  1. We define a function named factorial_ternary, which calculates the factorial of the parameter number n using a ternary operator and recursion.
  2. In the function, we use the ternary operator to check the base condition n==0. If this is true, then the ternary operator returns 1.
  3. If the condition is false, it returns n multiplied by the factorial of n-1, which is achieved by calling factorial_ternary(n - 1).
  4. This recursive approach continues until it reaches the base case where n is 0.
  5. Once the base case is reached, the function starts returning values back up the call stack, each time multiplying n with the result of the factorial of n-1.
  6. In the main part, we initialize a variable number with the value 3 and then call the factorial_ternary() function.
  7. The factorial is printed to the console using f-strings inside a print() function.

Time Complexity: O(n)
Space Complexity: O(n)

Python Program For Factorial Using Prime Factorization Method

Image example of the factorisation process when writing factorial program in Python.

The prime factorization method for finding the factorial of a number involves breaking down the number into its prime factors and then counting the occurrences of each prime factor. Since factorial involves multiplying consecutive numbers, the prime factors of the factorial can be derived from the prime numbers less than or equal to the given number.

We can write a factorial program in Python by counting the occurrences of each prime factor in the range [2, n]. 

Code Example:

Output:

The factorial of 5 is 120

Explanation:

In this sample factorial program in Python-

  1. We begin by defining a function named factorial_prime_factorization, which calculates the factorial of a given number n using prime factorization.
  2. Inside this function, there's another nested function named prime_factors that computes the prime factors of a given number.
    • Inside, we initialize an empty dictionary named factors to store the prime factors and their respective counts.
    • We then set a divisor to 2 and use a while loop that iterates until the square of the divisor is less than or equal to the input number.
    • During each iteration, an if-else statement checks if the number is divisible by the divisor. If it is, we update the factors dictionary accordingly and reduce the number by dividing it by the divisor.
    • If the number is not divisible by the current divisor, we increment the divisor by 1.
    • After the loop, we have another if-statement, which checks if the remaining number is greater than 1. If it is, we update the factors dictionary accordingly.
    • The prime_factors function returns the dictionary containing the prime factors and their counts.
  3. Moving back to the outer function, we create another empty dictionary prime_factors_count to store the prime factors and their respective counts for all numbers from 2 to n.
  4. Then, we use a set of nested for loops to iterate through the range from 2 to n, where the outer loop computes the prime factors for each number using the prime_factors() function and the inner loop updates prime_factors_count accordingly.
  5. Next, we initialize a variable factorial with the value 1 and then use a for loop to calculate the factorial using the prime factors stored in prime_factors_count.
  6. The loop iterates through the items of prime_factors_count, multiplying the factorial by each prime factor raised to its respective count (using the exponent operator).
  7. Finally, the function returns the calculated factorial stored inside the variable factorial.
  8. Lastly, we initialize a variable number with the value 5 and calculate and print its factorial using the factorial_prime_factorization() and print() functions. 

Time Complexity: O(n sqrt{n})
Space Complexity: O(n log n)

NumPy Module | Factorial Program In Python Using numpy.prod() Function

The NumPy library in Python offers multiple efficient numerical operations on arrays, etc. We can leverage its capabilities to compute the factorial of a number using the numpy.prod() function. This method involves creating an array containing the integers from 1 to the given number and then using the numpy.prod() function to calculate their product.

The numpy.prod() function efficiently computes the product of array elements along a specified axis, providing a succinct and optimized solution for calculating factorials. Look at the simple Python example below, which illustrates this approach. 

Code Example:

Output:

The factorial of 5 is 120

Explanation:

In the Python example code, we first import the NumPy library as np, which provides support for mathematical operations on arrays and matrices.

  1. We then define a function named factorial_numpy(), which calculates the factorial of a given number n using NumPy.
  2. Inside the function, we create an array named numbers containing integers from 1 to n using the arrange() function, i.e., np.arange(1, n + 1).
  3. Next, we use the np.prod() function from NumPy to calculate the product of all elements in the numbers array, which effectively computes the factorial.
  4. The result is stored in a variable named factorial, which the function then returns.
  5. Lastly, we initialize a variable called number with the value 5 and calculate its factorial using the factorial_numpy() function.

Time Complexity: O(n)
Space Complexity: O(n)

Complexity Analysis Of Factorial Programs In Python

Here is a detailed complexity analysis of the different methods used to write a factorial program in Python programming language:

Method Time Complexity Space Complexity
math.factorial() O(n) O(1)
While Loop O(n) O(1)
For Loop O(n) O(1)
Recursive Approach O(n) O(n)
numpy.prod() O(n) O(n)

Ternary Operator(One Line Solution)

O(n) O(n)
If-else Statement O(n) O(n)
Prime Factorization O(n sqrt{n}) O(n log n)

Conclusion

Factorial of a number is the product of all preceding integers and the respective number itself. There are many ways to write a factorial program in Python, including iterative loops, recursive functions, and built-in functions like math.factorial() and numpy.prod(). Python provides flexibility to suit different needs. Factors such as input size, performance requirements, and code readability guide the selection of the most appropriate method. Despite the diversity of approaches, the factorial operation remains a foundational tool in mathematics and programming, supporting various algorithms and computations in Python applications.

Frequently Asked Questions

Q. What is a factorial, and why is it used?

A factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. Factorials are commonly used in mathematics and computer science for various purposes, such as combinatorial problems, probability calculations, and algorithmic solutions.

Q. What are the limitations of using recursion to calculate factorials?

Recursive methods for calculating factorials can be elegant and concise, but they may have limitations, particularly for large inputs. Recursive functions rely on the call stack, and deep recursion may lead to stack overflow errors, especially with large input values. As a result, iterative or built-in function-based approaches may be preferred when writing a factorial program in Python language in terms of efficiency and scalability.

Q. In what scenarios should I use built-in functions like math.factorial() or libraries like NumPy for factorial calculations?

Inbuilt functions like math.factorial() and libraries like NumPy offer optimized implementations for factorial calculations, suitable for general-purpose numerical computing tasks. They are particularly useful when working with large numbers or performing computations on arrays or matrices containing factorial-related operations. These functions provide efficient, reliable, and well-tested solutions, making them suitable for a wide range of applications. 

Q. How can I handle large factorial results in Python?

Python's integers are of arbitrary precision, meaning they can grow as large as the memory allows. However, when working with extremely large numbers, performance and memory usage can become concerns. You can use libraries like math module or NumPy, which are optimized for large-number computations. Additionally, you can consider using the gmpy2 library for specialised applications, which provides enhanced performance for large integer arithmetic. 

Q. Are there any optimizations for computing factorials efficiently?

Yes, there are optimizations that can improve the efficiency of calculations in a factorial program in Python. For example, memoization in recursive functions can reduce redundant computations by caching previously calculated results. Additionally, leveraging mathematical properties of factorials, such as prime factorization, can lead to more efficient algorithms for computing factorials, especially for large inputs like when writing a factorial program in Python.

You might also be interested in reading the following:

  1. Python Logical Operators, Short-Circuiting & More (With Examples)
  2. Convert Int To String In Python | Learn 6 Methods With Examples
  3. Python Bitwise Operators | Positive & Negative Numbers (+Examples)
  4. Python String.Replace() And 8 Other Ways Explained (+Examples)
  5. How To Reverse A String In Python? 10 Easy Ways With Examples
Edited by
Shivani Goyal
Manager, Content

An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.

Tags:
Python programming language Engineering Computer Science

Comments

Add comment
No comments Image No comments added Add comment
Powered By Unstop Logo
Best Viewed in Chrome, Opera, Mozilla, EDGE & Safari. Copyright © 2024 FLIVE Consulting Pvt Ltd - All rights reserved.