Solving for $i$ amounts to computing the real root of a degree $n$ polynomial*, so unless $n \in \{1, 2, 3, 4\}$, there is in general no elementary closed form solution. For $n = 25$ as in your case, your best bet is to use a recursive numerical algorithm; e.g., Newton's method. It is convenient to let $v = 1/(1+i)$ or equivalently, $i = \frac{1}{v} - 1$, so that the equation of value is $$P\left(\frac{1}{v} - 1\right) = M(1-v^n). \tag{1}$$ Rewriting this as a polynomial in $v$, we obtain
$$v^{n+1} - \left(1+\frac{P}{M}\right)v + \frac{P}{M} = 0. \tag{2}$$ Let $c = P/M > 1$ and we seek the unique real root $0 < v < 1$ of $(2)$. To this end, we set up the Newton's method recursion with initial guess $v_0$ by computing the derivative of $f(v) = v^{n+1} - (1+c)v + c$: $$f'(v) = (n+1)v^n - (1+c), \tag{3}$$ hence $$v_{k+1} = v_k - \frac{f(v_n)}{f'(v_n)} = \frac{n v_k^{n+1} - c}{(n+1)v_k^n - (c+1)}. \tag{4}$$
What is a suitable initial guess? Well, we know that if the payments were made in perpetuity, the equation of value would simply be $M = Pi$, hence $i = M/P$ is the periodic interest rate in the limiting case $n \to \infty$. So this furnishes a lower bound on $v$, namely $v > 1/(1+M/P)$. So we use this as our initial guess. Convergence is rapid: for instance, suppose the monthly mortgage is $M = 2500$ on a principal of $P = 375000$. The term of the loan is $n = 240$ months, or $20$ years. Payments are made at the end of each month. Then $c = 375000/2500 = 150$ and our initial estimate of $v$ is $$v_0 = \frac{1}{1 + M/P} = \frac{150}{151} \approx 0.993377.$$ We compute the iterates of $(4)$ until they stop changing, and summarize these in a table:
$$\begin{array}{c|c}
k & v_k \\
\hline
0 & 0.993377 \\
1 & 0.995353 \\
2 & 0.995729 \\
3 & 0.995750 \\
4 & 0.995751 \\
5 & 0.995751 \\
\end{array}$$
This gives us $i = 1/v - 1 \approx 0.00426763$, which is the effective periodic (monthly) rate of interest, and the effective annual rate is $(1+i)^{12} - 1 \approx 0.0524308$.
*Note. Although $(2)$ is degree $n+1$ in $v$, it should be observed that $v = 1$ is always a solution, thus the extra degree comes from an extraneous linear factor of the form $(v-1)$. However, factoring it out results in a cumbersome expression, which is why we employ $(2)$ instead.