Ulam spiral


[PDF] [TEX]
% !TEX TS-program = pdflatex
\documentclass[border=2mm]{standalone}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{ifthen}
\usepackage{tikz}


\newcounter{cmpt}
\newcounter{next}
\newcounter{end}

\newcommand*\ballcolor{%
    \stepcounter{cmpt}
    \pgfmathisprime{\value{cmpt}}
    \ifthenelse{\equal{\pgfmathresult}{0}}%
        { \colorlet{colornb}{blue!40}}%
        { \colorlet{colornb}{red!40}}%
}

\newcommand*{\ulam}[2]{%
    \setcounter{cmpt}{#1}
    \addtocounter{cmpt}{-1}
    \setcounter{next}{0}
    \setcounter{end}{#2}

    \ballcolor
    \node(place) at (0,0)  {$\mathbf\thecmpt$};

    \whiledo{\value{cmpt}<\value{end}}%
    {
            \foreach \i in {0,...,\thenext}
            {\ballcolor
            \node[above of=place] (place) {$\mathbf\thecmpt$};
        }

        \foreach \i in {0,...,\thenext}
        {
            \ballcolor
            \node[right of=place] (place) {$\mathbf\thecmpt$};
        }
        \stepcounter{next}

        \foreach \i in {0,...,\thenext}
        {
            \ballcolor
            \node[below of=place] (place) {$\mathbf\thecmpt$};
        }

        \foreach \i in {0,...,\thenext}
        {
            \ballcolor
            \node[left of=place] (place) {$\mathbf\thecmpt$};
        }
        \stepcounter{next}
    }
    \addtocounter{next}{-1}
    \foreach \i in {0,...,\thenext}
    {
        \ballcolor
        \node[above of=place] (place) {$\mathbf\thecmpt$};}
}
\begin{document}

  \begin{tikzpicture}
  \tikzstyle{every node}=[draw,%
                          rectangle,%
                          shade,%
                          minimum size  = 1.6cm,%
                          ball color    = colornb,%
                          node distance = 1.6cm]

  \ulam{41}{113}

  \end{tikzpicture}

\end{document}