You don't need a lengthy code for this. It is obvious that the spot size at the distance L is minimum when L =
zR, where zR is the Rayleigh range. That's all.
Then compare the spot size and the aperture size whether it is enough or not.
It is not your case, but if the damage is the matter, just escape to the large zR side. If that is not possible
because of the aperture size, your EOM is not adequate for your purpose.