vencinachev

Fraction class

Mar 13th, 2019
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1.  
  2.  
  3. public class Fraction {
  4.     private int numerator;
  5.     private int denominator;
  6.  
  7.     public Fraction(int n, int d) {
  8.         this.numerator = n;
  9.         this.denominator = d;
  10.     }
  11.  
  12.     @Override
  13.     public String toString() {
  14.         String txt = this.numerator + "/" + this.denominator;
  15.         return txt;
  16.     }
  17.  
  18.     public Fraction multiply(Fraction other) {
  19.         int n = this.numerator * other.numerator;
  20.         int d = this.denominator * other.denominator;
  21.         Fraction fr = new Fraction(n, d);
  22.         fr.reduce();
  23.         return fr;
  24.     }
  25.  
  26.     public Fraction divide(Fraction other) {
  27.         int n = this.numerator * other.denominator;
  28.         int d = this.denominator * other.numerator;
  29.         Fraction fr = new Fraction(n, d);
  30.         fr.reduce();
  31.         return fr;
  32.     }
  33.  
  34.     public Fraction sum(Fraction other) {
  35.         int n = this.numerator * other.denominator + this.denominator * other.numerator;
  36.         int d = this.denominator * other.denominator;
  37.         Fraction fr = new Fraction(n, d);
  38.         fr.reduce();
  39.         return fr;
  40.     }
  41.  
  42.     public Fraction subtract(Fraction other) {
  43.         int n = this.numerator * other.denominator - this.denominator * other.numerator;
  44.         int d = this.denominator * other.denominator;
  45.         Fraction fr = new Fraction(n, d);
  46.         fr.reduce();
  47.         return fr;
  48.     }
  49.  
  50.     public void reduce() {
  51.         int nod = gcd(this.denominator, this.numerator);
  52.         this.numerator /= nod;
  53.         this.denominator /= nod;
  54.     }
  55.  
  56.     private int gcd(int a, int b) {
  57.         if (b == 0) {
  58.             return a;
  59.         } else {
  60.             return gcd(b, a % b);
  61.         }
  62.     }
  63.  
  64. }
Add Comment
Please, Sign In to add comment