waltermilner

Untitled

Aug 23rd, 2016
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. public class Rational {
  2.  
  3.   // the rational number a/b
  4.   private final long a;
  5.   private final long b;
  6.   // class is immutable
  7.  
  8.   // overloaded constructors
  9.   public Rational(long a, long b) {
  10.     this.a = a;
  11.     this.b = b;
  12.   }
  13.  
  14.   public Rational(int a, int b) {
  15.     this.a = a;
  16.     this.b = b;
  17.   }
  18.  
  19.   public Rational(int a)
  20.   {
  21.     this.a=a;
  22.     this.b=1;
  23.   }
  24.  
  25.   private static Rational lowestForm(long a, long b) {
  26.     long x = a;
  27.     long y = b;
  28.     while (b != 0) {
  29.       long t = b;
  30.       b = a % b;
  31.       a = t;
  32.  
  33.     }
  34.     return new Rational(x / a, y / a);
  35.   }
  36.  
  37.   public String toString() {
  38.     return a + "/" + b;
  39.   }
  40.  
  41.   public Rational add(Rational other) {
  42.     return lowestForm(a * other.b + b * other.a, b * other.b);
  43.   }
  44.  
  45.   public Rational div(Rational other) {
  46.     return lowestForm(a * other.b, b * other.a);
  47.   }
  48.  
  49. }
  50. public class Test {
  51.  
  52.   public static void main(String[] args) {
  53.  
  54.     Rational r1 = new Rational(1);
  55.     Rational r2 = new Rational(1,3);
  56.     Rational r3 = r1.add(r2);
  57.     System.out.println(r3); // 4/3
  58.  
  59.   }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment