To quickly raise the result of integer division in C/C++

Asked 1 years ago, Updated 1 years ago, 129 views

I know that C/C++ always lowers the result of dividing int. I know that math.h has ceil(), but I want to know how to raise the header right away without including it.

My code is inefficient by comparing and multiplying it separately, but I want to know a better code.

q = x / y;
if (q * y < x) ++q;

algorithm c c++ math

2022-09-21 20:53

1 Answers

Code assuming that both x and y are positive.

q = (x + y - 1) / y;
q = 1 + ((x - 1) / y);


2022-09-21 20:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.