Exemplo n.º 1
0
        /// <summary>
        /// Create a new instance of <see cref="Fraction" /> with a numerator and denominator.
        /// </summary>
        /// <remarks>
        /// When creating an instance of <see cref="Fraction" /> it will always be in its simplest form.
        /// </remarks>
        /// <param name="numerator">Numerator for the fraction.</param>
        /// <param name="denominator">Denominator for the fraction.</param>
        public Fraction(int numerator, int denominator = 1)
        {
            if (denominator == 0)
            {
                throw new ArgumentException(nameof(denominator));
            }

            Sign = numerator < 0 ^ denominator < 0 ? -1 : 1;

            Numerator   = Math.Abs(numerator);
            Denominator = Math.Abs(denominator);

            var gcd = NumberTheory.GreatestCommonDivisor(Numerator, Denominator);

            Numerator   /= gcd;
            Denominator /= gcd;

            if (Denominator == 1)
            {
                ProperNumerator = 0;
            }
            else
            {
                ProperNumerator = Numerator < Denominator ? Numerator : Numerator % Denominator;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Compare the <see cref="Fraction" /> with another fraction.
        /// </summary>
        /// <param name="other">The <see cref="Fraction" /> to compare against.</param>
        /// <returns>-1 if it is less, 0 if equal, 1 if it is greater.</returns>
        public int CompareTo(Fraction other)
        {
            var lcm            = NumberTheory.LeastCommonMultiple(Denominator, other.Denominator);
            var leftNumerator  = Numerator * lcm / Denominator;
            var rightNumerator = other.Numerator * lcm / other.Denominator;

            return(leftNumerator.CompareTo(rightNumerator));
        }
Exemplo n.º 3
0
        public static Fraction operator-(Fraction left, Fraction right)
        {
            var newDenominator = NumberTheory.LeastCommonMultiple(left.Denominator, right.Denominator);
            var newNumerator   = left.Sign * left.Numerator * newDenominator / left.Denominator
                                 - right.Sign * right.Numerator * newDenominator / right.Denominator;

            return(new Fraction(newNumerator, newDenominator));
        }