12

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.

Chang
  • 9,528
  • 1
    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
  • @tohecz Seamus says "Perhaps I misunderstood the question …" – Seamus Mar 13 '12 at 17:39
  • 1
    @Seamus and tohecz: Chang says "Thank you for your answers." – Chang Mar 13 '12 at 17:52

2 Answers2

13

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}
yo'
  • 51,322
11

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.

egreg
  • 1,121,712
  • the first time I compile it gives me ?? and the second time it shows 0. Why? I have written more than 100 problems. – yngabl Jan 16 '18 at 20:13
  • 1
    @yngabl I'm sorry, but I get 2 with the example code. Maybe you have some different setting. – egreg Jan 16 '18 at 21:23