Integer division

Sion Arrowsmith siona at chiark.greenend.org.uk
Thu Jun 7 11:22:36 EDT 2007


Hamish Moffatt  <hamish at cloud.net.au> wrote:
>jm.suresh at no.spam.gmail.com wrote:
>>>>> def div_ceil(a, b):
>> ...     if a%b:
>> ...         return ((a/b)+1)
>> ...     else:
>> ...         return (a/b)
>
>Yes, although it's not as short or as fast (probably as my version):
>
>def div_ceil(a, b):
>     return ((a+(b-1))/b)

If that's what you care about:

$ python -mtimeit -s 'def divc1(a,b): return (a+b-1)/b' 'divc1(3,2)'
1000000 loops, best of 3: 0.443 usec per loop
$ python -mtimeit -s 'def divc2(a,b): return -(-a/b)' 'divc2(3,2)'
1000000 loops, best of 3: 0.331 usec per loop

Also, note:

>>> divc2(sys.maxint, 2)
1073741824
>>> divc1(sys.maxint, 2)
1073741824L

which is going to cause problems with sys.version_info < (2, 3) .
(Or do I mean (2, 2)? I don't have a 2.2 to hand.)

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
        -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list