Java: How do I perform integer division that rounds towards -Infinity rather than 0?

Jason S picture Jason S · May 5, 2012 · Viewed 10.5k times · Source

(note: not the same as this other question since the OP never explicitly specified rounding towards 0 or -Infinity)

JLS 15.17.2 says that integer division rounds towards zero. If I want floor()-like behavior for positive divisors (I don't care about the behavior for negative divisors), what's the simplest way to achieve this that is numerically correct for all inputs?

int ifloor(int n, int d)
{
    /* returns q such that n = d*q + r where 0 <= r < d
     * for all integer n, d where d > 0
     *
     * d = 0 should have the same behavior as `n/d`
     *
     * nice-to-have behaviors for d < 0:
     *   option (a). same as above: 
     *     returns q such that n = d*q + r where 0 <= r < -d
     *   option (b). rounds towards +infinity:
     *     returns q such that n = d*q + r where d < r <= 0
     */
}

long lfloor(long n, long d)
{
    /* same behavior as ifloor, except for long integers */
}

(update: I want to have a solution both for int and long arithmetic.)

Answer

Louis Wasserman picture Louis Wasserman · May 5, 2012

If you can use third-party libraries, Guava has this: IntMath.divide(int, int, RoundingMode.FLOOR) and LongMath.divide(int, int, RoundingMode.FLOOR). (Disclosure: I contribute to Guava.)

If you don't want to use a third-party library for this, you can still look at the implementation.