fork download
  1. import java.lang.*;
  2.  
  3. class Rational {
  4. private int n, d;
  5.  
  6. public Rational (int n, int d) throws ArithmeticException {
  7. if (d == 0) throw new ArithmeticException("wrong ");
  8. int divisor = gcd(n,d);
  9. this.n = n/divisor;
  10. this.d = d/divisor;
  11. }
  12.  
  13. private static int gcd(int n, int d) {
  14. return ( d == 0 ? n: gcd(d, n%d));
  15. }
  16.  
  17. public static boolean equals(Rational x, Rational y) {
  18. if ( x.n != y.n || x.d != y.d) return false;
  19. else return true;
  20. }
  21.  
  22. public static Rational add(Rational x, Rational y) {
  23. return new Rational(x.n * y.d + y.n * x.d, x.d * y. d);
  24. }
  25.  
  26. public static Rational sub(Rational x, Rational y) {
  27. return new Rational(x.n * y.d - y.n * x.d, x.d * y. d);
  28. }
  29.  
  30. public static Rational mul(Rational x, Rational y) {
  31. return new Rational(x.n * y.n, x.d * y.d);
  32. }
  33.  
  34. public static Rational div(Rational x, Rational y) {
  35. return new Rational(x.n * y.d, x.d * y.n);
  36. }
  37.  
  38. public String toString() {
  39. return n + "/" + d;
  40. }
  41.  
  42. public static void cmp(Rational x, Rational y) {
  43. if ( ! equals(x,y)) {
  44. if ( (x.n * y.d ) > (y.n * x.d)) System.out.println( x.toString() + " > " + y.toString());
  45. else System.out.println( y.toString() + " > " + x.toString());
  46. }
  47. else System.out.println( x.toString() + " = " + y.toString());
  48. }
  49.  
  50. public static void main(String[] args) {
  51. try {
  52. Rational a = new Rational(4, 5);
  53. Rational b = new Rational(1, 2);
  54. Rational c = new Rational(2, 5);
  55. System.out.println("Equality - " + equals(a, b));
  56. System.out.println("Equality - " + equals(mul(a,b), c));
  57. System.out.println(c.toString() + "+" + b.toString() + "=" + add(c, b));
  58. System.out.println(a.toString() + "-" + b.toString() + "=" + sub(a, b));
  59. System.out.println(b.toString() + "-" + a.toString() + "=" + sub(b, a));
  60. System.out.println(c.toString() + "*" + b.toString() + "=" + mul(c, b));
  61. System.out.println(a.toString() + "%" + b.toString() + "=" + div(a, b));
  62. cmp(a,b);
  63. cmp(b,c);
  64. cmp(mul(a,b), c);
  65. }
  66. catch (ArithmeticException e) {
  67. System.out.println("dividing on 0");
  68. }
  69. }
  70. }
Success #stdin #stdout 0.04s 711168KB
stdin
Standard input is empty
stdout
Equality - false
Equality - true
2/5+1/2=9/10
4/5-1/2=3/10
1/2-4/5=-3/10
2/5*1/2=1/5
4/5%1/2=8/5
4/5 > 1/2
1/2 > 2/5
2/5 = 2/5