I'm looking for an overflow-safe method to perform round division of unsigned integers.
I have this:
uint roundDiv(uint n, uint d)
{
return (n + d / 2) / d;
}
But unfortunately, the expression n + d / 2
may overflow.
I think that I will have to check whether or not n % d
is smaller than d / 2
.
But d / 2
itself may truncate (when d
is odd).
So I figured I should check whether or not n % d * 2
is smaller than d
.
Or even without a logical condition, rely on the fact that n % d * 2 / d
is either 0
or 1
:
uint roundDiv(uint n, uint d)
{
return n / d + n % d * 2 / d;
}
This works well, however once again, n % d * 2
may overflow.
Is there any custom way to achieve round integer division which is overflow-safe?
Update
I have come up with this:
uint roundDiv(uint n, uint d)
{
if (n % d < (d + d % 2) / 2)
return n / d;
return n / d + 1;
}
Still, the expression d + d % 2
may overflow.