0

I am trying to use two theorem environments, one for exercises and another for their solutions. The counter for the solution should be the same as the counter for the associated exercise.

An example:

Exercise 1.1. What is 2+2?

Exercise 1.2. What is 3+5?

Solution to Exercise 1.1. 2+2=4.

Solution to Exercise 1.2. 3+5=8.

Should be the output of:

\begin{exercise}\label{ex: 22} What is 2+2?\end{exercise}
\begin{exercise}\label{ex: 35} What is 3+5?\end{exercise}
\begin{solution}[ex: 22] 2+2=4.\end{solution}
\begin{solution}[ex: 35] 3+5=8.\end{solution}

Is this possible using the amsthm package?

s.harp
  • 103

1 Answers1

3

I think one counter and the label-ref mechanism is enough:

\documentclass{article}
\usepackage{amsthm}
\newcounter{exercise}
\counterwithin{exercise}{section}
\NewDocumentEnvironment{exercise}{ m +b }{%
  \noindent
  Exercise~\refstepcounter{exercise}\theexercise\label{#1}. #2}{\par\medskip}
\newenvironment{solution}[1]{%
  \begin{proof}[Solution to Exercise~\ref{#1}]}%
  {\end{proof}}
\begin{document}

\section{AAAAA} \begin{exercise}{ex:22} What is 2+2?\end{exercise} \begin{exercise}{ex:35} What is 3+5?\end{exercise} \begin{solution}{ex:22} 2+2=4.\end{solution} \begin{solution}{ex:35} 3+5=8.\end{solution}

\end{document}

enter image description here

You can also use amsthm to define the exercise environment which makes the code a little simpler:

\documentclass{article}
\usepackage{amsthm}
\newtheorem{exercise}{Exercise}[section]
\newenvironment{solution}[1]{%
  \begin{proof}[Solution to Exercise~\ref{#1}]}%
  {\end{proof}}
\begin{document}

\section{AAAAA} \begin{exercise}\label{ex:22} What is 2+2?\end{exercise} \begin{exercise}\label{ex:35} What is 3+5?\end{exercise} \begin{solution}{ex:22} 2+2=4.\end{solution} \begin{solution}{ex:35} 3+5=8.\end{solution}

\end{document}

enter image description here

Stephen
  • 3,826