1

If I have two numbers $x$ and $y$, how do I find the smallest value of $ax + by$, where $a$ and $b$ are integers, such that $ax + by$ is still larger than another number $z$?

For example, imagine I have two types of drug vials, one holds 20mg and the other 50mg. How do I find the combination of these vials so that I have enough drug for some who needs, say, 80mg of drug, whilst minimizing waste?

I can of course do this specific example in my hand, but I need a generalizable algorithm that I can code into Python eventually. Thank you so much!

Arturo Magidin
  • 398,050
  • Are $x$, $y$ and $z$ integer? Are they positive? – Aig Mar 07 '24 at 22:54
  • 1
    Based on your example, we presumably also want $a,b$ non-negative. – user469053 Mar 07 '24 at 22:54
  • By the linked dupe $,a\Bbb Z + b\Bbb Z = \gcd(a,b)\Bbb Z,$ so your set of sums is simply the set of multiples of the gcd, so you seek the least multiple of the gcd larger than $,z.\ \ $ – Bill Dubuque Mar 08 '24 at 00:03
  • If $a$ and $b$ must be non-negative you should look up the https://en.wikipedia.org/wiki/Coin_problem the Frobenius coin problem. – fleablood Mar 08 '24 at 01:41

1 Answers1

1

Firstly to address the comments: In your example you can presumably use the vials to remove the drug as well as add it. Thus we really are looking for integers $a,b$. Note that we can always do all the adding first, and then the removing, so we never have to worry about "negative" quantities of drug.

The numbers of the form $ax+by$ are precisely the multiples of $\gcd(x,y)$. This is due to Euclid's algorithm - typically the first thing one is taught when studying number theory.

So the smallest such number greater than (or equal to) $z$ would be $\lceil z/\gcd(x,y)\rceil \times\gcd(x,y)$.

To work out $a,b$ you need to implement Euclid's algorithm, to find $a',b'$ such that: $$a'x+b'y=\gcd(x,y).$$

Then multiply your values of $a',b'$ by $\lceil z/\gcd(x,y)\rceil$.

tkf
  • 11,563
  • 1
    Please strive not to post more (dupe) answers to dupes of FAQs. This is enforced site policy, see here. It's best for site health to delete this answer (which also minimizes community time wasted on dupe processing.) – Bill Dubuque Mar 08 '24 at 00:05