TITLE: Share the beer fairly in a finite number of pours
QUESTION [8 upvotes]: A classical problem within measurements is that you have a $8\,\text{dl}$ mug of delicious expensive beer and need to share it evenly with your friend. However you only have two empty glasses of $5\,\text{dl}$ and $3\,\text{dl}$. Is it possible to divide the liquid in two using those two containers? With some light pondering one comes to the conclusion that yes, it is possible.
8 5 3 

8 0 0 - 0 
3 5 0 - 1 
3 2 3 - 2 
6 2 0 - 3 
6 0 2 - 4 
1 5 2 - 5 
1 4 3 - 6 
4 4 0 - 7

Assume that we have a mug containing $B\,\text{dl}$ delicious beer, and two empty mugs of sizes $p$ and $q$. What conditions must lie on $p$ and $q$ to ensure that there always exists a finite number of pours to split $B$ in half? (It is taken for given that $B$ always is even...)

REPLY [3 votes]: We assume $A=B/2$, $p$, and $q$ are integers, with $1\le p\le q\le B$, and $q\ge A$. We adopt the protocol, 

fill $q$ from $B$  
fill $p$ from $q$ if possible, else, empty $q$ into $p$ and go to 1  
empty $q$ into $B$ and go to 2

Let's see how this goes with $(B,q,p)=(20,15,7)$. We start at $(20,0,0)$ and go $(5,15,0)$, $(5,8,7)$, $(12,8,0)$, $(12,1,7)$, $(19,1,0)$, $(19,0,1)$, $(4,15,1)$, $(4,9,7)$, $(11,9,0)$, $(11,2,7)$, $(18,2,0)$, $(18,0,2)$, $(3,15,2)$, $(3,10,7)$, $(10,10,0)$ and we're done. Well, I didn't put a "stop" anywhere in the protocol, but it's clear that you stop when/as/if you have (some permutation of) $(A,A,0)$. The question is, what starting values of $B,q,p$ guarantee that you'll get to $(A,A,0)$? 
Note that if $p$ and $q$ have a common divisor $d$, then the contents of the $p$- and $q$-containers are always multiples of $d$. It follows that if $A$ is not a multiple of $d$, you can't win. 
But that's the only obstacle. If every common divisor of $p$ and $q$ divides $A$, then $\gcd(p,q)$ divides $A$, and we can divide through by it (think of measuring our beer in units $d$ times as large as usual), so now we have $\gcd(p,q)=1$. The contents of the $B$-container get decreased by $q$, then (repeatedly) increased by $p$, so they take on all the values of $B-(mq-np)$ (well, all the values satisfying $0\le B-(mq-np)\le B$). E.g., in the example, the contents of the $B$-container started at 20, went down by 15 to 5, then up by 7 to 12 and to 19, down by 15 to 4, up by 7 to 11 and to 18, down by 15 to 3, up by 7 to 10. Since $\gcd(p,q)=1$, elementary number theory tells us we can find $m$ and $n$ such that $mq-np=A$, so eventually the big container has $A$, and we're done.