Fast ceiling of an integer division in C C

most common architectures divide instruction also includes remainder in its result so this really needs only one division and would be very fast

What does losing a hand or arm to a crit mean if it was just a punch?

Could a humanoid species exist with vastly different heights?

Do modern aircraft require rudder input in order to perform a coordinated turn?

How to politely avoid eating with a colleague

Is any map homotopic to a map having fixed point?

mod requires division so its not just 1 division here, but maybe complier can optimize two similar divisions into one.

I dont know about the speed thing but its easy to understand. I give this two thumbs up. If only I was an octopus I could give it the truly well deserved eight thumbs up.

The obvious approach involves something like:

It depends on what you mean by easier. It may or may not be faster, depending on how the compiler translates it. My guess would be slower but I would have to measure it to be sure.

You could use thedivfunction in cstdlib to get the quotient & remainder in a single call and then handle the ceiling separately, like in the below

Why arent Java objects deleted immediately after they are no longer referenced?

Join Stack Overflowto learn, share knowledge, and build your career.

By posting your answer, you agree to theprivacy policyandterms of service.

When and why does bypassing XSS sanitizers with double encoding work?

Paladins source of spellcasting ability

q = x/y+((x%y!=0)?!((x0)^(y0)):0);

How about this? (requires y non-negative, so dont use this in the rare case where y is a variable with no non-negativity guarantee)

See Eric Lipperts /questions/921180/c-round-up/926806926806

Given integer valuesxandy, C and C++ both return as the quotientq = x/ythe floor of the floating point equivalent. Im interested in a method of returning the ceiling instead. For example,ceil(10/5)=2andceil(11/5)=3.

Sum of 4 dice rolls greater than the product

Start here for a quick overview of the site

Ist der Preis des Ripples gutes Deutsch?

Sign uporlog into customize your list.

voltage being zero in a short circuit

@LưuVĩnhPhc that comment should be the accepted answer, imo.

For signedx, negative and zero still combine into a single case.

site design / logo 2018 Stack Exchange Inc; user contributions licensed undercc by-sa 3.0withattribution required.rev2018.5.9.30331

Is the legacy of Marx & Engels unwarranted?

q = (x 0)? 1 + (x – 1)y: (x y);

Precise word to differentiate major and minor in music

Is it better to lie to students or to be pedantic when teaching Intro CS?

Learn more about hiring developers or posting ads with us

include cstdlib include iostream int div_ceil(int numerator, int denominator) std::div_t res = std::div(numerator, denominator); return res.rem ? (res.quot + 1) : res.quot; int main(int, const char**) std::cout 10 / 5 = div_ceil(10, 5) std::endl; std::cout 11 / 5 = div_ceil(11, 5) std::endl; return 0;

How to respond to empty compliments after many years of playing along?

There was an easier way to fix overflow, simply reduce y/y:

Was there a meaning to the design on Shuris shirt?

It will be slightly faster than the OPs code, because the modulo and the division is performed using the same instruction on the processor, because the compiler can see that they are equivalent. At least gcc 4.4.1 performs this optimization with -O2 flag on x86.

This works for positive or negative numbers.

How can a colony of teleporters make the most money while keeping their teleportation a secret?

No, it does not. As I explained in the answer, the % operator is free when you already perform the division.

As a final note, none of this matters on a modern machine, except if you are in an extremely tight loop and all your data is in registers or the L1-cache. Otherwise all of these solutions will be equally fast, except for possibly Nathan Ernsts, which might be significantly slower if the function has to be fetched from main memory.

I reducedy/yto one, eliminating the termx + y – 1and with it any chance of overflow.

is the ceiling of the division. C90 didnt specify how to round, and I dont think the current C++ standard does either.

I avoidx – 1wrapping around whenxis an unsigned type and contains zero.

Formula for delta between two numbers

Detailed answers to any questions you might have

Note, ifxis positive then division is towards zero, and we should add 1 if reminder is not zero.

Discuss the workings and policies of this site

Nathan Ernsts answer provides one solution, but it involves a function call, a variable declaration and a conditional, which makes it no shorter than the OPs code and probably even slower, because it is harder to optimize.

Learn more about Stack Overflow the company

Probably not a huge benefit on a modern general-purpose CPU, but this would be far faster in an embedded system than any of the other correct answers.

@LưuVĩnhPhc Seriously you need to add that as the answer. I just used that for my answer during a codility test. It worked like a charm though I am not certain how the mod part of the answer works but it did the job.

-1: this is an inefficient way, as it trades a cheap * for a costly %; worse than the OP approach.

Note: this will only work for positive numbers.

For a more generic answer,C++ functions for integer division with well defined rounding strategy

interesting, because there are common cases with y being constant

Access to constexpr variable inside lambda expression without capturing

q = 1 + ((x – 1) / y); // if x != 0

Do lightsaber blades/blaster bolts cast shadows?

@AndreasGrapentin the answer below by Miguel Figueiredo was submitted nearly a year before Lưu Vĩnh Phc left the comment above. While I understand how appealing and elegant Miguels solution is, Im not inclined to change the accepted answer at this late date. Both approaches remain sound. If you feel strongly enough about it, I suggest you show your support by up-voting Miguels answer below.

A private, secure home for your teams questions and answers.

I found the answer by Miguel Figueiredo after I left this comment. Yeah I did give him an upvote. Sorry for any confusion.

Note: This might overflow. q = ((long long)x + y – 1) / y will not. My code is slower though, so if you know that your numbers will not overflow, you should use Sparkys version.

Is there a common saying in English that means Its just business, I dont feel any shame

the divide instruction often returns both quotient and remainder at the same time so theres no need to multiply, just

Theres a solution for both positive and negativexbut only for positiveywith just 1 division and without branches:

As an interesting case of the double bang, you could also

@bitc: For negative numbers, I believe C99 specifies round-to-zero, so

The second one has a problem where x is 0. ceil(0/y) = 0 but it returns 1.

Doesnt ldiv always promote the arguments into long longs? And doesnt that cost anything, up-casting or down-casting?

Sparkys answer is one standard way to solve this problem, but as I also wrote in my comment, you run the risk of overflows. This can be solved by using a wider type, but what if you want to dividelong longs?

Ifxis negative then division is towards zero, thats what we need, and we will not add anything becausex % yis not positive

If there is a remainder, checks to see if x and y are of the same sign and adds 1 accordingly.

This requires an extra comparison and multiplication; and other methods Ive seen (used in fact) involve casting as afloatordouble. Is there a more direct method that avoids the additional multiplication (or a second division) and branch, and that also avoids casting as a floating point number?

In theory the compiler might inline the function call in Nathan Ernsts code and emit the same thing, but gcc didnt do that when I tested it. This might be because it would tie the compiled code to a single version of the standard library.

Fast ceiling of an integer division in C C

Leave a Comment