Solution (source code)

= Solution

After the first <Hadamard gate> and the <controlled unitary gate>, the state is
$$
\frac1{\sqrt2}
\left(|0\rangle|\psi\rangle
+e^{i\theta}|1\rangle|\psi\rangle\right).
$$
The final Hadamard gate gives
$$
\boxed{
\frac12\left[
(1+e^{i\theta})|0\rangle
+(1-e^{i\theta})|1\rangle
\right]|\psi\rangle.}
$$
Hence the <Hadamard test> returns one with probability
$$
\boxed{
\Pr(1)=\frac{|1-e^{i\theta}|^2}{4}
=\frac{1-\cos\theta}{2}
=\sin^2\frac\theta2.}
$$
If $U|\psi\rangle=|\psi\rangle$, then $\theta=0$ and the outcome is zero with certainty. If $U|\psi\rangle=-|\psi\rangle$, then $\theta=\pi$ modulo $2\pi$ and the outcome is one with certainty. The single measurement therefore distinguishes the two promised cases exactly.