Factorial in TeX

Example for versions Web2c 2009

This example uses iterative factorial definition.

Note that \factorial macro has to use double curly brackets because it has loop that is used inside other loop.

Also only factorials up to 12 are handled. For bigger numbers TeX throws “Arithmetic overflow” error.

\newcount\n \newcount\p \newcount\m

\def\factorial#1{{\m=#1\advance\m by 1
\loop\ifnum\n<\m \multiply\p by \n \advance\n by 1 \repeat\number\p}}

\def\printfactorials#1{\m=#1\advance\m by 1
\loop\ifnum\n<\m \hfil\break\number\n! = \factorial{\n} \advance\n by 1 \repeat}