Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Fraction {
- private int numerator;
- private int denominator;
- public Fraction(int n, int d) {
- this.numerator = n;
- this.denominator = d;
- }
- @Override
- public String toString() {
- String txt = this.numerator + "/" + this.denominator;
- return txt;
- }
- public Fraction multiply(Fraction other) {
- int n = this.numerator * other.numerator;
- int d = this.denominator * other.denominator;
- Fraction fr = new Fraction(n, d);
- fr.reduce();
- return fr;
- }
- public Fraction divide(Fraction other) {
- int n = this.numerator * other.denominator;
- int d = this.denominator * other.numerator;
- Fraction fr = new Fraction(n, d);
- fr.reduce();
- return fr;
- }
- public Fraction sum(Fraction other) {
- int n = this.numerator * other.denominator + this.denominator * other.numerator;
- int d = this.denominator * other.denominator;
- Fraction fr = new Fraction(n, d);
- fr.reduce();
- return fr;
- }
- public Fraction subtract(Fraction other) {
- int n = this.numerator * other.denominator - this.denominator * other.numerator;
- int d = this.denominator * other.denominator;
- Fraction fr = new Fraction(n, d);
- fr.reduce();
- return fr;
- }
- public void reduce() {
- int nod = gcd(this.denominator, this.numerator);
- this.numerator /= nod;
- this.denominator /= nod;
- }
- private int gcd(int a, int b) {
- if (b == 0) {
- return a;
- } else {
- return gcd(b, a % b);
- }
- }
- }
Add Comment
Please, Sign In to add comment