# How to create a Sierpinski triangle in LaTeX with numbers in the triangles?

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

As follows:

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??

• Sep 5 '16 at 17:21
• Please always post complete examples we can compile!
– cfr
Sep 5 '16 at 22:17

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.

## 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}

• Thank you very much!!. I could ask how to make the image smaller? Sep 5 '16 at 20:03
• @DarioGutierrez No problem! You can add scale=0.8, every node/.style={transform shape} to the tikzpicture options (next to x=2cm*sin 60, y=3cm*cos 60). Sep 5 '16 at 20:07
• @DarioGutierrez But scaling fonts in diagrams is not recommended.
– cfr
Sep 5 '16 at 22:17
• @cfr wouldn't that scale text properly as well? If not, he can simply modify the x and y values, along with the node sizes. Sep 5 '16 at 22:43
• That's my point. It is better not to scale text in diagrams to arbitrary sizes unless you really are stuck with no choice. It is better to use one of the standard sizes to ensure consistency.
– cfr
Sep 5 '16 at 23:59