Why can a milk-sharing puzzle help protect your bank account? Diophantus and integer equations
From the 8, 5, 3 litre milk puzzle to Diophantus, integer equations, packing, recurring schedules and the arithmetic used to generate RSA keys.

Mục lục
Here is a familiar childhood milk-sharing puzzle: an 8-litre jug is full of milk, while a 5-litre jug and a 3-litre jug are empty. None has measuring marks. You may not discard any milk, add another tool, or stop a pour before its source is empty or its destination is full. How can you divide the milk into two equal 4-litre shares?
The milk-jug puzzle takes 7 pours, ending with two 4-litre shares. Its connection to banking lies in the underlying mathematics: combining integer multiples also appears in RSA key generation, a tool that can help secure online connections. The puzzle is not an account-security mechanism, and banks do not all use the same suite of algorithms. We will identify the exact shared calculation, without confusing it with passwords, one-time codes or an entire banking system.
The pouring trick is to leave 2 litres in the 3-litre jug. Once the 5-litre jug is full, the smaller jug accepts only 1 more litre, leaving 4 behind. From that solution we move through integer equations associated with Diophantus, packing orders and recurring schedules, then the calculation of a private RSA exponent. Diophantus is not being credited with inventing either the puzzle or modern cryptography.
How do you solve the 8, 5, 3 litre milk-jug puzzle?
Call the jugs A, B and C, holding at most 8, 5 and 3 litres respectively. We record their contents in that fixed order. For example, (3, 2, 3) means A holds 3 litres, B holds 2, and C holds 3. The total remains 8.
A pour ends at a definite stopping point: either its source is empty or its destination is full. You cannot simply stop when you estimate that 4 litres remain. Allowing that would quietly introduce a measuring instrument into the puzzle.
| Pour | Action | A: 8 L jug | B: 5 L jug | C: 3 L jug |
|---|---|---|---|---|
| 0 | Initial contents | 8 | 0 | 0 |
| 1 | A fills B | 3 | 5 | 0 |
| 2 | B fills C | 3 | 2 | 3 |
| 3 | C empties into A | 6 | 2 | 0 |
| 4 | B empties into C | 6 | 0 | 2 |
| 5 | A fills B | 1 | 5 | 2 |
| 6 | B fills C, adding only 1 L | 1 | 4 | 3 |
| 7 | C empties into A | 4 | 4 | 0 |
Rather than memorising the table, notice two moments. Pour 2 leaves 2 litres in the middle jug; pour 4 transfers that amount to the smallest jug. We measure with the remaining empty space, not with marks on the container. A 3-litre jug already holding 2 litres is a tool that accepts exactly 1 litre more.
You can use the same idea while cooking. A cup of known capacity measures either what it contains or what is missing. The puzzle has no scale, but it still provides two exact reference points: full and empty.

