# Programming/Kdb/Factorial

< Programming‎ | Kdb
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

# The factorial

The factorial of a non-negative integer ${\displaystyle n}$, denoted by ${\displaystyle n!}$, is the product of all positive integers less than or equal to ${\displaystyle n}$:

${\displaystyle n!=n\cdot (n-1)\cdot (n-2)\cdot (n-3)\cdot \ldots \cdot 3\cdot 2\cdot 1.}$

For example,

${\displaystyle 5!=5\cdot 4\cdot 3\cdot 2\cdot 1=120.}$

The value of ${\displaystyle 0!}$ is 1, according to the convention for an empty product.

The factorial operation is encountered in many areas of mathematics, notably in combinatorics, algebra, and mathematical analysis. Its most basic use counts the number of distinct sequences—the permutations—of ${\displaystyle n}$ distinct objects: there are ${\displaystyle n!}$.

# Implementing the factorial in q

We'll implement the factorial as a q function. That function will take a single parameter, x, and return the result.

fact:{[x]1f}