Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ceil conterpart for Math.floorDiv in Java?

Tags:

java

math

java-8

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.

like image 747
Suzan Cioc Avatar asked Dec 25 '14 01:12

Suzan Cioc


People also ask

How does math Ceil work in Java?

Java Math ceil() The ceil() method rounds the specified double value upward and returns it. The rounded value will be equal to the mathematical integer. That is, the value 3.24 will be rounded to 4.0 which is equal to integer 4.

What is Ceil and floor in Java?

floor: Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. ... ceil: Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. ...

Does Java integer division round up or down?

So Does Java division round down? The answer is Yes. Java does a round down in case of division of two integer numbers.


2 Answers

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).

like image 129
k_g Avatar answered Oct 22 '22 12:10

k_g


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;
}
like image 43
Vesal Avatar answered Oct 22 '22 14:10

Vesal