-
-
Save anonymous/621a2f4bdeb33486ed3776d822d6348b to your computer and use it in GitHub Desktop.
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 HelloWorld { | |
public static void main(String[] args) { | |
Rational a = new Rational(1, 6); | |
Rational b = new Rational(1, 3); | |
a.add(b); | |
a.output(); | |
} | |
} | |
class Rational | |
{ | |
private int numerator; | |
private int denominator; | |
Rational(int a, int b) { | |
this.numerator = a; | |
this.denominator = b; | |
} | |
Rational() { | |
this.numerator = 1; | |
this.denominator = 1; | |
} | |
void add(Rational r) { | |
int mother = lcm(this.denominator, r.denominator); | |
int son = this.numerator * (mother / this.denominator) + r.numerator * (mother / r.denominator); | |
this.numerator = son; | |
this.denominator = mother; | |
this.simplify(); | |
} | |
void product(Rational r) { | |
int son = this.numerator * r.numerator; | |
int mother = this.denominator * r.denominator; | |
this.numerator = son; | |
this.denominator = mother; | |
this.simplify(); | |
} | |
void divide(Rational r) { | |
int son = this.numerator * r.denominator; | |
int mother = this.denominator * r.numerator; | |
this.numerator = son; | |
this.denominator = mother; | |
this.simplify(); | |
} | |
void substract(Rational r) { | |
int mother = lcm(this.denominator, r.denominator); | |
int son = this.numerator * (mother / this.denominator) - r.numerator * (mother / r.denominator); | |
this.numerator = son; | |
this.denominator = mother; | |
this.simplify(); | |
} | |
void simplify() { | |
int gcd = gcd(this.numerator, this.denominator); | |
this.numerator /= gcd; | |
this.denominator /= gcd; | |
} | |
void output() { | |
System.out.printf("%d/%d", this.numerator, this.denominator); | |
} | |
int gcd(int a, int b) { | |
if ( b > a ) { | |
int temp = b; | |
b = a; | |
a = temp; | |
} | |
int mod = a % b; | |
if (mod == 0) { | |
return b; | |
} else { | |
return gcd(b, mod); | |
} | |
} | |
int lcm(int a, int b) { | |
return a * b / gcd(a, b); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment