# What is a function f(n) returning LaTeX code requiring exactly n compilations to yield stable output?

Is there a (simple) recipe for producing LaTeX code requiring exactly n compilations? (That is, I'm looking for an algorithm/function f(n) with domain {1, 2, 3, ...} and LaTeX code as its range.) If that makes answering easier, I'll be happy about a solution requiring n to be above a certain threshold (say, 2 or 3), since most ordinary code requires not more than 2 or 3 runs of latex. Ideally the solution isn't too contrived and easy to comprehend; direct solutions as well as solutions with recursive characteristics are welcome.

Note: This question grew out of this question about patterns increasing the number of required LaTeX compilation runs.

-
Isn't the ideal solution to have exactly one compilation? – morbusg Sep 23 '12 at 6:42
– Werner Sep 23 '12 at 6:43
@morbusg Yep (I agree), this is more of a fun/theoretical question. It somehow grew in an obvious way out of another question (the one I linked to); so keeping separate answers/info in separate posts was an additional reason to create this question. – Lover of Structure Sep 23 '12 at 6:46

Here is a small example that you can modify to give you as many compilations as you want:

\documentclass{article}
\usepackage{refcount}% http://ctan.org/pkg/refcount
\begin{document}
\setcounterref{section}{sec:foo}% Read label number from reference
\addtocounter{section}{-1}% Correct for stepping when issuing \section
\ifnum\value{section}<3% Modify this condition for different compiles
\stepcounter{section}% section = section + 1
\fi
\section{A section}\label{sec:foo}% New label
\end{document}


The condition \ifnum\value{section}<3 requires 4 compiles to settle. So, in general, \ifnum\value{section}<N will require N+1 compiles. It would be possible to make the example even simpler.

The generic way LaTeX checks for a possible rerun is to scan the .aux file at \enddocument and see whether an existing label written to the .aux (say mylabel) matches that of what it is in the current document/compile (stored as \r@mylabel). If there is any difference in the macro definitions, a rerun warning is issued.

For completeness, a label can move around on the same page and within the same "unit of reference" and not trigger a rerun.

-

The longtable documentation (section 4) gives an example of a 3 column table that takes 4 passes to stabilise (and 5 passes for latex to know that it has stabilised). It is easy to generalise this to an n-column table taking n+1 runs.

-