Graph of Thomae function by an amateur

conditionalsifthenelsepgfmathpgfmathparsetikz-pgf

I am trying to plot the Thomae function, which is defined in the following way:
enter image description here

Now, I went through this answer, but unfortunately, could not grasp much. My idea is simple. Run two nested loops for the rationals and plot the points. What I have done is the following:

\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
    \begin{tikzpicture}[scale=5]
        \node [fill, circle, inner sep=0.5pt] at (0,0) {};
        \node [fill, circle, inner sep=0.5pt] at (1,1) {};
        \foreach [evaluate=\n as \den using \n-1] \n in {2,...,85}
            \foreach \m in {1,...,\den}
                \node [fill, circle, inner sep=0.5pt] at ({\m/\n},{1/\n}) {};
    \end{tikzpicture}
\end{document}

I am getting stuck at the gcd part. I do not know the proper usages and syntaxes of pgfmathsetmacro and the conditional ifthenelse statements. Please help.

Best Answer

I think that this is what you are looking for. I wrote my code with \pgfmathtruncatemacro (better than \pgfmathsetmacro as we need integer numbers), and a conditional statement with \ifnum.

\documentclass[tikz,border=2mm]{standalone}

\def\maxden{50} % maximum denominator

\begin{document}
\begin{tikzpicture}[scale=5]
\foreach\d in {2,...,\maxden}        % denominators from 2 to maximum
{
  \pgfmathtruncatemacro\maxnum{\d-1} % maximum numerator
  \foreach\n in {1,...,\maxnum}      % numerators from 2 to maximum
  {
    \pgfmathtruncatemacro\gcd{gcd(\n,\d)} 
    \ifnum\gcd = 1 % then the fraction is irreducible, so we draw a point
      \fill (\n/\d,1/\d) circle (0.1pt);
    \fi
  }
}
\end{tikzpicture}
\end{document}

enter image description here