Mincong Huang Mincong Huang - 1 year ago 81
Java Question

Calculate the array size according to remainder

There're a construction site and there're works to do. And we need certain number of workers to do them. Each worker has the same work capacity and they can't handle more than that limit. So for a given number of works, the number of workers required is :

  • If the
    is an integer multiple of
    , then
    will be a simple division of
    works / workerCapacity

  • If the
    is not an integer multiple of
    , then after the division, we need to increment one. E.g. if capacity = 10, 100 works need 10 workers but 101 works need 11 workers.

Here's my implementation:

public int getNumWorkers(int works) {
int workers = works / workerCapacity;
if (works % workerCapacity != 0) {
return workers;

My question is: can we simplify the lines 2-5 into only one line ?

Answer Source

Yes, you can. Add workerCapacity-1 before dividing it out, like this:

return (works+workerCapacity-1) / workerCapacity;

If workerCapacity divides works evenly (i.e. works % workerCapacity == 0) adding workerCapacity-1 will be too little to change the answer. If the remainder is above zero, adding workerCapacity-1 will increase the result of division by one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download