// Operator overloading public static BigRational operator +(BigRational num1, BigRational num2) { if (num1.Denominator == num2.Denominator) { // The denominators are the same; just add the numerators and return. return new BigRational(num1.Numerator + num2.Numerator, num1.Denominator); } else { // Make the denominator the same, reduce it, and return it. BigRational retval = new BigRational ((num1.Numerator * num2.Denominator) + (num2.Numerator * num1.Denominator), num1.Denominator * num2.Denominator); retval.Reduce(); return retval; } }
// I don't want to call it scalar multiplication... but it's scalar multiplication if you consider the BigRational a 1x2 matrix. public static BigRational operator *(BigRational num1, BigInteger num2) { BigRational retVal = new BigRational(num1.Numerator * num2, num1.Denominator); retVal.Reduce(); return retVal; }
/// <summary> /// Returns the BigRational raised to the specified power. /// </summary> /// <param name="power">An integer greater than or equal to one.</param> /// <returns></returns> public BigRational Pow(BigInteger power) { // Error checking if (power < 1) throw new ArgumentException("BigRational.Pow only supports integer powers greater than or equal to one."); BigRational retVal = new BigRational(Numerator, Denominator); // Create a copy of the current BigRational for (BigInteger i = 1; i < power; i++) // Multiply the copy by itself power - 1 number of times { retVal.Numerator *= Numerator; retVal.Denominator *= Denominator; } retVal.Reduce(); return retVal; }
public static BigRational operator *(BigRational num1, BigRational num2) { // a/b * c/d = ac/bd BigRational retVal = new BigRational(num1.Numerator * num2.Numerator, num1.Denominator * num2.Denominator); retVal.Reduce(); return retVal; }
public static BigRational operator -(BigRational num1, BigRational num2) { // Same as + but we subtract here... if (num1.Denominator == num2.Denominator) { // The denominators are the same; just add the numerators and return. return new BigRational(num1.Numerator - num2.Numerator, num1.Denominator); } else { // Make the denominator the same, reduce it, and return it. BigRational retval = new BigRational((num1.Numerator * num2.Denominator) - (num2.Numerator * num1.Denominator), num1.Denominator * num2.Denominator); retval.Reduce(); return retval; } }