Jon Slaughter <Jo***********@Hotmail.comwrote:
If it is integer variables you do not need Math.Ceiling:
double d = (a + b - 1) / b;
um,. if the lhs is done using all integer arithmetic then
(a + b - 1)/b = a/b + 1 - 1/b
You're applying algebra to split the whole thing up, which doesn't take
rounding into account. The rounding is only applied once in Arne's
post, instead of three times with your dissection.
but 1/b = 0
so your left with a/b + 1 which is the ceiling of course(since a/b is floor)
but no reason to subtract 1.
Yes there is. Take a=8, b=4. The ceiling of a/b is 2, but if you use
(a+b)/b you end up with 3. Take (a+b-1)/b you get 11/4 which is rounded
down to 2, the correct answer.
Point is, is that its unecessary to subtract 1/b as it does absolutely
nothing in integer arithmetic.
So rather,
int d = a / b + 1;
Again, that's wrong - when b is exactly divisible by a, the answer is
incorrect.
Not that your wrong but just wanted to clear up that issue.
Arne was absolutely correct, and you are wrong to apply algebra and
then integer division to each part and assume it's the same answer as
applying integer division to the original expression.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too