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;
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

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.

About Our Journalist