Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java integer division doesn't give floor for negative numbers

I was trying to use java's integer division, and it supposedly takes the floor. However, it rounds towards zero instead of the floor.

public class Main {
    public static void main(String[] args) {
        System.out.println(-1 / 100); // should be -1, but is 0
        System.out.println(Math.floor(-1d/100d)); // correct
    }
}

The problem is that I do not want to convert to a double/float because it needs to be efficient. I'm trying to solve this with a method, floorDivide(long a, long b). What I have is:

static long floorDivide(long a, long b) {
    if (a < 0) {
        // what do I put here?
    }
    return a / b;
}

How can I do this without a double/float?

like image 523
AMACB Avatar asked Jan 07 '23 01:01

AMACB


1 Answers

floorDiv() from Java.Math that does exactly what you want.

static long floorDiv(long x, long y)

Returns the largest (closest to positive infinity) long value that is less than or equal to the algebraic quotient.

like image 153
Frank Harper Avatar answered Jan 08 '23 13:01

Frank Harper