Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform ceiling-division in integer arithmetic? [duplicate]

It's basically returning the boxes_needed. 1 box can contain 10 items. So if the items typed by the user is 102 then the code should return 11 boxes.

Is there a way to divide that rounds upwards if there is a non-zero remainder?

like image 702
Newbie_Android Avatar asked Oct 23 '15 09:10

Newbie_Android


2 Answers

For your use case, use integer arithmetic. There is a simple technique for converting integer floor division into ceiling division:

items = 102
boxsize = 10
num_boxes = (items + boxsize - 1) // boxsize

Alternatively, use negation to convert floor division to ceiling division:

num_boxes = -(items // -boxsize)
like image 28
Raymond Hettinger Avatar answered Oct 08 '22 00:10

Raymond Hettinger


Negate before and after?

>>> -(-102 // 10)
11
like image 169
Stefan Pochmann Avatar answered Oct 07 '22 23:10

Stefan Pochmann