As you wrote, we have $$q=e-k\qquad\text{and}\qquad r=k\left(n+1+\frac{n-1}{d}\right)-e\left(1+\frac{n-1}{d}\right)$$ under the condition that $$0\le r\lt M,$$ i.e. $$0\le k\left(n+1+\frac{n-1}{d}\right)-e\left(1+\frac{n-1}{d}\right)\lt n+1+\frac{n-1}{d},$$ i.e. $$\frac{e(d+n-1)}{dn+d+n-1}\le k\lt \frac{e(d+n-1)}{dn+d+n-1}+1,$$ i.e. $$k=\left\lceil \frac{e(d+n-1)}{dn+d+n-1}\right\rceil$$
It follows that the answer is $$q=e-\left\lceil \frac{e(d+n-1)}{dn+d+n-1}\right\rceil$$ and $$r=\left\lceil \frac{e(d+n-1)}{dn+d+n-1}\right\rceil\left(n+1+\frac{n-1}{d}\right)-e\left(1+\frac{n-1}{d}\right)$$