Ceiling of Integer Division without Multiplication or Floating-Point Casting
In C and C , integer division (x/y) returns the floor of the result. To calculate the ceiling instead, avoiding floating-point casting and additional multiplication, consider the following methods:
1. Using (x y - 1) / y:
unsigned int x, y, q; // Round up q = (x + y - 1) / y;
This formula ensures that the ceiling is computed, as it adds 1 before performing division.
2. Avoiding Overflow in (x y):
To prevent integer overflow when adding x and y, an alternative method is:
q = 1 + ((x - 1) / y); // if x != 0
This formulation effectively increments the ceiling by 1, except when x is 0, where it remains 0.
The above is the detailed content of How to Calculate the Ceiling of Integer Division in C/C without Multiplication or Floating-Point Operations?. For more information, please follow other related articles on the PHP Chinese website!