Reputation: 189
Guys this is the function to implement ceil function Which is working fine,I want to ask what is the logic behind subtracting -1 from denominator ?
I am new to programming
please Help
int checkceil(int numerator,int denominator){
return (numerator+denominator-1)/denominator;
}
Upvotes: 1
Views: 1147
Reputation: 26800
Since dividing two integers a
and b
will always floor
(truncate) the result, we need to find some d
(delta) such that floor(d + a/b) == ceil (a/b)
.
How do we find d
? Think about it this way:
ceil(a/b) > floor(a/b)
, except when (a/b)
is a whole number. So, we want to bump (a/b)
to (or past) the next whole number, unless (a/b)
is a whole number, by adding d
. This way floor(a/b + d)
will be equal to ceil(a/b)
. We want to find d
so that for whole numbers, it won’t quite push them up to the next whole number, but for non-whole numbers it will.
So how much d
is just enough?
So assuming (a/b)
is not a whole number, the smallest leftover we can have is (1/b)
. So in order to bump (a/b)
to the next whole number, it suffices to add d = 1 - (1/b)
. This is less than 1, which will not bump (a/b)
to the next whole number in case (a/b)
is a whole number, but still enough to bump (a/b)
to the next whole number in case (a/b)
is not a whole number.
Summing it up, we know adding d = 1 - (1/b)
to (a/b)
will fulfill the equality:
floor(a/b + d) = ceil(a/b)
. Thus we get:
ceil(a/b) = floor(a/b + d) = floor(a/b + 1 - 1/b) = floor((a + b - 1)/b)
When we write in terms of code it will be:
int myceil = (a + b - 1)/b;
Upvotes: 2
Reputation: 20027
The numerator n is of form n = a * d + b
, where b is the remainder of n / d. The remainder is by definition smaller than d.
In C, the division of n/d returns the integral part of a. When b == 0, one can add only d - 1 to n to get the same result (ad + 0)/d == (ad + d-1)/d. For all other remainders 0<b<d
, the division returns the next integer a+1, ie the ceiling.
Upvotes: 2