What does Diophantus have to do with three milk jugs?
Diophantus worked in Alexandria and is generally placed around the third century CE. His biography is less certain than the formulas carrying his name. Dates are largely inferred from authors who mention him and people he references. A precise birth year would therefore imply certainty that the evidence does not provide.[1]
His best-known work is the Arithmetica, a collection of arithmetic problems treated algebraically. Instead of merely evaluating a known expression, he looked for unknown numbers satisfying several conditions. It is the familiar step from a word problem to “let the unknown number be x”.[1]
One distinction matters. Diophantus accepted many positive rational solutions, numbers expressible as fractions, such as half a cake. The modern name “Diophantine equation” usually refers to a polynomial equation for which we seek integer solutions. The modern term describes a wider subject than one person’s problems, and not every answer he sought was an integer.[1]
For someone selling milk, a fraction of a litre is perfectly reasonable. In this puzzle, however, jug capacities and initial amounts are whole numbers of litres, and every pour continues until full or empty. Those operations keep the contents at whole numbers of litres. This restriction comes from the equipment and the rules, not from any inability to divide a liquid further.
That is the bridge to Diophantus: ask not only whether an equation has answers, but what kinds of answers are allowed. You can pay for three bowls of noodles with fractional currency units, but you cannot order 2.4 bowls if the shop only sells whole bowls. The arithmetic may look similar; an integer restriction changes the problem.
To continue that historical thread, Fermat and the note in a book’s margin follows a reader of the Arithmetica many centuries later. Here we stay with a smaller question: which amounts can two jug capacities generate?
Why can changing the capacities make the puzzle impossible?
Replace the jugs with 12, 8 and 4 litre containers, starting with the largest full and the others empty. Equal sharing would require two 6-litre portions. No clever sequence can achieve it.
Every capacity is divisible by 4. Initially, every amount is also divisible by 4. During a pour, both the source’s contents and the destination’s remaining space are multiples of 4. The transferred amount, whichever limit is reached first, is therefore a multiple of 4 too. This remains true after one pour, two pours, or any number of pours.
That is an invariant, something preserved by the allowed actions. It is like exchanging money using only 20,000 and 50,000 dong notes: the total remains a multiple of 10,000. The jugs and their contents can change, but no jug can contain exactly 6 litres, because 6 is not divisible by 4.
Here, 4 is the greatest common divisor, or gcd: the largest whole-number unit dividing all the capacities. The gcd of 8, 5 and 3 is 1, so this obstacle does not rule out 4 litres. For 12, 8 and 4, the gcd is 4, and the target is blocked immediately.
More generally, if both capacities and initial contents are multiples of a positive integer g, every later amount is a multiple of g. We have just proved this from the pouring operation, rather than guessed it by trying examples.
Does a gcd of 1 guarantee a solution?
Not under these closed three-jug rules. Consider capacities 10, 6 and 3, starting at (10, 0, 0) and targeting (5, 5, 0). The gcd of all three capacities is 1. But the smaller jugs together hold only 9 litres, so the largest always retains at least 1 litre: it never becomes empty.
Meanwhile, both smaller capacities are multiples of 3. Pouring from the largest fills a smaller jug; pouring back empties it. Pouring between the smaller jugs also preserves contents in multiples of 3. The 6-litre jug can therefore never hold 5 litres, even though the gcd of all three capacities does not object.
A search with the same pouring rules finds only six states: (10,0,0), (4,6,0), (7,0,3), (7,3,0), (1,6,3) and (4,3,3). The target is absent. This shows why a necessary condition does not automatically become sufficient. Having enough money for dinner does not mean the restaurant is open.
For the same reason, a criterion for two jugs with an unlimited tap and permission to discard water cannot simply be transplanted into a closed milk puzzle. Adding a source and a drain changes the rules and the reachable states.
From milk sharing to integer equations
Temporarily set aside the actual pours and consider arithmetic with the capacities 5 and 3. Can whole-number multiples of them be combined to produce 4?
Yes: , , since . Here x and y are coefficients in an addition and subtraction, not the contents currently sitting in jugs. The minus sign does not tell us to discard milk; it describes an amount subtracted when comparing quantities.
An equation of the form , requiring integer x and y, is a linear Diophantine equation. “Linear” means that adding one unit of x always increases the total by the same amount a, just as buying another identical bag of rice adds the same price to your bill.[2]
Its central property is concise. For integer a and b, not both zero, an integer solution exists if and only if c is divisible by gcd(a,b). For example, has no integer solution: the left-hand side is always even while the right-hand side is odd.[2]
The reverse implication relies on Bézout’s identity: the greatest common divisor of two integers can always be written as an integer combination of them. Think of constructing a basic monetary unit by adding and subtracting two denominations. For 5 and 3, we have ; multiplying this equality generates every integer multiple of 1.[2]
How do integers differ from nonnegative integers?
A shop sells only 3 kg and 5 kg bags. You want exactly 14 kg. If x counts 3 kg bags and y counts 5 kg bags, then with the additional restriction . Three smaller bags and one larger bag work.
Now change the target to 1 kg. The equation still has integer solutions, for example , . But you cannot buy minus one bag. There is no purchase made solely from these prepacked bags, even though the gcd remains 1.
The chickens-and-dogs puzzle (article in Vietnamese) has the same boundary. An equation might return 14.5 dogs, but someone counting animals cannot accept that answer. Milk sharing adds another layer: even a final inventory fitting every jug must have a path leading to it.
Where are integer equations used beyond the milk puzzle?
When quantities come in indivisible units, an approximate answer may be unusable. You cannot deliver 2.4 sealed cases if the customer accepts only whole cases. The following examples move from packing orders to recurring schedules and one step in cryptographic key generation. All numbers are illustrative, not company data.
Packing: once the quantity is right, which option uses fewer cases?
A shop has cases containing 3 or 5 bottles. An order requires exactly 24 bottles, and cases cannot be opened. If x counts small cases and y counts large ones, then , with nonnegative integer x and y.
There are two options: 8 small cases, or 3 small and 3 large cases. Both fill the order, but the second uses only 6 cases rather than 8. If every case has the same handling cost, it takes less handling in this model.
We have added another question: among admissible solutions, which minimises x + y? This is a form of integer optimisation, like choosing boxes that hold exactly the order while requiring the fewest trips to carry them. The equation says “24 bottles”; the nonnegative integer restriction says “actual cases”; the objective says “which option to choose”.
Real cases may have different costs, the vehicle has a weight limit, or the warehouse may lack large cases. Those conditions must be added. Six cases is not advice for every shipment. Large packing problems belong to a wider modelling framework; Bézout’s identity does not solve all the optimisation by itself.
Scheduling: when can two machines be maintained together?
Suppose one machine finishes a cycle at minutes 0, 6, 12, 18… Another finishes at minutes 4, 12, 20, 28… To stop both exactly at a cycle boundary, we need a time appearing in both lists. We can see minute 12, but longer cycles call for calculation rather than enumeration.
Call the time t. We have and , so:
The solution , gives t = 12 minutes. They meet again every 24 minutes: 12, 36, 60… That interval is the least common multiple of 6 and 8, like two clock hands moving at different rhythms and periodically returning to the same relative position.
Now let the second machine start at minute 3 rather than 4. The equation becomes . Its left-hand side is always even, so it cannot equal 3: there is no meeting under the unchanged schedules. The gcd condition tells us this before we inspect thousands of cycles.[2]
Saying “t leaves remainder 0 on division by 6, and remainder 4 on division by 8” uses congruence, which tracks a position within a cycle. A clock behaves this way: its display repeats after 12 hours. Real maintenance planning still needs to account for job duration, acceptable windows and clock drift. Sharing an instant does not mean there is enough time to do the work.
RSA: how can an integer equation help generate a key?
A more distant application appears during RSA key generation. We need a number d which, multiplied by e, leaves remainder 1 on division by m. The number d is the modular inverse of e modulo m: an “undo multiplication” button, but on a cycle of remainders rather than through ordinary division.[2]
For a small example, find d such that leaves remainder 1 when divided by 40. Equivalently, find integers d and k satisfying:
We have d = 23, k = 4, since . The gcd of 7 and 40 is 1, so the inverse exists. The extended Euclidean algorithm finds these coefficients systematically: divide with remainders, then work backwards to express the final remainder as a combination of the original numbers.[2]
Specifically, , , and . Working backwards gives . Substituting yields . The coefficient of 7 is −17; adding 40 gives 23, because the two numbers have the same remainder modulo 40. We need not test every possible d.
In an introductory RSA construction, choose primes p = 5 and q = 11. Then n = 55 and . Choose e = 7 and obtain d = 23 through the same calculation. The relationship between the exponents is part of what makes encryption followed by decryption recover the message.[4]
This is a bridge for recognising an integer equation inside technology, not a recipe for building a cryptosystem. The inverse is easy to compute when m is known; RSA’s security does not come from making this calculation hard. The numbers 5 and 11 are far too small for security. Real RSA also requires proper key generation, message encoding and standard padding schemes. RSA and digital signatures for JWT explains the system in more detail.
What lies between an RSA key and a bank account?
When opening an online banking service, distinguish two questions: does the connection lead to the intended service, and is the person requesting a transaction authorised to do so? A digital signature helps check that a message was created by the holder of the corresponding private key, like inspecting a seal on a document. It does not by itself establish that the person holding the phone owns the account.[4]
In systems that use RSA for signatures or authentication, the inverse calculation above is part of key generation. The key is useful only within a sound process: validating the issuer’s identity, protecting the private key and using standard cryptographic schemes. A particular system may choose another algorithm; a padlock icon does not tell you that a bank uses RSA.
Passwords, one-time codes and transaction limits address additional questions. Knowing how to calculate does not prevent every scam or stop someone from sharing a confirmation code. The milk puzzle leads to a mathematical tool used in security, not a complete solution for protecting an account. That is both the meaning and the limit of the title’s connection.
These examples do not mean Diophantus anticipated modern packing, machine schedules or RSA. The connection is the kind of question: find integers satisfying conditions. Moving from “a solution exists” to “fewest cases”, “first meeting” or “a secure key” requires additional tools and assumptions.
Why are seven pours minimal, rather than merely possible?
Treat each allocation of milk as a location. From (8,0,0), filling the middle jug takes us to (3,5,0). A legal pour is a road connecting two locations. A collection of locations and connections is called a graph, like a railway map showing stations and the routes between them.
For the 8–5–3 puzzle, 24 nonnegative integer triples sum to 8 without exceeding any jug’s capacity. But only 16 are reachable from the initial position under the full-or-empty rule. For example, (2,4,2) conserves the milk and fits every jug, yet none is full or empty. It cannot be the result of a pour made under these rules.
To find the shortest route, check everything reachable in one pour, then two, then three. This is breadth-first search, or BFS, like searching through circles of acquaintances: direct friends first, friends of friends next. When each connection costs one pour, the first time we find the target gives the fewest pours.[3]
Running it on this exact model gives 7 pours. The computer does not “guess cleverly”; it checks successive layers without skipping a shorter route. Minimising pours differs from minimising shipping cases, but both force us to say what cost we are counting.
Three distinctions the puzzle makes us keep
No marks does not mean no measurement. Full capacity and empty space already provide reference points. But we may not assume we know the halfway height in an arbitrary jug, especially if its shape is irregular.
Integer amounts do not make liquid discrete. Milk can still be divided further. Whole-number amounts arise from the model’s inputs and operations. If a capacity is 2.5 litres, we can choose half a litre as our unit and rewrite it using integers.
The name Diophantus is not an authorship certificate. This article connects a familiar puzzle to a field bearing his name. None of the sources here says he divided milk with three jugs.
Find the pouring path and draw the seven moves yourself
The Python below visits every reachable state, traces back one shortest path, and creates exactly Figure 1. It uses only the standard library and Pillow for drawing. Nothing is random, so no seed is needed; the order in which jug pairs are tried is fixed.
Save it as milk_jugs.py and run it in the directory where you want the image. It produces bay-luot-rot-en.png. Drawing plays no part in finding the answer: if you change capacities and the target cannot be reached, the program reports that rather than drawing an imaginary solution.
from collections import dequefrom PIL import Image, ImageDraw, ImageFont
cap, start, goal = (8, 5, 3), (8, 0, 0), (4, 4, 0)queue, parent = deque([start]), {start: None}while queue: s = queue.popleft() for i in range(3): for j in range(3): amount = min(s[i], cap[j] - s[j]) if i != j else 0 if not amount: continue nxt = list(s) nxt[i] -= amount nxt[j] += amount nxt = tuple(nxt) if nxt not in parent: parent[nxt] = s queue.append(nxt)if goal not in parent: raise SystemExit("No pouring path to the target")path, state = [], goalwhile state is not None: path.append(state) state = parent[state]path.reverse()print("Reachable states:", len(parent))print("Minimum pours:", len(path) - 1)print(" -> ".join(map(str, path)))
# Arial is available on macOS; elsewhere change these to Unicode font paths.regular = "/System/Library/Fonts/Supplemental/Arial.ttf"bold = "/System/Library/Fonts/Supplemental/Arial Bold.ttf"bg, panel, ink = "#10151e", "#19212d", "#efe3cc"muted, milk, gold = "#afb8c6", "#d8cbb2", "#e8b05a"im = Image.new("RGB", (1600, 990), bg)draw = ImageDraw.Draw(im)def text(xy, value, size=28, color=ink, strong=False): f = ImageFont.truetype(bold if strong else regular, size) draw.text(xy, value, font=f, fill=color, anchor="mm")text((800, 58), "Seven pours, two equal shares", 44, strong=True)text((800, 112), "Volumes are litres; pour until the source is empty or the destination is full.", 26, muted)for step, volumes in enumerate(path): x, y = 34 + (step % 4) * 395, 165 + (step // 4) * 395 draw.rounded_rectangle((x, y, x + 365, y + 350), 10, fill=panel) text((x + 182, y + 37), "Start" if step == 0 else f"Pour {step}", 30, strong=True) for j, (capacity, volume) in enumerate(zip(cap, volumes)): left, bottom, width = x + 40 + j * 100, y + 240, 65 height = capacity * 15 draw.rounded_rectangle((left, bottom - height, left + width, bottom), 5, fill=panel) if volume: fill = gold if step == 7 and volume == 4 else milk draw.rectangle((left + 4, bottom - volume * 15 + 3, left + width - 4, bottom - 4), fill=fill) draw.line([(left, bottom - height), (left, bottom), (left + width, bottom), (left + width, bottom - height)], fill=ink, width=3) text((left + width / 2, bottom + 23), f"{capacity} L", 22, muted) text((left + width / 2, bottom - height - 20), str(volume), 25, strong=True) text((x + 182, y + 310), str(volumes), 26, gold if step == 7 else ink)text((800, 965), "Computed by breadth-first search; all 16 reachable states checked.", 25, muted)im.save("bay-luot-rot-en.png")The output reports 16 reachable states and a shortest route of 7 pours, following the sequence in the opening table. Change capacities to 12, 8, 4, the start to (12,0,0), and the target to (6,6,0): the program reports no path. Capacities 10, 6, 3 provide another unreachable target, (5,5,0), despite the capacities having a gcd of 1.
Back to the unmarked milk jug
The 3-litre jug ends empty. Each remaining jug holds 4 litres, without anyone estimating a level by eye. The solution comes from keeping an amount in the right place so that the empty space becomes a measuring tool.
That childhood puzzle leaves us with three separate questions: does arithmetic rule out the desired number, is there a legal sequence of actions, and how long is the shortest sequence? Integer equations help with the first. A state map and a search answer the other two. Whole-case orders, machine schedules and the modular inverse in RSA likewise require us to separate arithmetic conditions from the other demands of the task.
Diophantus need not appear in an invented milk-sharing anecdote for the connection to matter. His name reminds us to ask one more thing before solving an equation: which answers are admissible? On paper, they may need to be integers. On the table, they must also be pourable.
Free geometric illustrations for students and teachers: EyeViz.
Tài liệu tham khảo
- [1]J. J. O’Connor and E. F. Robertson. Diophantus of Alexandria. MacTutor History of Mathematics, University of St Andrews.
- [2]CP-Algorithms contributors. Linear Diophantine Equation. CP-Algorithms.
- [3]CP-Algorithms contributors. Breadth First Search. CP-Algorithms.
- [4]R. L. Rivest, A. Shamir and L. Adleman. A Method for Obtaining Digital Signatures and Public-Key Cryptosystems. Communications of the ACM, 21(2), 120–126, 1978.


