Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast ceiling of an integer division in C / C++

Given integer values x and y, C and C++ both return as the quotient q = x/y the floor of the floating point equivalent. I'm interested in a method of returning the ceiling instead. For example, ceil(10/5)=2 and ceil(11/5)=3.

The obvious approach involves something like:

q = x / y; if (q * y < x) ++q; 

This requires an extra comparison and multiplication; and other methods I've seen (used in fact) involve casting as a float or double. Is there a more direct method that avoids the additional multiplication (or a second division) and branch, and that also avoids casting as a floating point number?

like image 985
andand Avatar asked Apr 30 '10 14:04

andand


People also ask

How do you find the division ceiling?

Using simple maths, we can add the denominator to the numerator and subtract 1 from it and then divide it by denominator to get the ceiling value.

How does C handle integer division?

Integer division yields an integer result. For example, the expression 7 / 4 evaluates to 1 and the expression 17 / 5 evaluates to 3. C provides the remainder operator, %, which yields the remainder after integer division.

How do you find the number ceiling in C?

C library function - ceil() The C library function double ceil(double x) returns the smallest integer value greater than or equal to x.


1 Answers

For positive numbers

unsigned int x, y, q; 

To round up ...

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

or (avoiding overflow in x+y)

q = 1 + ((x - 1) / y); // if x != 0 
like image 125
Sparky Avatar answered Sep 20 '22 23:09

Sparky