Re: very simple questions about integer division

  • From: Pierpaolo Bernardi <olopierpa@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 31 Aug 2012 14:20:30 +0200

On Fri, Aug 31, 2012 at 1:39 PM, Philipp Kutin <philipp.kutin@xxxxxxxxx> wrote:
> On Thu, Aug 30, 2012 at 6:10 PM, Francesco Abbate
> <francesco.bbt@xxxxxxxxx> 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)
> end
>
> to simulate C's division for negative divisors or dividends.

Isn't C division truncation direction undefined, if one argument is negative?

Or has this changed recently?

Other related posts: