How to Convert Floor Division to Ceiling Division

Jan
7

Today I found an elegant way to implement ceiling division.

Using Java, the following code results in an integer result of ceil(5/6):

int div = (int)Math.ceil(5 / (double)6);

A simpler, more elegant solution the doesn't require the Math library would be:

int div = (5 + 6 - 1) / 6;

Here's the solution generally:

int ceiling = (numerator + denominator - 1) / denominator;

However, one must be careful since there is a possibility here for an overflow. One way to prevent an overflow would be to use long instead of int.

On a related note, to convert floor division to rounding division, you can use the following:

int rounded = (numerator + denominator / 2) / denominator;

You may read more about this at its source.

Tags: #Java #Math Author: Seth Westphal
comments powered by Disqus