private static T GetSimplifiedRational <T>(IValueHelper <T> valueHelper, T n, T d, out T denominator) where T : struct, IComparable, IFormattable, IConvertible, IComparable <T>, IEquatable <T> { if (d.Equals(valueHelper.Zero)) { throw new DivideByZeroException(); } if (n.Equals(valueHelper.Zero)) { denominator = valueHelper.PositiveOne; return(valueHelper.Zero); } if (n.Equals(d)) { denominator = valueHelper.PositiveOne; return(valueHelper.PositiveOne); } if (d.CompareTo(valueHelper.Zero) < 0) { d = valueHelper.Multiply(d, valueHelper.NegativeOne); n = valueHelper.Multiply(n, valueHelper.NegativeOne); } T gcd = GetGCD <T>(valueHelper, n, d); denominator = valueHelper.Divide(d, gcd); return(valueHelper.Divide(n, gcd)); }
private static T GetNormalizedRational <T>(IValueHelper <T> valueHelper, T w, T n, T d, out T numerator, out T denominator) where T : struct, IComparable, IFormattable, IConvertible, IComparable <T>, IEquatable <T> { n = GetSimplifiedRational <T>(valueHelper, n, d, out denominator); if (n.Equals(valueHelper.Zero)) { numerator = n; return(w); } if (denominator.Equals(valueHelper.PositiveOne)) { numerator = valueHelper.Zero; return(valueHelper.Add(w, n)); } if (n.CompareTo(denominator) > 0) { numerator = valueHelper.Modulus(n, denominator); if (w.CompareTo(valueHelper.Zero) < 0) { w = valueHelper.Subtract(w, valueHelper.Divide(valueHelper.Subtract(n, numerator), denominator)); } else { w = valueHelper.Add(w, valueHelper.Divide(valueHelper.Subtract(n, numerator), denominator)); } numerator = GetSimplifiedRational <T>(valueHelper, numerator, denominator, out denominator); } else { numerator = n; } if (w.Equals(valueHelper.Zero)) { return(w); } if (numerator.CompareTo(valueHelper.Zero) < 0) { if (w.CompareTo(valueHelper.Zero) < 0) { w = valueHelper.Add(w, valueHelper.PositiveOne); } else { w = valueHelper.Subtract(w, valueHelper.PositiveOne); } numerator = valueHelper.Add(numerator, denominator); } return(w); }
private static T GetLCM <T>(IValueHelper <T> valueHelper, T d1, T d2, out T secondMultiplier) where T : struct, IComparable, IFormattable, IConvertible, IComparable <T>, IEquatable <T> { T zero = default(T); if (d1.CompareTo(zero) < 0) { return(GetLCM <T>(valueHelper, valueHelper.Abs(d1), d2, out secondMultiplier)); } if (d2.CompareTo(zero) < 0) { return(GetLCM <T>(valueHelper, d1, valueHelper.Abs(d2), out secondMultiplier)); } if (d1.Equals(d2)) { secondMultiplier = valueHelper.PositiveOne; return(secondMultiplier); } if (d1.CompareTo(d2) < 0) { secondMultiplier = GetLCM <T>(valueHelper, d2, d1, out d1); return(d1); } secondMultiplier = d1; while (!valueHelper.Modulus(secondMultiplier, d2).Equals(zero)) { secondMultiplier = valueHelper.Add(secondMultiplier, d1); } return(GetSimplifiedRational <T>(valueHelper, valueHelper.Divide(secondMultiplier, d1), secondMultiplier, out secondMultiplier)); }