Function for factorial in Python
How do I go about computing a factorial of an integer in Python?
Solution 1:
The easiest way is to use math.factorial
(available in Python 2.6 and above):
import math
math.factorial(1000)
If you want/have to write it yourself, you can use an iterative approach:
def factorial(n):
fact = 1
for num in range(2, n + 1):
fact *= num
return fact
or a recursive approach:
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
Note that the factorial function is only defined for positive integers, so you should also check that n >= 0
and that isinstance(n, int)
. If it's not, raise a ValueError
or a TypeError
respectively. math.factorial
will take care of this for you.
Solution 2:
On Python 2.6 and up, try:
import math
math.factorial(n)
Solution 3:
Existing solution
The shortest and probably the fastest solution is:
from math import factorial
print factorial(1000)
Building your own
You can also build your own solution. Generally you have two approaches. The one that suits me best is:
from itertools import imap
def factorial(x):
return reduce(long.__mul__, imap(long, xrange(1, x + 1)))
print factorial(1000)
(it works also for bigger numbers, when the result becomes long
)
The second way of achieving the same is:
def factorial(x):
result = 1
for i in xrange(2, x + 1):
result *= i
return result
print factorial(1000)
Solution 4:
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1)
Solution 5:
If you are using Python 2.5 or older, try
from operator import mul
def factorial(n):
return reduce(mul, range(1, n+1))
For newer versions of Python, there is factorial in the math module as given in other answers here.