How to simulate C style integer division?

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Thu Jan 21 09:48:37 EST 2016


Marko Rauhamaa writes:

> Jussi Piitulainen writes:
>
>> Steven D'Aprano writes:
>>
>>> So my guess is that the fastest, and certainly the most obvious, way
>>> to get the same integer division behaviour as C99 would be:
>>>
>>> def intdiv(a, b):
>>>     # C99 style integer division with truncation towards zero.
>>>     n = a//b
>>>     if (a < 0) != (b < 0):
>>>         n += 1
>>>     return n
>>
>> You should only increment if there is a (non-zero) remainder.
>
> Maybe:
>
>    def intdiv(a, b):
>        return a // b if (a < 0) == (b < 0) else -(-a // b)

Nice.



More information about the Python-list mailing list