Advertisement
pojler

Labki 5

Oct 25th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1.  
  2. package lab5;
  3.  
  4. class Rational {
  5. ///////////////////////////////utilities/////////////////////////////
  6. int NWD(int a, int b)
  7. { if(a==0)
  8. {
  9. return 1;
  10. }
  11. int c = a;
  12. int d = b;
  13. while (c != d)
  14. {
  15. if (c>d)
  16. {
  17. c -= d;
  18. }
  19. else
  20. {
  21. d -= c;
  22. }
  23.  
  24. }
  25. return c;
  26. }
  27.  
  28. ////////////////////////////////////fields////////////////////////////////
  29.  
  30. private int l = 0, m = 0, c = 0;
  31. ////////////////////////constructors//////////////////////////////////////
  32.  
  33. Rational (int a, int b)
  34. {
  35. l = a;
  36. m = b;
  37.  
  38. }
  39. Rational ( int a)
  40. {
  41. this (a,1);
  42. }
  43. ////////////////////////methods/////////////////////////
  44.  
  45. Rational short_rat()
  46. { if (l ==0)
  47. {
  48. return this;
  49. }
  50. int nwd = NWD(l, m);
  51. l = l/nwd;
  52. m = m/nwd;
  53. c = l/m;
  54. if (c != 0)
  55. {
  56. l = l-c*m;
  57. }
  58.  
  59. return this;
  60.  
  61. }
  62.  
  63. Rational addition (Rational b)
  64. {
  65. return new Rational (l*b.m + m*b.l, m*b.m );
  66.  
  67. }
  68.  
  69. Rational substraction (Rational b)
  70. {
  71. return new Rational (l*b.m - m*b.l, m*b.m );
  72. }
  73.  
  74. Rational multipli (Rational b)
  75. {
  76. return new Rational (l*b.l, m*b.m );
  77. }
  78.  
  79. Rational reverse()
  80. {
  81. return new Rational (m,l);
  82. }
  83. Rational divide (Rational b)
  84. {
  85. return new Rational (l*b.m, m*b.l);
  86. }
  87.  
  88.  
  89. public String toString()
  90. {
  91. short_rat();
  92. if (c == 0 && l != 0)
  93. {
  94. return l+"/"+m;
  95. }
  96. else if (l == 0 && c == 0 )
  97. {
  98. return Integer.toString(0);
  99. }
  100. else if (c != 0 && l == 0)
  101. {
  102. return Integer.toString(c);
  103. }
  104.  
  105.  
  106. else
  107. {
  108. return c+" "+l+"/"+m;
  109. }
  110. }
  111. }
  112.  
  113.  
  114.  
  115. public class Lab5 {
  116.  
  117.  
  118.  
  119.  
  120. public static void main(String[] args) {
  121.  
  122.  
  123. Rational x = new Rational(1,2);
  124. Rational y = new Rational(3,4);
  125. Rational z = new Rational(3,4);
  126. Rational a = new Rational(5,6);
  127. System.out.println(x.addition(y).divide(z.substraction(a)).short_rat());
  128.  
  129.  
  130.  
  131. }
  132. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement