This is a Frobenius problem , which is generally NP-Hard.
For small instances, fairly fast algorithms are known.
The article here: http://www.combinatorics.org/Volume_12/PDF/v12i1r27.pdf seems to describe previous algorithms (including the Dijkstra shortest path algorithm application!) Plus this gives a new algorithm, which seems to be faster previous ones.
In any case, for the case when there are only 2 numbers, a and b such that gcd (a, b) = 1, finding i, j> 0, that ai + bj = M is easily solved.
It is also known that any number greater than (a-1) (b-1) can be represented as ai + bj with i> = 0 and j> = 0. The Frobenius number is defined as the largest number that cannot be represented in this form, it exists when n> = 2 and gcd (a, b, c ...) = 1.
So, in your case, if the numbers involved are small enough, you can sort the array, find the "smallest" two a and b, such as gcd (a, b) = 1 and see if M> (a-1) ( b-1), which can only be solved with a and b.
if M <= (a-1) (b-1) and a and b are small enough, you can simply force the exile.
Aryabhatta May 26 '10 at 12:50 2010-05-26 12:50
source share