Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static Fraction simplifyFraction(Fraction f)
- throws ArithmeticException {
- int denominator = f.getDenominator();
- int numerator = f.getNumerator();
- int sign = 1;
- int smaller;
- int factorLimit; // the largest of the lower of potential factor pairs
- // check for division by zero
- if (denominator == 0) {
- throw new ArithmeticException("division by zero");
- }
- // check the sign and keep only the magnitude until the return
- if ((long) denominator * (long) numerator < 0) {
- denominator = Math.abs(denominator);
- numerator = Math.abs(numerator);
- sign = -1;
- }
- // check which number is larger and whether the larger is an even
- // multiple of the smaller
- if (numerator < denominator) {
- if (denominator % numerator == 0) {
- return new Fraction(1 * sign, denominator / numerator);
- }
- smaller = numerator;
- } else {
- if (numerator % denominator == 0) {
- return new Fraction(numerator / denominator * sign, 1);
- }
- smaller = denominator;
- }
- factorLimit = (int) Math.abs(smaller);
- for (int i = 2; i < factorLimit; i++) {
- int factorCandidate1 = i;
- int factorCandidate2 = (smaller / i);
- if (numerator % factorCandidate1 == 0
- && denominator % factorCandidate1 == 0) {
- numerator /= factorCandidate1;
- denominator /= factorCandidate1;
- }
- if (denominator % factorCandidate2 == 0
- && numerator % factorCandidate2 == 0) {
- numerator /= factorCandidate2;
- denominator /= factorCandidate2;
- }
- }
- return new Fraction(numerator * sign, denominator);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement