# How to calculate factorial in python

Method 1:

import math
math.factorial(5)

Method 2 - recursive :

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

Method 3:

for i in range(1,n+1):
fact = fact * i 

Speed test i using timeit:

import math
import timeit

def factorial_method_1(n):
return math.factorial(n)

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

def factorial_method_3(n):
for i in range(1, n + 1):
fact = fact * i
return fact

def main():
n = 5
time = timeit.repeat(lambda: factorial_method_1(n))
print("Method 1 time - ", time)
time = timeit.repeat(lambda: factorial_method_2(n))
print("Method 2 time - ", time)
time = timeit.repeat(lambda: factorial_method_2(n))
print("Method 3 time - ", time)

if __name__ == "__main__":
main()


Speed test output:

Method 1 time -  [0.2941538, 0.22269869999999997, 0.2118059, 0.19471419999999995, 0.19232120000000008]
Method 2 time -  [0.9977693999999999, 0.7664341000000001, 0.7983863000000002, 0.7173130999999997, 0.7640148999999994]
Method 3 time -  [0.7642040000000003, 0.7658972000000004, 0.8779051999999998, 0.8027160999999996, 0.9024419999999989]

you can see that method 1 (math.factorial) is the fastest.