11
JulFactorial Calculator in Python
The factorial calculator in Python is a common programming exercise for beginners and professionals alike. It involves calculating the factorial of a number, which is the product of all positive integers up to that number.
What is factorial?
The factorial of a number is the multiplication of all the numbers between 1 and the number itself. It is a mathematical operation written like this: n!. It's a positive integer. Factorial is not defined for negative numbers.
For example, the factorial of 3 is 3! (= 1 × 2 x 3).
Read More: Top 50 Python Interview Questions and Answers |
How to calculate the factorial of a number in Python?
1. Using While Loop/Iterative approach
def factorial(n):
if n < 0:
print("Sorry, factorial is undefined for negative numbers")
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
num = 8
print("Factorial of",num,"is",
factorial(num))
In the above code, we check if the number is negative, zero, or positive using the if...elif...else statement. If the number is positive, we use the while loop in python to calculate the factorial.
iteration | fact*i (returned value) |
1 | 8*1=8 |
2 | 8*7=56 |
3 | 56*6=336 |
4 | 336*5=1680 |
5 | 1680*4=6720 |
6 | 6720*3=20160 |
7 | 20160*2=40320 |
8 | 40320*1=40320 |
Output
Factorial of 8 is 40320
Explanation:
- If n is negative, it prints an error message (factorials are undefined for negatives).
- If n is 0 or 1, it returns 1 (by definition of factorial).
- Otherwise, it uses a while loop to multiply n down to 1 to compute the factorial.
Time Complexity:O(n)
- Because the loop runs from n down to 1, doing a constant-time multiplication at each step.
Space Complexity: O(1)
- It uses only a constant amount of extra space (fact, n), regardless of the input size.
2. Using Recursion
def factorial(n):
# single line to find factorial
return 1 if (n==1 or n==0) else n * factorial(n - 1)
# Driver Code
num = 5
print("Factorial of",num,"is",factorial(num))
In the above code, factorial() is a recursive function that calls itself. Here, the function will recursively call itself by decreasing the value of the num.
Output
Factorial of 8 is 40320
Read More: Recursion in Data Structures |
Explanation:
- The function calculates the factorial of a number using recursion.
- If the input n is 0 or 1, it directly returns 1 (this is the base case).
- For any other positive integer n, the function calls itself with n - 1.
- The result is calculated by multiplying n by the factorial of n - 1, building up until the base case is reached.
- This continues until the recursive calls unwind and return the final result.
Time Complexity: O(n)
- The function calls itself n times (from n down to 1), doing a constant-time multiplication at each step.
Space Complexity: O(n)
- Each recursive call consumes stack space.
So for input n, there are n function calls on the call stack, leading to linear space usage.
3. Using One line Solution (Using Ternary operator)
def factorial(n):
# single line to find factorial
return 1 if (n==1 or n==0) else n * factorial(n - 1)
num = 8
print ("Factorial of",num,"is",
factorial(num))
Output
Factorial of 8 is 40320
Read More: What are Operators in Python? |
4. Using Function
import math
def factorial(n):
return(math.factorial(n))
num = 8
print("Factorial of", num, "is",
factorial(num))
In the above code, we've used the math module that contains the math.factorial() function to calculate the factorial of any given number.
Output
Factorial of 8 is 40320
Read More: Python Functions - A Complete Guide |
Explanation (No Code):
- This version imports Python's math module.
- It uses math.factorial(n) to compute the factorial of n.
- The factorial() function is simply a wrapper around math.factorial().
Time Complexity: O(n)
- Internally, math.factorial() still performs a loop or efficient multiplication strategy (like binary splitting), which is at least linear in nature.
Space Complexity: O(1)
- Since it’s written in C, it’s memory-efficient and does not use Python's call stack.
- It uses constant space from the perspective of Python code (no recursion, no large data structures).
5. Using numpy.prod
import numpy
num=8
fact=numpy.prod([i for i in range(1,num+1)])
print("Factorial of", num, "is",
fact)
In the above code, we've used the numpy module that contains the numpy.prod() function to calculate the factorial of any given number.
Output
Factorial of 8 is 40320
Explanation:
- The code uses NumPy's prod() function to compute the product of a list of numbers from 1 to num (inclusive).
- [i for i in range(1, num+1)] creates a list of numbers from 1 to num.
- numpy.prod() multiplies all elements in the list together to return the factorial.
- This is an iterative approach but leverages NumPy's optimized internal functions.
Time Complexity: O(n)
- Creating the list takes O(n).
- numpy.prod() iterates over n elements to compute the product → O(n).
Space Complexity: O(n)
- The list [1, 2, ..., n] takes O(n) space.
- However, if NumPy is given an array instead of a list generator, it can be more memory-efficient.
6. Using the Prime Factorization Method
def primeFactors(n):
factors = {}
i = 2
while i*i <= n:
while n % i == 0:
if i not in factors:
factors[i] = 0
factors[i] += 1
n //= i
i += 1
if n > 1:
if n not in factors:
factors[n] = 0
factors[n] += 1
return factors
# Function to find factorial of a number
def factorial(n):
result = 1
for i in range(2, n+1):
factors = primeFactors(i)
for p in factors:
result *= p ** factors[p]
return result
num = 8
print("Factorial of", num, "is", factorial(num))
Output
Factorial of 8 is 40320
Explanation (No Code):
primeFactors(n) function:
- Finds the prime factorization of a number n.
- Uses trial division from i = 2 up to √n to check if i divides n.
- Stores each prime factor and its exponent in a dictionary.
- IIf n is still greater than 1 after the loop, it’s a prime and added to the dictionary.
factorial(n) function:
- Computes the factorial of n by multiplying the prime factorizations of all integers from 2 to n.
- For each i in 2 to n:
- Gets the prime factors using primeFactors(i).
- Multiplies the result by p ** exponent for all prime factors p.
Time Complexity:
- primeFactors(i) takes up to O(√i) time.
- Running it from 2 to n gives:
- Total time: O(n√n) in the worst case.
Space Complexity:
- Space for the factors dictionary during each iteration is O(log n) (since the number of distinct prime factors of n is bounded by log n).
- Total space: O(1) extra (no persistent storage of all factorizations).
7. Using For Loop
The for loop iteratively multiplies numbers in a sequence. Here’s how to calculate the factorial of a number using a for loop:
def factorial_for_loop(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
Read More: |
Explanation (No Code):
- The function calculates the factorial of n using a simple for loop.
- It initializes a variable result to 1.
- Iterates from 1 to n (inclusive), multiplying result by each i.
- After the loop ends, result holds the value of n!.
Time Complexity: O(n)
- The loop runs n times, performing a constant-time multiplication on each iteration.
Space Complexity: O(1)
- Only a fixed amount of space is used (result and loop counter i), regardless of the input size.
Comparison Between Different Methods of Finding Factorials
Method Name | Approach | Time Complexity | Space Complexity |
While Loop (Iterative) | Iterative using a while loop | O(n) | O(1) |
Recursive Method | Recursion | O(n) | O(n) |
Built-in (math.factorial) | Uses Python standard library | O(n)* | O(1) |
NumPy Product Method | NumPy prod() over range | O(n) | O(n) |
Prime Factorization Method | Multiply prime factorizations | O(n√n) | O(1) |
For Loop (Iterative) | Iterative using a for loop | O(n) | O(1) |
Summary
In the above tutorial, we explored different ways to compute a factorial in Python. Make sure you're comfortable with basic concepts like loops, recursion, modules, and functions before applying these methods. Enroll in our Python Certification Course to become a full-stack Python developer and secure a high-paying job. Explore our Python career guide to clarify any confusion regarding learning Python.
FAQs
built-In function, numpy.prod, and prime factorization method.
Take our Python skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.