4

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

2

1 Answer 1

8

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} 
5
  • Thank you very much!!. I could ask how to make the image smaller? Commented Sep 5, 2016 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). Commented Sep 5, 2016 at 20:07
  • @DarioGutierrez But scaling fonts in diagrams is not recommended. Commented Sep 5, 2016 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. Commented Sep 5, 2016 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. Commented Sep 5, 2016 at 23:59

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.