Getting Ceil value of the integral division in Java

Getting Ceil value of the integral division in Java

·

2 min read

For a double number...

  • Floor value = greatest integer smaller than or equal to the number (e.g., floor(3.6) = 3 )

  • Ceil value = smallest integer greater than or equal to the number (e.g., ceil(3.6) = 4 ).

In JAVA, the division operator / returns the floor value.

int n = 8;
int d = 3;
int value = n/d;
System.out.println( value ); // Output = 2

Let us see the patterns behind the ceil values:

  • 8/3 = 3 --> remainder = 2

  • 11/4 = 3 --> remainder = 3

  • 22/6 = 4 --> remainder = 4

  • 18/3 = 6 --> remainder = 0

Observations:

  1. If n is divisible by d i.e, n%d = 0 --> ceil == floor

  2. Else --> ceil = floor +1

  3. 0 <= remainder < d --> max value of remainder = d-1

Therefore, CEIL value comes from the FLOOR division of the multiple of d greater than or equal to n.

Generalizing the above observation, we can conclude:

ceil( n/d ) = floor( (n+d-1)/d )

  • ceil( 8/3 ) = floor( (8+3-1)/3 ) = floor( 10/3 ) = 3

  • ceil( 18/3 ) = floor( (18+3-1)/3 ) = floor( 20/3 ) = 6

  • ceil( 11/4 ) = floor( (11+4-1)/4 ) = floor( 14/4 ) = 3

int n = 22;
int d = 6;
int ceilValue = (n+d-1)/d;
System.out.println(ceilValue); // Output = 4