private BigFloat Factor() { //factoring can be very slow. So use only when neccessary (ToString, and comparisons) if (denominator == 1) { return(this); } //factor numerator and denominator BigInteger factor = BigInteger.GreatestCommonDivisor(numerator, denominator); numerator /= factor; denominator /= factor; return(this); }
public BigRational(BigInteger numerator, BigInteger denominator) { if (denominator.IsZero) { numerator = numerator.Sign; } else if (numerator.IsZero) { denominator = BigInteger.One; } else { var pgcd = BigInteger.GreatestCommonDivisor(numerator, denominator); if (denominator.Sign < 0) { pgcd = -pgcd; } numerator /= pgcd; denominator /= pgcd; } Numerator = numerator; Denominator = denominator; }
// Least Common Denominator (LCD) // // The LCD is the least common multiple of the two denominators. For instance, the LCD of // {1/2, 1/4} is 4 because the least common multiple of 2 and 4 is 4. Likewise, the LCD // of {1/2, 1/3} is 6. // // To find the LCD: // // 1) Find the Greatest Common Divisor (GCD) of the denominators // 2) Multiply the denominators together // 3) Divide the product of the denominators by the GCD public static BigInteger LeastCommonDenominator(BigRational x, BigRational y) { // LCD( a/b, c/d ) == (bd) / gcd(b,d) return (x.Denominator * y.Denominator) / BigInteger.GreatestCommonDivisor(x.Denominator, y.Denominator); }