devxlogo

A Smart Ceiling for a Ratio of Two Integers

A Smart Ceiling for a Ratio of Two Integers

I often use the following trick in my code.

Let “a” and “b” be real positive numbers. You want to find the smallest integer greater than or equal to “a/b”. Perhaps your code looks like:

 #include double a, b;long c;c = (long) ceil( a / b );

Now, the question remains the same, but your numbers “a” and “b” happen to be integers. You can write:

 #include long a, b, c;c = (long) ceil( (double)a/(double)b );

However, there is a more elegant and efficient solution:

 long a, b, c;c = (a - 1) / b + 1;

devx-admin

Share the Post: