Suppose that the particle is projected from a height H above the ground at speed V at an angle \alpha to the x-axis, with x measuring the horizontal distance travelled and y measuring the vertical distance travelled.
Then the coordinates of the points along this trajectory are
(x, y) = \left(V \cos(\alpha) t, -0.5 g t^2+V\sin(\alpha) t +H\right)\;.
The particle intersects the x-axis when the y-coordinate is zero. This is when
t = \frac{V\sin(\alpha) \pm \sqrt{V^2\sin^2(\alpha) +2gH}}{g}\;.
The particular caseH=0
The square root simplifies giving the point of intersection as
(x, y) = \left(\frac{2V^2}{g}\cos(\alpha)\sin(\alpha), 0\right) = \left(\frac{2V^2}{g}\sin(2\alpha), 0\right)\,,
where the second equality makes use of a trig identity. The x-value V\sin(2\alpha) is maximised when 2\alpha=90^\circ. Thus the optimal angle of projection is 45^\circ, for any initial velocity.
WhenH\neq 0
In this case, the particle intersects the x-axis at
x =\frac{V^2}{g} \cos(\alpha) \left(\sin(\alpha) + \sqrt{\sin^2(\alpha) +\frac{2gH}{V^2}}\right)\;.
This looks complicated to differentiate so I tried a numerical solution using a spreadsheet.This produced an optimal angle of 40.4^\circ (3sf).
It seems clear that this angle will be dependent on the initial speed, but to check I calculate the optimum angle numerically for a large initial speed of 100\mathrm{ms}^{-1}. This produces an optimium of 44.9^\circ (3sf) which is close to 45^\circ, as we might intuitively expect.
Extension:
You might like to investigate this further. Here are some starting points.
Note that the expression for the derivative is:
\frac{g}{V^2}\frac{dx}{d\alpha} = \cos(2\alpha)-\sin(\alpha)\sqrt{\sin^2(\alpha) +\frac{2gH}{V^2}}+\cos^2\alpha\sin\alpha \frac{1}{\sqrt{\sin^2(\alpha) +\frac{2gH}{V^2}}}\;.
For an optimum we can set the left hand side to zero. This gives us
\sin\alpha\left(\cos(2\alpha) -\frac{2gH}{V}\right) + \sin(\alpha)\cos(2\alpha)\left(1 +\frac{2gH}{V^2\sin^2(\alpha)}\right)^{\frac{1}{2}}=0\;.
If X(\alpha) \equiv \frac{2gH}{V^2\sin^2(\alpha)} is small then we can expand to give
\sin\alpha\left(\cos(2\alpha) -\frac{2gH}{V}\right)+ \sin(\alpha)\cos(2\alpha)\left(1+\frac{1}{2}\frac{2gH}{V^2\sin^2(\alpha)}+\mathcal{O}(X^2)\right)=0\;.
In principle that can now be turned into a polynomial expression in \cos(\alpha)\ldots