Step 1: Potential energy of a dipole in a field.
The orientation potential energy of a magnetic dipole is \(U = -\vec{M}\cdot\vec{B} = -MB\cos\theta\), taking the zero of energy at \(\theta = 90^\circ\).
Step 2: Work-energy connection.
The work done by an external agent in slowly rotating the dipole equals the change in its potential energy, \(W = U_{final} - U_{initial}\).
Step 3: Substitute the two orientations.
\(W = (-MB\cos\theta_2) - (-MB\cos\theta_1) = MB(\cos\theta_1 - \cos\theta_2)\). This is the required general formula.
Step 4: Dipole parallel to the field, turned by \(180^\circ\).
Parallel means \(\theta_1 = 0^\circ\); after a \(180^\circ\) turn \(\theta_2 = 180^\circ\).
\(W = MB(\cos 0^\circ - \cos 180^\circ) = MB(1 + 1) = 2MB\).
Step 5: Physical check.
Going from the lowest-energy parallel state \((U = -MB)\) to the highest-energy anti-parallel state \((U = +MB)\) costs \(U_2 - U_1 = MB - (-MB) = 2MB\), the same result.
\[\boxed{W = MB(\cos\theta_1 - \cos\theta_2),\quad W_{180^\circ} = 2MB}\]