Advertisement
Guest User

Rationals

a guest
Sep 15th, 2012
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. public class Rational {
  2.    
  3.     // Creating instance variables for the numerator and denominator   
  4.     private long numerator;
  5.     private long denominator;
  6.    
  7.     // Constructor that creates a new Rational object, making sure the denominator is not 0 or negative.   
  8.     public Rational (long numer, long denom){
  9.        
  10.         if (denom == 0){
  11.             throw new RuntimeException("Error, can't have a denominator of 0.");
  12.         }
  13.        
  14.         if (denom <0){
  15.             denom = -denom;
  16.             numer = -numer;
  17.         }
  18.        
  19.         long greatestCommonDivisor = gcd(numer, denom);
  20.         numerator = numer / greatestCommonDivisor;
  21.         denominator = denom / greatestCommonDivisor;
  22.        
  23.     }
  24.    
  25.     // This method takes two rational numbers and adds them together   
  26.     public Rational plus(Rational b){
  27.         Rational answer = new Rational (this.numerator * b.denominator + b.numerator * this.denominator, b.denominator * this.denominator);
  28.        
  29.         return answer;
  30.     }
  31.    
  32.     //This method takes two rational numbers and subtracts them
  33.     public Rational minus (Rational b){
  34.         Rational answer = new Rational (this.numerator * b.denominator - b.numerator * this.denominator, b.denominator * this.denominator);
  35.        
  36.        
  37.         return answer;
  38.     }
  39.    
  40.     //This method takes two rational numbers and multiplies them
  41.     public Rational times (Rational b){
  42.         Rational answer = new Rational (this.numerator * b.numerator, this.denominator * b.denominator);
  43.        
  44.         return answer;
  45.     }
  46.    
  47.    
  48.    
  49.     // This method uses Euclid's algorithm  which calculates the greatest common divisor   
  50.     public static long gcd(long p, long q){
  51.         if (q==0) return p;
  52.         long r = p % q;
  53.         return gcd(q, r);
  54.     }
  55.  
  56.     // This method produces a string representation of values
  57.     public String toString(){
  58.         if (denominator == 1)
  59.             return numerator + "";
  60.         else
  61.             return numerator + "/" + denominator;
  62.     }
  63.    
  64.    
  65.     // Test client
  66.     public static void main (String args[]){
  67.         Rational p = new Rational (1, 6);
  68.         Rational q = new Rational (4, 8);
  69.        
  70.         Rational r = p.minus(q);
  71.         System.out.println(r);
  72.     }
  73.    
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement