Last active
May 27, 2017 23:23
-
-
Save LuxXx/c93249afce76b89745d461bcd8bbe405 to your computer and use it in GitHub Desktop.
Fraction
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 Fraction { | |
public static final Fraction ONE = new Fraction(1); | |
public static final Fraction TWO = new Fraction(2); | |
public static final Fraction TEN = new Fraction(10); | |
private long num; | |
private long denom; | |
public Fraction(long num, long denom) { | |
super(); | |
this.num = num; | |
if (denom == 0) throw new Error("Cannot instantiate a fraction with 0 as denominator"); | |
this.denom = denom; | |
simplify(); | |
} | |
public Fraction(long num) { | |
this(num, 1); | |
} | |
public Fraction multiply(Fraction val) { | |
return new Fraction(num * val.num, denom * val.denom).simplify(); | |
} | |
public Fraction divide(Fraction val) { | |
return new Fraction(num * val.denom, denom * val.num).simplify(); | |
} | |
public Fraction add(Fraction val) { | |
return new Fraction(num * val.denom + val.num * denom, denom * val.denom).simplify(); | |
} | |
public Fraction subtract(Fraction val) { | |
return new Fraction(num * val.denom - val.num * denom, denom * val.denom).simplify(); | |
} | |
public Fraction simplify() { | |
long gcd = gcd(num, denom); | |
num = num / gcd; | |
denom = denom / gcd; | |
return this; | |
} | |
private static long gcd(long a, long b) { | |
while (b > 0) { | |
long temp = b; | |
b = a % b; | |
a = temp; | |
} | |
return a; | |
} | |
// private static long lcm(long a, long b) { | |
// return a * (b / gcd(a, b)); | |
// } | |
public double doubleValue() { | |
return (double) num / denom; | |
} | |
@Override | |
public String toString() { | |
return num + "/" + denom; | |
} | |
@Override | |
public boolean equals(Object obj) { | |
if (!(obj instanceof Fraction)) | |
return false; | |
Fraction that = (Fraction) obj; | |
return ((long) num) * that.denom == ((long) that.num) * denom; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment