Fibonacci numbers in TeX

Example for versions Web2c 2009

This example uses iterative process to calculate Fibonacci numbers.

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

\newcount\n \newcount\np \newcount\npp \newcount\m \newcount\f

\def\fibonacci#1{{\ifnum #1<3 1\else
\np=1\npp=1\m=3
\loop\ifnum\m<#1\f=\npp\npp=\np\advance\np by\f\advance\m by 1\repeat
\f=0\advance\f by\np\advance\f by\npp
\number\f\fi}}

\def\printfibonacci#1{\m=#1\advance\m by 1
\n=1
\loop\ifnum\n<\m\fibonacci{\n}, \advance\n by 1\repeat...}

\printfibonacci{16}
\bye