This program is a practise exercise in using instance methods, and also in recursion which I struggle to get my head around. I want to know how my technique for the recursion could be improved, and if there's anything else which could be made more efficient.
The program creates a Rational object type (a fraction) which has numerator and denominator variables. It runs a method to find the greatest common divisor using Euclid's algorithm, and then prints the simplified form of the fraction.
Any feedback is helpful, but things I'm interested in:
- Is there a more efficient way for me to take the two integers of input (which may both be positive or negative and in any size order) and turn them into two positive integers with the largest first? The if/else section I've used feels excessively big for the simplicity of the task but I couldn't think of another way.
- Is there a way that I could combine the getGcd and reduce methods into a single method? I couldn't work out how to make a method where a subsection of it is recursive but the rest isn't.
- Is there anything that could be improved about my recursive Euclid's algorithm bit? It's pretty simple but I wonder if I missed any tricks to make it extra efficient.
Code:
public class Rational {
public static void main(String[] args) {
Rational test = new Rational(-462, 1071);
System.out.println(test.reduce());
}
private int nume;
private int deno;
public Rational(int nume, int deno) {
this.nume = nume;
this.deno = deno;
}
public String toString() {
return this.nume + "/" + this.deno;
}
public Rational reduce() {
int gcd = this.getGcd();
return new Rational(this.nume / gcd, this.deno / gcd);
}
public int getGcd() {
// Set up variables
int a;
int b;
int gcd;
if (Math.abs(this.nume) > Math.abs(this.deno)) {
a = Math.abs(this.nume);
b = Math.abs(this.deno);
} else {
a = Math.abs(this.deno);
b = Math.abs(this.nume);
}
// Euclid's algorithm
if (a%b == 0) {
gcd = b;
return gcd;
} else {
gcd = new Rational(b, a%b).getGcd();
return gcd;
}
}
}