Example: Pascal triangle

Published 2016-12-30 | Author: M.H. Ahmadi

A calculated Pascal triangle built with hexagons.

Download as: [PDF] [TEX]  •  [Open in Overleaf]

Pascal triangle

Do you have a question regarding this example, TikZ or LaTeX in general? Just ask in the LaTeX Forum.
Oder frag auf Deutsch auf TeXwelt.de. En français: TeXnique.fr.

% Pascal triangle
% Author: M.H. Ahmadi 
\documentclass[border=10pt]{standalone}%
\usepackage[dvipsnames]{xcolor} 
\usepackage{tikz}
\usepackage{ifthen}
\makeatletter
\newcommand\binomialCoefficient[2]{%
    % Store values 
    \c@pgf@counta=#1% n
    \c@pgf@countb=#2% k
    %
    % Take advantage of symmetry if k > n - k
    \c@pgf@countc=\c@pgf@counta%
    \advance\c@pgf@countc by-\c@pgf@countb%
    \ifnum\c@pgf@countb>\c@pgf@countc%
        \c@pgf@countb=\c@pgf@countc%
    \fi%
    %
    % Recursively compute the coefficients
    \c@pgf@countc=1% will hold the result
    \c@pgf@countd=0% counter
    \pgfmathloop% c -> c*(n-i)/(i+1) for i=0,...,k-1
        \ifnum\c@pgf@countd<\c@pgf@countb%
        \multiply\c@pgf@countc by\c@pgf@counta%
        \advance\c@pgf@counta by-1%
        \advance\c@pgf@countd by1%
        \divide\c@pgf@countc by\c@pgf@countd%
    \repeatpgfmathloop%
    \the\c@pgf@countc%
}
\makeatother
\begin{document}
\newdimen\R
\R=.4cm
\newcommand\mycolor{gray}
\begin{tikzpicture}[line width=.8pt]
  \foreach \k in {0,...,12}{
    \begin{scope}[shift={(-60:{sqrt(3)*\R*\k})}]
      \pgfmathtruncatemacro\ystart{12-\k}
      \foreach \n in {0,...,\ystart}{
        \pgfmathtruncatemacro\newn{\n+\k}
        \ifthenelse{\k=0}{\def\mycolor{pink}}{}
        \ifthenelse{\k=1}{\def\mycolor{yellow}}{}
        \ifthenelse{\k=2}{\def\mycolor{blue}}{}
        \ifthenelse{\k=3}{\def\mycolor{green}}{}
        \ifthenelse{\k=8 \AND \n < 4}{\def\mycolor{purple}}{}
        \ifthenelse{\k=9 \AND \n = 3}{\def\mycolor{purple}}{}
        \begin{scope}[shift={(-120:{sqrt(3)*\R*\n})}]
           \draw[top color=\mycolor!20,bottom color=\mycolor!60] 
             (30:\R) \foreach \x in {90,150,...,330} {
                -- (\x:\R)}
                -- cycle (90:0)
                   node {\tiny $\mathbf{\binomialCoefficient{\newn}{\k}}$};
         \end{scope}
      }
    \end{scope}
  }
\end{tikzpicture} 
\end{document}

Comments

Adding comments is currently not enabled.

Features
Tags
Scientific and technical areas

Cookbook

LaTeX Beginners Guide

Limited discount 50%
coupon code tDRet6Y

Creative Commons License