c++c++11divisioninteger-divisionceil

Division Round Up in C++


How can I round up when performing division on two int values in C++ without using std::ceil?

Typically I end up doing something like the following:

double res = ceil(a / (double) b);

Is there any way I can duplicate the result without using std::ceil?


Solution

  • If a and b are both positive, you can avoid floating point completely and get both exact results (no problems with FP rounding) and faster execution time through the classical method:

    int res = (a + (b - 1)) / b;
    

    For negative a you don't need any correction - the truncation performed by integer division already has the semantics matching your ceil formula; so, if you want a more general case:

    int res = (a<0 ? a : (a + (b - 1))) / b;