In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
A factorial of a non-negative integer n, is the product of all positive integers up to n, and is denoted with an exclamation mark, n!.
- 5! = 5*4*3*2*1 = 120
- 20! = 1*2*3*...*18*19*20 = 2 432 902 008 176 640 000 (largest factorial representable as a 64-bit long-integer)
- 69! ≈ 1.72 × 1098, 70! ≈ 1.20 × 10100
- 0! = 1 (by definition)
Factorial implementation
In computer programming, the function which computes the factorial of a number is often used as an example of a recursive function. Here is a simply recursive Python code for the factorial function.
# Calculates factorial of a number n! recursively
def factorial(n):
# Base case, stop when n is 0 or 1
if n == 0 or n == 1:
return 1
# Recursive step
return n*factorial(n-1)
Here is an equivalent iterative version of the factorial function:
# Calculates factorial of a number n!
def factorial(n):
# Base case, stop when n is 0 or 1
if n == 0 or n == 1:
return 1
# Loop to multiply by successive integers
product = 1
counter = 2
while counter <= n:
product *= counter
counter += 1
return product
Applications of the factorial
The factorial is important in fields of combinatorics. The most well-known example of factorial is to count the ways n objects can be arranged in a line - the number of ways (permutations) is n!. The binomial coefficient nCk is equivalent to n!/k!(n-k)!. It also serves a role in evaluating power series of well-known functions such as exp.
Factorial time and complexity is also one of the commonly referred complexity levels of an algorithm, namely O(n!) complexity. The factorial function grows very fast, and grows asymptotically faster than any exponential function an with linear exponent, so therefore factorial time and complexity indicates very poor asymptotic performance. In fact, a 64-bit long integer can only store up to 20!, and 69! is the largest factorial less than a googol.
Enumerating and generating a list of all the permutations of n objects takes factorial time and space, and quickly becomes infeasible for even small integers such as 10.
See more
- complexity-theory, time-complexity, big-o: Factorial time is an example of bad time complexity!
- recursion: The factorial function is often used to teach recursion.
- exponentiation, multiplication: Exponentiation and factorials both involve multiplication. Exponential growth is also considered bad in terms of algorithmic complexity.
- Wolfram article
- Wikipedia article for more information about factorials, including the binomial coefficient, power series, and generalization to complex numbers.