Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more elegant way to calculate x = (y / n) + (y % n ? 1 : 0) ?

While programming I often find myself needing to calculate something like:

x = (y / n) + (y % n ? 1 : 0);

Or more explicitly:

x = y / n;
if (y % n != 0) {
   x = x + 1;
}

Is there a more elegant way to achieve this value? Can it be achieved without using a conditional expression?

like image 272
grieve Avatar asked Aug 09 '12 19:08

grieve


1 Answers

So, you want the integer division to round up instead of down. You can fake this by adding n-1 to the numerator:

x = (y + n - 1) / n;

That way you shift the value it'll be rounded down to just enough to give you the desired outcome.

like image 153
Sebastian Paaske Tørholm Avatar answered Oct 12 '22 23:10

Sebastian Paaske Tørholm