[Tex/LaTex] square root of number in counter

calculationscounters

I would like to get the square root of a number which I have stored into a counter. I have been using the calc package for summation and multiplication operations, but I cannot find anything like

\setcounter{squarerootofmynumber}{\value{mynumber}^{1/2}}

or something like that. Do you know the way?

Best Answer

Here are four ways for calculating the square root of a number (with varying precision). However, the result cannot be stored in a counter unless it is an integer.

  1. The calculator package

    \documentclass{article}
    \usepackage{calculator}
    \newcounter{mycount}
    \setcounter{mycount}{7}
    \begin{document}
    \SQUAREROOT{\themycount}{\solution}%
    $\sqrt{\themycount}=\solution$
    \end{document}
    
  2. The fp package

    \documentclass{article}
    \usepackage{fp}
    \newcounter{mycount}
    \setcounter{mycount}{7}
    \begin{document}
    \FProot\solution{\themycount}{2}%
    \FPround\solution\solution{5}%
    $\sqrt{\themycount}=\solution$
    \end{document}
    
  3. The pgf package (thanks to Peter Grill for the reminder)

    \documentclass{article}
    \usepackage{pgf}
    \newcounter{mycount}
    \setcounter{mycount}{7}
    \begin{document}
    \pgfmathsetmacro{\solution}{sqrt(\themycount)}%
    $\sqrt{\themycount}=\solution$
    \end{document}
    
  4. The l3fp module of the l3kernel

    \documentclass{article}
    \usepackage{expl3}
    \ExplSyntaxOn
    \cs_new_eq:NN \calculate \fp_eval:n
    \ExplSyntaxOff
    \newcounter{mycount}
    \setcounter{mycount}{7}
    \begin{document}
    $\sqrt{\themycount}=\calculate{round(sqrt(\themycount),5)}$
    \end{document}
    

All of these examples give

enter image description here

Storing the result in a counter requires the result to be an integer. Packages 2-4 have means to round a result which would allow to set a counter afterwards. Here is an example with l3fp:

\documentclass{article}
\usepackage{expl3}
\ExplSyntaxOn
\cs_new_eq:NN \calculate \fp_eval:n
\ExplSyntaxOff
\begin{document}
\newcounter{mycount}
\setcounter{mycount}{7}
\edef\solution{\calculate{round(sqrt(\value{mycount}),0)}}
\setcounter{mycount}{\solution}\themycount
\end{document}