Is there an integer division operator rounding up? To make it so:

1 / N = 1 2 / N = 1 ... N / N = 1 N + 1 / N = 2 N + 2 / N = 2 ... 2N / N = 2 2N + 1 / N = 3 ... 

Or how can this be implemented without using mathematics, only on embedded primitives and integer data types?

UPD: there is no built-in, then is it possible to simplify the following function:

 int div_up(int x, int y) { return x / y + (x%y ? 1 : 0); } 
  • one
    There is no built-in one, but you can declare your class and assign operators to it. - nick_n_a

2 answers 2

I do not know how much simpler it is, but you can

 int div_up(int x, int y) { return (x + y - 1) / y; } 

Well, think what round up is for negative numbers

Update

To avoid possible overflow, the expression can be rewritten as

 int div_up(int x, int y) { return (x - 1) / y + 1; } 
  • thanks, your solution is easier - goldstar_labs
  • wait, there are a lot of smart people here, maybe they will still advise) - goldstar_labs
  • one
    Possible overflow (in x + y ) not confused? - avp
  • Great, along with ret fit into 5 teams (3 less than in question) - avp
  • 2
    The second option, unfortunately, behaves ugly on the zero divisible. - AnT

You can use the ceil() function from <math.h> . Examples can be viewed at the link: www.cplusplus.com

  • one
    The unjustified attraction of floating arithmetic to a pure integer problem is always desirable to avoid. - AnT