tterrag1098

Untitled

May 9th, 2018
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. private static class Fraction extends Number {
  2.  
  3. public final int num, denom;
  4.  
  5. public Fraction() {
  6. this(0);
  7. }
  8.  
  9. public Fraction(int num) {
  10. this(num, 1);
  11. }
  12.  
  13. public Fraction(int num, int denom) {
  14. if (denom == 0) {
  15. throw new IllegalStateException("Invalid fraction.");
  16. }
  17. // Move negative sign to numerator
  18. if (denom < 0) {
  19. num = -num;
  20. denom = -denom;
  21. }
  22. // Always simplify fractions. Since fractions are immutable, this guarantees simplification of all fractions.
  23. int gcd = euclidGcd(num, denom);
  24. if (gcd > 1) {
  25. num /= gcd;
  26. denom /= gcd;
  27. }
  28. this.num = num;
  29. this.denom = denom;
  30. }
  31.  
  32. public Fraction inverse() {
  33. if (num == 0) {
  34. return this;
  35. }
  36. return new Fraction(denom, num);
  37. }
  38.  
  39. public Fraction add(Fraction other) {
  40. int lcm = lcm(denom, other.denom);
  41. int newNum = scaleNumerator(lcm) + other.scaleNumerator(lcm);
  42. return new Fraction(newNum, lcm);
  43. }
  44.  
  45. public Fraction sub(Fraction other) {
  46. int lcm = lcm(denom, other.denom);
  47. int newNum = scaleNumerator(lcm) - other.scaleNumerator(lcm);
  48. return new Fraction(newNum, lcm);
  49. }
  50.  
  51. public Fraction mul(Fraction other) {
  52. return new Fraction(num * other.num, denom * other.denom);
  53. }
  54.  
  55. public int scaleNumerator(int denom) {
  56. if (num == 0) return 0;
  57. if (denom % this.denom != 0) {
  58. throw new IllegalArgumentException("Given denominator is not a multiple of the current denominator");
  59. }
  60. return num * (denom / this.denom);
  61. }
  62.  
  63. @Override
  64. public double doubleValue() {
  65. return (double) num / denom;
  66. }
  67.  
  68. @Override
  69. public float floatValue() {
  70. return (float) num / denom;
  71. }
  72.  
  73. @Override
  74. public int intValue() {
  75. return (int) doubleValue();
  76. }
  77.  
  78. @Override
  79. public long longValue() {
  80. return (long) doubleValue();
  81. }
  82.  
  83. @Override
  84. public String toString() {
  85. return num + "/" + denom;
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment