private static T GetGCD <T>(IValueHelper <T> valueHelper, T d1, params T[] denominators) where T : struct, IComparable, IFormattable, IConvertible, IComparable <T>, IEquatable <T> { if (denominators == null || denominators.Length == 0) { return(d1); } T gcd = valueHelper.Abs(d1); foreach (T d in denominators) { T b; if (d.CompareTo(gcd) > 0) { b = gcd; gcd = valueHelper.Abs(d); } else { b = valueHelper.Abs(d); } while (b.CompareTo(valueHelper.Zero) > 0) { T rem = valueHelper.Modulus(gcd, b); gcd = b; b = rem; } } return(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)); }