-2
public class Main   
{
    public static void main(String[] args) 
 {
       Rational a = new Rational(1,2);
       Rational b = new Rational(1,4);
             System.out.println(a + " + " + b + " = " + a.add(b));
             System.out.println(a + " - " + b + " = " + a.sub(b));
             System.out.println(a + " * " + b + " = " + a.mul(b)); 
             System.out.println(a + " / " + b + " = " + a.div(b));
}
}


 class Rational
 {

private int numerator, denominator;
public Rational (int numer, int denom)
{
   if (denom == 0)
      denom = 1;
   if (denom < 0)
   {
      numer = numer * -1;
      denom = denom * -1;
   }

   numerator = numer;
   denominator = denom;   
}


public Rational add (Rational b)
{
   
   int commonDenominator = denominator * b.getDenominator();
   int numerator1 = numerator * b.getDenominator();
   int numerator2 = b.getNumerator() * denominator;
   int sum = numerator1 + numerator2;

   return new Rational (sum, commonDenominator);
}

public Rational sub(Rational b) {
           int commonDenominator = denominator * b.getDenominator();
           int numerator1 = numerator * b.getDenominator();
           int numerator2 = b.getNumerator() * denominator;
           int difference = numerator1 - numerator2;

       return new Rational (difference, commonDenominator);
}   
  public Rational mul(Rational b) {
    int numer = numerator * b.getNumerator();
       int denom = denominator * b.getDenominator();

       return new Rational (numer, denom);
    
}
public Rational div(Rational b) {
     return mul (b.reciprocal());
}
public int getNumerator ()
{
   return numerator;
}

public int getDenominator ()
{
   return denominator;
}

public Rational reciprocal ()
{
   return new Rational (denominator, numerator);
}
public String toString ()
{
   String result;

   if (numerator == 0)
      result = "0";
   else
      if (denominator == 1)
         result = numerator + "";
      else
         result = numerator + "/" + denominator;
 
   return result;
 }
}

I have all of these done: constructor add sub mul div toString i just need the gcd and a testing method, I'm not sure how to implement the GCD into my code, if anyone could help, that would be great.

Wenfang Du
  • 8,804
  • 9
  • 59
  • 90

1 Answers1

0

Here's the pseudocode for it, taken from Wikipedia, as well as the recursive version. You should be able to implement either of them in Java. I would have posted this as a comment, since it's not really an answer, but the formatting would have been terrible.

function gcd(a, b)
    while b ≠ 0
       t := b; 
       b := a mod b; 
       a := t; 
    return a;

function gcd_r(a,b) {
    if (b = 0) {
        return a;
    }
    return gcd_r( b, a mod b );
}
David Choweller
  • 1,060
  • 1
  • 8
  • 7