[Tex/LaTex] How to create a Sierpinski triangle in LaTeX with numbers in the triangles

graphicstikz-pgf

I would need to create a Sierpinski triangle in LaTeX, with numbers in the triangles.

As follows:

Sierpinski triangle

I have tried to modify the following code:

\begin{figure}[h]
\centering
\begin{tikzpicture}[scale=2]
    \def\trianglewidth{2cm}%
    \pgfdeclarelindenmayersystem{Sierpinski triangle}{
        \symbol{X}{\pgflsystemdrawforward}
        \symbol{Y}{\pgflsystemdrawforward}
        \rule{X -> X-Y+X+Y-X}
        \rule{Y -> YY}
    }%

    \tikzset
    {
        l-system={step=\trianglewidth/(2^6), order=6, angle=-120}
    }


    \fill [black] (0,0) -- ++(0:\trianglewidth) -- ++(120:\trianglewidth) -- cycle;
    \draw [draw=none] (0,0) l-system [l-system={Sierpinski triangle, axiom=X},fill=white];
\end{tikzpicture}
\caption{Sierpiński Sieve.}
\label{fig:SierpinskiTriangle}
\end{figure}

But without success 🙁
How can I write numbers in the triangles??

Best Answer

You could use Mark Wibrow's solution, but it employs lualatex and if you don't already use it, it might not be worth it to switch to a different engine. Besides, that solution uses hexagons instead of triangles and it doesn't color them.

So here's an alternative version based on that answer but that has all the necessary changes. Plus it works with regular pdflatex, since we use pgfmath to do the proper calculations.

Output

enter image description here

Code

\documentclass[tikz,margin=10pt]{standalone}
\usetikzlibrary{shapes.geometric}

\tikzset{
    tris/.style={#1,
    font=\ttfamily,
    regular polygon, regular polygon sides=3, 
    minimum size=2cm, inner sep=0pt,
}
}

\begin{document}
\begin{tikzpicture}[x=2cm*sin 60, y=3cm*cos 60]

\foreach \n in {0,...,7}{
    \foreach \k in {0,...,\n}{ 
        \pgfmathtruncatemacro\fact{factorial(\n)/(factorial(\n-\k)*factorial(\k))}
    \ifodd\fact
        \node[tris={draw,fill, text=white}] at (-\n/2+\k, -\n) {\fact};
    \else
        \node[tris] at (-\n/2+\k, -\n) {\fact};
    \fi
    }
}
\end{tikzpicture}
\end{document}