Re: very simple questions about integer division

  • From: Philipp Kutin <philipp.kutin@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 31 Aug 2012 13:39:10 +0200

On Thu, Aug 30, 2012 at 6:10 PM, Francesco Abbate
<> wrote:
> I was therefore wondering how to obtain the integer division in
> Lua/LuaJIT. Of course it can be done using some tricks:
> c = (a - a % b) / b
> or
> c = math.floor(a / b)

Careful there! These two are equivalent, but not the same as C integer
division, which is the remainder of a/b assuming truncated division.

I think there's no other way than resorting to something like

function cdiv(a, b)
    q = a/b
    return (q > 0) and math.floor(q) or math.ceil(q)

to simulate C's division for negative divisors or dividends.

Here's a nifty comparison of various division rounding methods I found
the other day:


Other related posts: