Function for Factorial in Python

How do I go about computing a factorial of an integer in Python?

0

10 Answers

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.

4

On Python 2.6 and up, try:

import math
math.factorial(n)
1

Existing solution

The shortest and probably the fastest solution is:

from math import factorial
print factorial(1000)
James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.