You could create a class for ratio (with positive denominator).
It also makes sense to implement the IComparable
interface and comparison operators:
public class Ratio : IComparable<Ratio>
{
public readonly int A;
public readonly int B;
public Ratio(int a, int b)
{
if (b < 0)
{
a = -a;
b = -b;
}
A = a;
B = b;
}
public int CompareTo(Ratio other)
{
return A * other.B - B * other.A;
}
public static bool operator <(Ratio r1, Ratio r2)
{
return r1.CompareTo(r2) < 0;
}
public static bool operator >(Ratio r1, Ratio r2)
{
return r1.CompareTo(r2) > 0;
}
public static bool operator >=(Ratio r1, Ratio r2)
{
return r1.CompareTo(r2) >= 0;
}
public static bool operator <=(Ratio r1, Ratio r2)
{
return r1.CompareTo(r2) <= 0;
}
public static bool operator ==(Ratio r1, Ratio r2)
{
return r1.CompareTo(r2) == 0;
}
public static bool operator !=(Ratio r1, Ratio r2)
{
return r1.CompareTo(r2) != 0;
}
}
Sample usage:
var r1 = new Ratio(1, 10); // 1/10
var r2 = new Ratio(2, 20); // 2/20
Console.WriteLine(r1 >= r2); // true
Console.WriteLine(r1 > r2); // false
Console.WriteLine(r1 < r2); // false
Console.WriteLine(r1 == r2); // true
var r1 = new Ratio(1, 10); // 1/10
var r2 = new Ratio(1, 11); // 1/11
Console.WriteLine(r1 >= r2); // true
var r1 = new Ratio(1, 10); // 1/10
var r2 = new Ratio(1, 9); // 1/9
Console.WriteLine(r1 >= r2); // false
Or you could just use a logic of the CompareTo
method above.
For 2 ratios a/b
and c/d
where b,d > 0
:
a/b > c/d
is true when and only when a*d > c*b
.