Solution (source code)

= Solution

Assume a positive common density scale $\rho_0$ and use the unit-radius coordinates of the source. The cylinder's density depends on distance from its axis. Its <mass> is
$$
M_{\mathrm{cyl}}=\int_0^4\int_0^{2\pi}\int_0^1\rho_0r^{-1}\,r\,dr\,d\phi\,dz
=8\pi\rho_0.
$$
The radial factor in the <cylindrical volume element> cancels the apparent density singularity.

For the sphere, the <spherical volume element> gives
$$
M_{\mathrm{sph}}=4\pi\rho_0\int_0^1r^{n+2}\,dr
=\frac{4\pi\rho_0}{n+3},\qquad n>-3.
$$
The condition is necessary for finite <mass>; the integral diverges for $n\leq-3$. Equating the two finite masses yields $1/(n+3)=2$, and hence
$$
\boxed{n=-\frac52.}
$$
This satisfies $n>-3$. A divergent pointwise density can therefore have finite total <mass>: the <integrable power-law density at an axis or center> must be tested together with its volume factor. Dimensionally, the density laws can be understood as $\rho_0(r/R)^{-1}$ and $\rho_0(r/R)^n$ with unit radius $R=1$ in the chosen length units.