Created
October 28, 2012 21:11
-
-
Save benfb/3969923 to your computer and use it in GitHub Desktop.
GCD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GCD | |
{ | |
//instance variables - DO NOT ADD ANY MORE INSTANCE VARIABLES | |
private int numerator; | |
private int denominator; | |
//default constructor | |
public GCD() | |
{ | |
numerator = 0; //initiates numerator variable | |
denominator = 0; //initiates denominator value | |
} | |
//initialization constructor | |
public GCD(int n, int d) | |
{ | |
numerator = n; | |
denominator = d; | |
} | |
//modifier method for numerator | |
public void setN(int n) | |
{ | |
numerator = n; //sets instance variable numerator equal to n | |
} | |
//modifier method for denominator | |
public void setD(int d) | |
{ | |
denominator = d; | |
} | |
//accessor method for numerator | |
public int getN() | |
{ | |
return numerator; | |
} | |
//accessor method for denominator | |
public int getD() | |
{ | |
return denominator; | |
} | |
//method to determine gcd | |
public int gcd() | |
{ | |
int gcd = 1; | |
if(numerator > denominator) //chooses which number to start at for the gcd | |
gcd = denominator; | |
else{ gcd = numerator; } | |
while((numerator % gcd != 0) || (denominator % gcd != 0)) //while numerator or the denominator does not divide equally by the current gcd | |
gcd--; | |
return gcd; | |
} | |
//method to determine lowest term of numerator | |
public int lnum() | |
{ | |
int lnum = numerator/gcd(); | |
return lnum; | |
} | |
//method to determine lowest term of denominator | |
public int lden() | |
{ | |
int lden = denominator/gcd(); | |
return lden; | |
} | |
//toString() method | |
public String toString() | |
{ | |
return "The GCD is: " + gcd() + "\nThe fraction in lowest terms is: " + lnum() + "/" + lden(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment