I completed an exercise on HackerRank, a site for programming exercises. The problem has been inspired from Die Hard 3 movie. The original problem is like the following.
The problem
You are given two buckets with capacity $5$ (bucket A
) and $3$ liters (bucket B
); you must obtain exactly $4$ liters of water (there is a fountain somewhere). The procedure is the following:
- fill bucket
A
from the fountain completely:A=5
,B=0
- fill the bucket
B
with the water in bucketA
:B=3
andA=2
- empty bucket
B
:A =2
,B=0
- fill bucket
B
with the water inA
:A=0
,B=2
- refill bucket
A
from the fountain:A=5
,B=2
- fill bucket
B
with the water inA
:A=4
,B=3
Now changing the capacity values (let me call them c1
and c2
) of the $2$ buckets and the desired final value (let me call it d
), sometimes this problem has a solution sometimes it doesn't.
The solution
It turns out it has a solution when two conditions are satisfied (at least according to the HackerRank website and some users):
- at least one of the buckets has a capacity larger than the final desired quantity:
c1>d OR c2>d
- calling
gcd
the greatest common divisor betweenc1
andc2
, it must be that the reminder of the divisiond/gcd
is0
.
I discovered Euclid's algorithm and this implementation in the C programming language and everything worked out. The Euclid's algorithm to find the greatest common divisor, has the following procedure (let me assume c1>c2
and let r
be the reminder at each step of the division c1/c2
):
while c2>0 do:
r = c1 % c2
c1 = c2
gcd = c2
c2 = r
return gcd
gcd
variable will hold the value representing the greatest common divisor.
My questions
However I am left with two questions, one about the problem and the other about Euclid's algorithm (they might be related):
- why does the second condition (the one about the greatest common divisor) guarantee to tell if a solution exists for such a problem? Can anyone make the passage explicit?
- Can you make explicit why Euclid's algorithm results in the
GCD
? It looks like magic to me.
Sorry if my question is quite long but I tried to give every piece of information.