Ceil conterpart for Math.floorDiv in Java?

Is there any ceil for Math.floorDiv()

How to calculate it in the fastest way with what we have?

UPDATE

The code for floorDiv() follows:

  public static long floorDiv(long x, long y) { long r = x / y; // if the signs are different and modulo not zero, round down if ((x ^ y) < 0 && (r * y != x)) { r--; } return r; } 

Is it possible to encode ceil same way?

UPDATE 2

I have seen this answer https://stackoverflow.com/a/166268/2126 , but there seem to be too many unnecessary operations.

+6
source share
3 answers

There are none in the Math class, but you can easily compute it

 long ceilDiv(long x, long y){ return -Math.floorDiv(-x,y); } 

For example, ceilDiv(1,2) = -floorDiv(-1,2) = -(-1) = 1 (the correct answer).

+6
source

I would also use floorMod negation, but if you are going to define your own function, you can simply adapt the code above:

 public static int ceilDiv(int x, int y) { int r = x / y; // if the signs are the same and modulo not zero, round up if ((x ^ y) >= 0 && (r * y != x)) r++; return r; } 
+2
source

You can use the floorDiv function and play with it:

 int ceilDiv(int x, int y) { return Math.floorDiv(x, y) + (x % y == 0 ? 0 : 1) } 
0
source

Source: https://habr.com/ru/post/980136/


All Articles