Solution (source code)

= Solution

Independently draw $Y\sim q$ and $U\sim\operatorname{Uniform}(0,1)$. Accept $Y$ if $U\le p(Y)/(Mq(Y))$; otherwise discard it and repeat with fresh <independent> draws. Return the first accepted value. The bound makes the acceptance probability at each proposal at most one. As $\int p=1$, the total acceptance probability is $1/M>0$, so the procedure terminates almost surely. Values outside the proposal support must have target <probability density function>[density] zero for the stated envelope assumption to make sense.