Understanding CEILING Macros

I found the following macro in the utility header in our code base:

#define CEILING(x,y) (((x) + (y) - 1) / (y))

Which (using this answer ) I analyzed how:

// Return the smallest multiple N of y such that:
//   x <= y * N

But no matter how much I look at how this macro is used in our code base, I cannot understand the meaning of such an operation. None of the posts has been commented, which seems to indicate that this is obvious.

Can anyone suggest an English precedent explanation for this macro? This is probably dazzlingly obvious, I just don’t see it ...

+5
source share
5 answers

, (: , ); , X? Y, : CEILING(X,Y)

+5

C, ,

y = a / b

, , .. 5 / 2 == 2, -5 / 2 == -2. , 5 / 2 == 3, , , n , n / sizeof(int) , , .

, : CEILING(5,2) == 3, , y, .

+5

CEILING(6, 3) = (6 + 3 -1) / 3 = 8 / 3 = 2 // integer division
CEILING(7, 3) = (7 + 3 -1) / 3 = 9 / 3 = 3
CEILING(8, 3) = (8 + 3 -1) / 3 = 10 / 3 = 3
CEILING(9, 3) = (9 + 3 -1) / 3 = 11 / 3 = 3
CEILING(10, 3) = (9 + 3 -1) / 3 = 12 / 3 = 4

, , z, : z * y >= x.

:

CEILING(k*y, y) = (k*y + y -1) / y = ((k+1)*y - 1) / y = k
CEILING(k*y + 1, y) = ((k*y + 1) + y -1) / y = ((k+1)*y) / y = k + 1
CEILING(k*y + 2, y) = ((k*y + 2) + y -1) / y = ((k+1)*y + 1) / y = k + 1
....
CEILING(k*y + y - 1, y) = ((k*y + y - 1) + y -1) / y = ((k+1)*y + y - 2) / y = k + 1
CEILING(k*y + y, y) = ((k*y + y) + y -1) / y = ((k+1)*y + y - 1) / y = k + 1
CEILING(k*y + y + 1, y) = ((k*y + y + 1) + y -1) / y = ((k+2)*y) / y = k + 2

, , , ..

. y.

, .

+3

... ... 5. 47 , . ? = (47,5) = ((47 + 5) - 1)/5 = 51/5 = 10 ( - ).

+3
source

CEILING(x,y)gives, assuming y > 0, a ceiling x/y(mathematical division). One use case for this would be a simple sieve, starting with an offset x, where you would mark all multiples of a simple ysieve in the range as composites.

+2
source

All Articles