Is there an easy, efficient and correct (i.e. not involving conversions to/from double) way to do floored integer division (like e.g. Python offers) in C#.
In other words, an efficient version of the following, that does not suffer from long/double conversion losses.
(long)(Math.Floor((double) a / b))
or does one have to implement it oneself, like e.g.
static long FlooredIntDiv(long a, long b)
{
if (a < 0)
{
if (b > 0)
return (a - b + 1) / b;
// if (a == long.MinValue && b == -1) // see *) below
// throw new OverflowException();
}
else if (a > 0)
{
if (b < 0)
return (a - b - 1) / b;
}
return a / b;
}
*) Although the C# 4 spec of the Division operator leaves it open whether OverflowException
is raised inside unchecked
, in reality it does throw (on my system) and the Visual Studio .NET 2003 version even mandated it throw:
If the left operand is the smallest representable int or long value and the right operand is –1, [..] System.OverflowException is always thrown in this situation, regardless of whether the operation occurs in a checked or an unchecked context.
Edit
The crossed out statements about checked
and unchecked
are all nice and well, but checked
is in fact only a compile time concept, so whether my function should wrap around or throw is up to me anyway, regardless of whether code calling the function is inside checked
or not.
Math.Floor
? – AsisMath.Floor
, but result is the same, it cuts off whole decimal part.Math.Floor
is redundant in this case. – Ballroom/
operator implementation. – Threefoldvar a = long.MinValue; var b = -1L;
ORvar a = long.MaxValue; var b = -1L;
. – Photojournalism