9

I am in the process of cleaning up the code for Sieve of Eratosthenes in tikz, but saw that when I initially did the code, I could not figure out how to do a <= comparison within the \whiledo, and had resorted to doing a < comparison with one more than the desired number. This feels like a hack to me, and since @StefanKottwitz is considering posting this on another site with tikz examples, I'd prefer to not have to resort to such hackery.

Question:

How do I implement a <= comparison within a \whiledo such as:

\whiledo{\value{MyCounter} <= \MaxValue}{

Notes:

  • As much as I would like to, I can't use the \foreach from pgf.

Code:

\documentclass{article}
\usepackage{ifthen}

\newcounter{MyCounter}

\def\StartValue{5}
\def\MaxValue{10}

\begin{document}
Note that 10 is missing when comparing to MaxValue:

\setcounter{MyCounter}{\StartValue}
\whiledo{\value{MyCounter} < \MaxValue}{
    \theMyCounter
    \stepcounter{MyCounter}
}

\bigskip
\textbf{Hack:} Comparing to MaxValuePlusOne does the job:

\newcounter{MaxValuePlusOne}
\setcounter{MaxValuePlusOne}{\MaxValue}
\stepcounter{MaxValuePlusOne}
%
\setcounter{MyCounter}{\StartValue}
\whiledo{\value{MyCounter} < \value{MaxValuePlusOne}}{
    \theMyCounter
    \stepcounter{MyCounter}
}
\end{document}
Peter Grill
  • 223,288

2 Answers2

17

<= is equivalent to not >

\documentclass{article}
\usepackage{ifthen}    
\newcounter{MyCounter}
\begin{document}
Note that 10 is not missing when comparing to MaxValue:

\def\StartValue{5}
\def\MaxValue{10}

\setcounter{MyCounter}{\StartValue}
\whiledo{\not{\value{MyCounter}>\MaxValue}}{%
    \theMyCounter
    \stepcounter{MyCounter}
}
\end{document} 
Alain Matthes
  • 95,075
8

We can define \newwhiledo with LaTeX3 macros or use the \numexpr trick, take your pick:

\documentclass{article}
\usepackage{ifthen}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\newwhiledo}{m m}
  {
   \bool_while_do:nn { \int_compare_p:n {#1} } { #2 }
  }
\ExplSyntaxOff

\newcounter{MyCounter}

\def\StartValue{5}
\def\MaxValue{10}

\begin{document}
Note that 10 is missing when comparing to MaxValue:

\setcounter{MyCounter}{\StartValue}
\newwhiledo{\value{MyCounter} <= \MaxValue}{
    \theMyCounter
    \stepcounter{MyCounter}
}

\bigskip
\textbf{Hack:} Using \verb|\numexpr|

\setcounter{MyCounter}{\StartValue}
\whiledo{\numexpr\value{MyCounter}-1 < \MaxValue}{
    \theMyCounter
    \stepcounter{MyCounter}
}
\end{document}
egreg
  • 1,121,712