devxlogo

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;

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Seven Service Boundary Mistakes That Create Technical Debt

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.