This is the subset-sum problem -- it is NP-Complete, hence although there are certainly algorithms for it, none are necessarily "fast" in general (possibly for special cases of the problem though).
The most common approach is dynamic programming.
EDIT: while Wikipedia is unnecessarily general, as usual, the subset sum problem usually refers to OP's problem (i.e. restricted to positive integers) and is well-studied with several known solutions, such as dynamic programming. All of the following links give dynammic programming solutions to the subset sum problem when the restriction is to the positive integers.
http://algorithms.tutorialhorizon.com/dynamic-programming-subset-sum-problem/
http://www.cs.dartmouth.edu/~ac/Teach/CS105-Winter05/Notes/nanda-scribe-3.pdf
https://www.cs.cmu.edu/~ckingsf/class/02713-s13/lectures/lec15-subsetsum.pdf
https://cseweb.ucsd.edu/classes/wi12/cse202-a/lecture7-final.pdf
Moreover, as also described in Cormen et al., and Kleinberg and Tardos, the Subset Sum problem refers to the restriction to the case of positive integers only. OP's $M$ constraint can be implemented easily by choosing a proper set of integers ($M$ copies of all integers less than or equal to $N-1$ will be sufficient, although strictly more than necessary).
Also all of the other answers given below just give pseudo-code for the dynamic programming solutions without explaining the provenance or the reasoning behind those choices. The links above, in contrast, explain the theory behind the idea in detail and how to specifically apply it to the subset sum problem, while retaining enough generality to allow OP to figure out how to fill in the details relevant for the implementation of their specific case.