12

Is there any ceil counterpart for Math.floorDiv()

How to calculate it fastest way with what we have?

UPDATE

The code for floorDiv() is 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;
    }

Can we code ceil the similar way?

UPDATE 2

I saw this answer https://stackoverflow.com/a/7446742/258483 but it seems to have too many unnecessary operations.

Community
  • 1
  • 1
Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

4 Answers4

21

There is none in the Math class, but you can easily calculate it

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

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

Mark Jeronimus
  • 9,278
  • 3
  • 37
  • 50
k_g
  • 4,333
  • 2
  • 25
  • 40
3

I'd also just use the negation of floorMod, but if you are going to define your own function, you could simply adapt the above code:

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;
}
Vesal
  • 181
  • 2
  • 3
0

You can make use of the floorDiv function and fiddle with that:

int ceilDiv(int x, int y) {
    return Math.floorDiv(x, y) + (x % y == 0 ? 0 : 1)
}
fejese
  • 4,601
  • 4
  • 29
  • 36
0

Since Java 18, Math.ceilDiv is available, see https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/Math.html#ceilDiv(int,int)

DaHoC
  • 314
  • 1
  • 4
  • 14