# Using Euclid's algorithm in a Fraction Class

• April 18th, 2013, 08:16 PM
Kristenw17
Using Euclid's algorithm in a Fraction Class
I am trying to use Euclid's Algorithm in a fraction class. I am not finished with the class yet so there are parts that are incomplete. I am unsure of how I would use the method. Would I put in the setter methods? or Public fraction (int n, int d)?

Code :

```public class Fraction{   private int numerator; private int denominator; int gcd;   public Fraction(){   }   public Fraction(int n, int d){ setNumerator(n); setDenominator(d);   }   public static int gcd(int p, int q) { if (q == 0) return p; else return gcd(q, p % q); }   public String toString(){ return String.format("%d/%d", getNumerator(), getDenominator()); }   public boolean equals(Object otherObject){ if(otherObject == null){ return false; }else{ if(!getClass().equals(otherObject.getClass())){ return false; }else{ Fraction otherFraction = (Fraction) otherObject; return getNumerator()== otherFraction.getNumerator() && getDenominator()== otherFraction.getDenominator();   } } }   public int getNumerator(){ return numerator; }   public void setNumerator(int newNumerator){ numerator = newNumerator/gcd; }   public int getDenominator(){ return denominator ; }   public void setDenominator(int newDenominator){ if(newDenominator == 0 ){ throw new IllegalStateException(String.format("Illegal denominator: %d", newDenominator)); } else{ denominator = newDenominator; } }   }```
• April 19th, 2013, 07:40 AM
Chris.Brown.SPE
Re: Using Euclid's algorithm in a Fraction Class
I'm not sure where you're going with this. It seems like you have a good start on it in your gcd method. You mention putting it in the setter methods or the constructor, what are you really trying to do with the algorithm? If you could give us a flow of what you're trying to accomplish it would be easier to help.

Example:
1. Create fraction
2. Call Euclid's Algorithm