Find a common batch size with gcd
Also published in our Blogger archive.
When several whole-item inventories must be divided into identically sized batches with no leftovers, the greatest common divisor gives the largest possible batch size. Python’s math.gcd() returns the greatest common divisor of integer arguments. It was added in Python 3.5; support for more than two arguments was added in Python 3.9.
Here, three production counts—84, 126, and 210—must each be packed into equal-sized batches. math.gcd(*counts) returns 42, so each count divides evenly by 42. The resulting batch counts are 2, 3, and 5. The assertions check both the calculated common size and that every input has a zero remainder. The program then prints the selected batch size and the derived number of batches.
This calculation applies to integer units. If the inputs describe kilograms, time, or another fractional measurement, converting them to a suitable common integer unit may be necessary before using gcd(). That conversion can introduce its own business rules and rounding concerns. A result of 1 is valid but means only single-item batches work. If every argument is zero, math.gcd() returns 0; this example intentionally uses positive counts because a zero-sized batch is not a useful packaging instruction. The assertions prove divisibility for these values only.
Consult the official math.gcd documentation for argument and zero-value behavior.
AI assistance disclosure: This article was drafted with AI assistance and should be reviewed for the target batching rules.
import math
item_counts = (84, 126, 210)
batch_size = math.gcd(*item_counts)
batches = tuple(count // batch_size for count in item_counts)
assert batch_size == 42
assert all(count % batch_size == 0 for count in item_counts)
assert batches == (2, 3, 5)
print(f"common batch size: {batch_size}")
print(f"batches per count: {batches}")
common batch size: 42
batches per count: (2, 3, 5)