.NET Math Quiz

I’ve been having a lot of fun with this post on .NET Undocumented.

If x, y, z are ints, …

1. If x < 0, then -x > 0.

False, unchecked(-int.MinValue) == int.MinValue.

2. If x = -x, then x = 0.

False (see 1)

3. If x - y > 0, then x > y.

False, unchecked(int.MinValue - int.MaxValue) == 1

4. If x and y are positive, then x + y > x.

False, unchecked(int.MaxValue + 1) < int.MaxValue

5. If x and y are positive, then (double)x * (double)y = (long)x * (long)y.

True – I don’t think this can’t be broken over the range of the integers. Not so over the longs, though.

6. If x - y > 0 and y - z > 0, then x - z > 0.

False, use

int x = int.MaxValue-1;

int y = -1;

int z = int.MinValue;

This gives you x - y == int.MaxValue, y - z == int.MaxValue, and x - z == -1.


If x, y, z are doubles, …

1. x = x.

False. double.NaN != double.NaN.

2. If x > y is false, then x < = y is true.

False – use double.NaN for both.

3. If x > 0, then x - x = 0.

False. double.PositiveInfinity - double.PositiveInfinity == double.NaN

4. If x and y are positive integers, then x + y > x.

This is true because at the boundary condition, double.MaxValue + double.MaxValue == double.PositiveInfinity.

Note that this is different from the behavior of longs or ints. It is only true for integer doubles, though, because x + double.Epsilon == x.

5. If x and y are integers and x > 0, then the statement “x + y = x for all y” is false for all x.

True.

6. If x <= 0 is false, then x > 0.

Both statements are false for double.NaN.

7. If x and y are longs, then (double)(x + y) = (long)(x + y).

This is true because of the order of operations, but it does not hold for (double)x + (double)y.

8. if x.Equals(y), then x = y.

This is false for double.NaN.

9. If x.Equals(-x), then x = 0.

This is false for double.NaN.

10. if x.ComparesTo(y) < 0, then x < y.

This is false where x is double.NaN.

Note: You don’t need to use the unchecked keyword for the counterexamples using it to be valid; it is easy enough to come up with examples that will pass as long as runtime checks are off. I just used it so that my answers would be brief and would compile.

Tags: , ,

Leave a Reply