a / b чисельник / знаменник b = b0; // НДС while (denom_ != 0) { b0 = a0 % (a0 = b0); } // скорочений дріб a = a / Math.Abs(a0); b = b / Math.Abs(a0); public class Program { public static void Main() { Calc.Reduce(2,4); } } public static class Calc { public static int gcd(int answerNumerator, int answerDenominator) { int x = Math.Abs(answerNumerator); int y = Math.Abs(answerDenominator); int m; if (x > y) m = y; else m = x; for (int i = m; i >= 1; i--) { if (x % i == 0 && y % i == 0) { return i; } } return 1; } public static void Reduce(int answerNumerator, int answerDenominator) { WriteFraction(answerNumerator, answerDenominator); try { int gcdNum = gcd(answerNumerator, answerDenominator); if (gcdNum != 0) { answerNumerator = answerNumerator / gcdNum; answerDenominator = answerDenominator / gcdNum; } if (answerDenominator < 0) { answerDenominator = answerDenominator * -1; answerNumerator = answerNumerator * -1; } } catch (Exception exp) { throw new InvalidOperationException("Cannot reduce Fraction: " + exp.Message); } WriteFraction(answerNumerator, answerDenominator); } public static void WriteFraction(int answerNumerator, int answerDenominator) { Console.WriteLine(string.Format(answerNumerator + "/" + answerDenominator)); } } |
Головна > Математика >