Why not a simple division in this case?

52 Views Asked by At

n represents total number of persons.
max represents the maximum number of persons by department.

To know the accepted number of persons by department, I would do:

personsPerDepartment = n / max

However, I read on a programming book:

personsPerDepartment = (n + (max - 1)) / max

I don't figure out what this formula means.
Is it a tip to round the result?
Indeed, it would be equals to:

n / max + (max - 1) / max  =  n / max + ~1

Any idea?

2

There are 2 best solutions below

5
On BEST ANSWER

It is not immediately clear what you're trying to do here, but I suppose it is something like

If you have to distribute $n$ persons across departments, and each department can take at most $\mathit{max}$ of them, then how many departments do you need to involve?

Suppose you have $n=5$ and $\mathit{max}=4$. Obviously you need two departments for that. However if you simply divide $5$ by $4$, you get $1.25$, which is a quite strange number of departments.

So what you want to do is round the result of the division upwards to the nearest integer if it is not already an integer.

Most programming languages don't do that when you divide two integers and the result doesn't come out even. Instead they round down (actually, towards $0$). The alternative calculation $$ (a+b-1)/b $$ is just a common trick to get the round-UP behavior when dividing $a$ by $b$, when all you have is a division operator that rounds down, without involving floating point which is seen as inefficient.

Adding $b-1$ to the numerator will change the numbers in the interval $5 \ldots 8$ (which are the ones you want to produce 2 departments) into the interval $8\ldots 11$ (which are what actually produce a result of $2$ departments with the division operator you have to work with). And similarly for all of the other possible intervals.

7
On

When using integer division, the formula (n + (max - 1)) / max is equivalent to $\Big\lceil\frac{n}{\max}\Big\rceil$.

These brackets mean ceiling, or in your words: "it is a tip to round the result upwards".