waltermilner

Untitled

Jun 14th, 2016
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.74 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.  
  7.   public Rational(long a, long b) {
  8.     this.a = a;
  9.     this.b = b;
  10.   }
  11.  
  12.   public Rational(int a, int b) {
  13.     this.a = a;
  14.     this.b = b;
  15.   }
  16.  
  17.   private static Rational lowestForm(long a, long b) {
  18.     long x = a;
  19.     long y = b;
  20.     while (b != 0) {
  21.       long t = b;
  22.       b = a % b;
  23.       a = t;
  24.  
  25.     }
  26.     return new Rational(x / a, y / a);
  27.   }
  28.  
  29.   public String toString() {
  30.     return a + "/" + b;
  31.   }
  32.  
  33.   public Rational add(Rational other) {
  34.     return lowestForm(a * other.b + b * other.a, b * other.b);
  35.   }
  36.  
  37.   public Rational div(Rational other) {
  38.     return lowestForm(a * other.b, b * other.a);
  39.   }
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment