Today I have already answered a similar code-golf question "Output the first 200 primes using TeX".
My answer needs 176 bytes to print the first 200 prime numbers with plain TeX. I have ungolfed the code and adapted it to LaTeX. As interface \primenumber
/\primecounter
are added as equivalents to \@alph
/\alph
. Internally the prime numbers are stored in macros \prime@<number>
.
\documentclass{article}
\makeatletter
\begingroup
\countdef\i=1 %
\countdef\j=2 %
\countdef\k=3 %
\countdef\ii=4 %
\newcount\prime@count
\prime@count=1 %
\global\@namedef{prime@1}{2}%
\i=3
\loop
\ifnum\prime@count<200 %
{% group with curly braces because of the nested \loop
% Test for all 2 <= j < i: trunc(i/j)*j == i
% If true, then j is divisor of i and i is not prime
\j=3
% small optimization, \ii should be sqrt(i),
% it is approximated by \ii/3 + 1
\ii=\i
\divide\ii 3
\advance\ii\@ne
\let\x.%
\loop
\ifnum\j<\ii
\k=\i
\divide\k \j
\multiply\k \j
\ifnum\k=\i
\let\iterate\@empty
\let\x!%
\fi
\advance\j\tw@
\repeat
\ifx\x.%
\global\advance\prime@count\@ne
\expandafter\xdef\csname prime@\the\prime@count\endcsname{\the\i}%
\fi
}%
\advance\i\tw@ % test next odd number
\repeat
\endgroup
\newcommand*{\primenumber}[1]{%
\@ifundefined{prime@\number#1}\@ctrerr{\csname prime@\number#1\endcsname}%
}
\newcommand*{\primecounter}[1]{%
\primenumber{\csname c@#1\endcsname}%
}
\makeatother
\begin{document}
\newcounter{test}
\renewcommand*{\thetest}{\primecounter{test}}
\setcounter{test}{1}
\makeatletter
\@whilenum\value{test}<\prime@count\do{%
\thetest, %
\stepcounter{test}%
}%
\primenumber{\prime@count}%
\makeatother
\end{document}
