How to Compute Factorial in Python

Formula for computing factorial is,

Factorial(n) = n*(n-1)*(n-2).... *1

This can be written as Factorial(n) = n*Factorial(n-1).

Hence we can use recursion to find factorial of a number.The following Python 3 program computes factorial of a number using recursion.

# python 3.6+ needed
def factorial(n):
    if n==1 or n==0:
        return 1
        return n * factorial(n-1)

number = int(input("Enter number for factorial calculation:"))
fact = factorial(number)
print(f"factorial({number}) = {fact}")

However, python does have a built-in method for computing factorial. The following sample program computes factorial in python 3 using the built-in factorial method in math module,

# python 3.6+ needed
import math
number = int(input("Enter number for factorial calculation:"))
fact = math.factorial(number)
print(f"factorial({number}) = {fact}")

If you have a program which computes factorial of multiple numbers, we can use a method level cache to speed up calculation of factorial. The following program stores any factorial computed in a cache. When a call is made to calculate the factorial of the same number, it is picked from the cache. This substantially speeds up factorial computation since we are using recursion in this program. See lru_cache documentation to learn more about this technique.

# python 3.6+ needed
import math
import functools

# caches calculated values for input number n.
def factorial(n):
    return math.factorial(n)

# find factorial of 1 to 100. Uses lru_cache for performance.
for num in range(1,101):
    fact = factorial(num)
    print(f"factorial({num}) = {fact}")

First few lines of the output is given below,

factorial(1) = 1
factorial(2) = 2
factorial(3) = 6
factorial(4) = 24
factorial(5) = 120
factorial(6) = 720
factorial(7) = 5040
factorial(8) = 40320
factorial(9) = 362880
factorial(10) = 3628800

Following is a python 2.7 program for finding factorial of a number,

# python 2.x solution for factorial
import math
number = int(raw_input("Enter number for factorial calculation:"))
fact = math.factorial(number)
print "factorial({0}) = {1}".format(number,fact)