# ceil() and int values

Discussion in 'C Programming' started by Test, Oct 13, 2013.

1. ### Eric SosmanGuest

It never struck me as either clever or hackish, but only as a
fairly obvious transformation. (Decades ago I thought it up myself,
so it can't be *that* abstruse!)
Essentially the same thing is often done with multiples
of powers of two:

unsigned int nextEven = (value + 1u) & ~1u;
unsigned int nextSixteen = (value + 15u) & ~15u;
unsigned int nextK = (value + 1023u) & ~1023u;
// ... etc.

(`unsigned' because bit-twiddling's safer that way).
If it encounters overflow with "integers greater than zero
and less than 128" it's being run on a non-conforming or non-C
implementation.

Eric Sosman, Oct 18, 2013

2. ### Phil CarmodyGuest

When i2's big, the risk of overflow is certainly possible. However,
there's an alternative which shrinks the overflow window to be at
the other end of the range, shrinking it into all but non-existence:

i = (i5-1)/i2 + 1;

Phil

Phil Carmody, Oct 20, 2013

3. ### blmblmGuest

Um. If i5 = 0 and i2 = 2 ....

((i5 + i2 - 1) / i2) == ( (0+2-1)/2 ) == ( 1/2 ) == 0

but

((i5 - 1) / i2 + 1) == ( (0-1)/2 + 1 ) == ( (-1/2) + 1 ) == 1

no?

blmblm, Oct 21, 2013
4. ### Phil CarmodyGuest

Good catch, due to infernal truncation towards zero. (Not a fan, it's
practical, rather than being mathematically pure, which is far more
important than being practical!)

I generally use this in contexts where I know I have a strictly
positive number. (Chunking work for cache friendlyness, for example.)

Thanks for pointing this out, it's a rather vital case.

Phil

Phil Carmody, Oct 21, 2013
5. ### Tim RentschGuest

Considering the quotient a/b

to divide rounding up: a/b + (a%b > 0)
to divide rounding down: a/b - (a%b < 0)

These expressions work for all signed (or unsigned) values of {a,b}
when the result is defined and representable, under both C90 and
C99/C11 operation rules.

Note also, on x86 I believe both quotient and remainder are
produced by a single instruction, so the speed should be okay
on those targets.

Tim Rentsch, Oct 22, 2013
6. ### Albert van der HorstGuest

I do this kind of thing all the time for math problems. http:/projecteuler.net/

Much faster is
i = (i5-1)/i2 + 1;

Or in stack pseudo code :
( i5 i2 -- ceil )
SWAP 1- SWAP / 1+

This works for all problems of this type.

Albert van der Horst, Oct 25, 2013
7. ### Ben BacarisseGuest

Except for negative numbers. I don't know if that matters to the OP,
but it might trip someone up using it as a general solution.

<snip>

Ben Bacarisse, Oct 26, 2013