% clara loeh
% 04/2012
% some basic tex macros
\documentclass{article}

\begin{document}

\def\punishment{Ich soll nicht abschreiben.}
\def\two#1{#1 #1 }
\def\ten#1{\two{\two{\two{#1}}}\two{#1}}
\def\hundred#1{\ten{\ten{#1}}}
%\hundred{\punishment}

% \show
% \makeatletter

% pagerefs

%\expandafter\x\y
%\expandafter\a\b
%\expandafter\expandafter\expandafter\x\expandafter\y\z

% primes
% basic loop structure
% (see TeXBOOK)
\def\loop#1\repeat{%
  \def\body{#1}\iterate}
\def\iterate{\body%
             \let\next=\iterate%
           \else%
             \let\next=\relax%
           \fi% !!
           %\show\next
           \next}

% primes
% (similar to TeXBOOK)
\newcount\k%
\newcount\p%
\newcount\n%
\newcount\q%
\newif\ifprime%
\newif\ifnodivisor%
% the first #1 primes
% assume that #1 >= 2
\def\primes#1{%
  \k=#1
  \p=3
  2%
  \loop%
    %\message{p=\number\p, k=\number\k}%
    \ifnum\k>1%
      %\message{testing \number\p}%
      \testifprime\p% 
      \ifprime%
         , \number\p%
         \global\advance\k by -1%
      \fi%
      \advance\p by 1%
  \repeat%
} 

% is #1 prime?
\def\testifprime#1{{%!!
  \global\primetrue%
  \n=2%
  \loop%
    \testifsmalldivisor{#1}{\n}%
    \ifnodivisor%  
      \advance\n by 1%
  \repeat%
}}

% is #1 divisible by #2 and #2 <= sqrt #1?
\def\testifsmalldivisor#1#2{%
  \q=#1%
  \divide\q by #2%
  \ifnum\q>#2%
    \nodivisortrue%
  \else%
    \nodivisorfalse%
  \fi%
  \multiply\q by #2%
  \ifnum\q=#1%
    \global\primefalse%
    \nodivisorfalse%
  \fi%
}

\primes{5000}
% in Haskell (www.haskell.org):
% take 5000 [ p | p <- [2 .. ], [ n | <- [2 .. p-1], p `mod` n ==0 ] == [] ]

\end{document}
