# Counting the total number of theorems

I have:

\usepackage{amsthm}
\newtheorem{problem}{Problem}
....
\begin{problem}...\end{problem}...
...
\begin{problem}...\end{problem}...


In the first page of the document, how can I know the number of the problem environments used in the document? That is, I want to know the value of the last problem counter.

-
You are looking for \value{problem} or maybe \the\value{problem} depending on where you want to use it. – Seamus Mar 13 '12 at 16:30
@Seamus I don't want to sound harsh, but wouldn't \the\value{problem} return 0 at the beginning of the document no matter the number of problems? – yo' Mar 13 '12 at 16:42
@tohecz Perhaps I misunderstood the question, but I took it to be about accessing the number of problems so far, at a point in the document. If you want to know the value of the problem counter at the end of the document, then my suggestion will work. – Seamus Mar 13 '12 at 16:54
@Seamus Chang says "In the first page of the document, ..." – yo' Mar 13 '12 at 17:05
@Seamus and tohecz: Chang says "Thank you for your answers." – Chang Mar 13 '12 at 17:52

The following code uses the .aux file for that. It provides a macro \total@problems that sets \totalproblems to its parameter. And calls this macro at the end of document to store the value of counter problem. You need to run twice, and there is 0 stored at the first run.

\documentclass{article}

\usepackage{amsthm}
\newtheorem{problem}{Problem}

% STARTS HERE
\makeatletter
\AtEndDocument{\write\@auxout{\protect\total@problems{\arabic{problem}}}}
\def\total@problems#1{\global\def\totalproblems{#1}}
\total@problems{0}
\makeatother
% ENDS HERE

\begin{document}

Number of problems: \totalproblems

....
\begin{problem}...\end{problem}...
...
\begin{problem}...\end{problem}

\end{document}

-
Thanks. It works good. I wrote There are \totalproblems problems., and it returns There are 5problems. What is a good workaround for the spacing without manually adding a space? – Chang Mar 13 '12 at 16:47
@Chang the manual space is simply a matter of writing \  (that is, backslash, space) There are \totalproblems\ problems. Or look at the xspace package. – Seamus Mar 13 '12 at 16:55
The package totcount does something similar. – egreg Mar 13 '12 at 17:03
– Seamus Mar 13 '12 at 17:03
@Chang An alternative to Seamus's solution is \totalproblems{} problems – yo' Mar 13 '12 at 17:06

The package totcount provides a very efficient solution. It's sufficient to register the counter to the list of "total counters".

\documentclass{article}

\usepackage{totcount}

\newtheorem{problem}{Problem}
\regtotcounter{problem} % register the counter for getting the total

\begin{document}

Number of problems: \total{problem}

\begin{problem}
A
\end{problem}

\begin{problem}
B
\end{problem}

\end{document}


Using \total{problem} will print the required number; LaTeX will warn if another run is needed because of changes in the total.

-