Solution (source code)

= Solution

Let $\alpha:G\to G$ be surjective and suppose that $1\ne g\in\ker\alpha$. By residual finiteness, choose $q:G\to Q$ with $Q$ finite and $q(g)\ne1$. The preceding part makes the sequence
$$
q,\ q\alpha,\ q\alpha^2,\ldots
$$
repeat, so $q\alpha^i=q\alpha^j$ for some $i<j$. Surjectivity of $\alpha^i$ permits cancellation on the right and gives $q=q\alpha^{j-i}$. But $g\in\ker\alpha^{j-i}$, which would imply $q(g)=1$, a contradiction. Thus $\alpha$ is injective. Every finitely generated residually finite group is therefore a <Hopfian group>.