Advertisement
Guest User

Untitled

a guest
Jan 15th, 2013
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. public static Fraction simplifyFraction(Fraction f)
  2. throws ArithmeticException {
  3. int denominator = f.getDenominator();
  4. int numerator = f.getNumerator();
  5. int sign = 1;
  6. int smaller;
  7. int factorLimit; // the largest of the lower of potential factor pairs
  8.  
  9. // check for division by zero
  10. if (denominator == 0) {
  11. throw new ArithmeticException("division by zero");
  12. }
  13.  
  14. // check the sign and keep only the magnitude until the return
  15. if ((long) denominator * (long) numerator < 0) {
  16. denominator = Math.abs(denominator);
  17. numerator = Math.abs(numerator);
  18. sign = -1;
  19. }
  20.  
  21. // check which number is larger and whether the larger is an even
  22. // multiple of the smaller
  23.  
  24. if (numerator < denominator) {
  25. if (denominator % numerator == 0) {
  26. return new Fraction(1 * sign, denominator / numerator);
  27. }
  28. smaller = numerator;
  29. } else {
  30. if (numerator % denominator == 0) {
  31. return new Fraction(numerator / denominator * sign, 1);
  32. }
  33. smaller = denominator;
  34. }
  35.  
  36. factorLimit = (int) Math.abs(smaller);
  37.  
  38. for (int i = 2; i < factorLimit; i++) {
  39. int factorCandidate1 = i;
  40. int factorCandidate2 = (smaller / i);
  41.  
  42. if (numerator % factorCandidate1 == 0
  43. && denominator % factorCandidate1 == 0) {
  44. numerator /= factorCandidate1;
  45. denominator /= factorCandidate1;
  46. }
  47. if (denominator % factorCandidate2 == 0
  48. && numerator % factorCandidate2 == 0) {
  49. numerator /= factorCandidate2;
  50. denominator /= factorCandidate2;
  51. }
  52. }
  53.  
  54. return new Fraction(numerator * sign, denominator);
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement