Advertisement
vencinachev

Calc

Nov 30th, 2020
650
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1.  
  2. public class Fraction {
  3.     private int num;
  4.     private int den;
  5.    
  6.     public int getNum() {
  7.         return this.num;
  8.     }
  9.     public void setNum(int num) {
  10.         this.num = num;
  11.     }
  12.     public int getDen() {
  13.         return this.den;
  14.     }
  15.     public void setDen(int den) {
  16.         if (den != 0){
  17.             this.den = den;
  18.         } else {
  19.             this.den = -1;
  20.             System.out.println("Error!!!");
  21.         }
  22.     }
  23.    
  24.     public Fraction(int num, int den) {
  25.         this.setNum(num);
  26.         this.setDen(den);
  27.     }
  28.    
  29.     @Override
  30.     public String toString() {
  31.         return this.getNum() + "/" + this.getDen();
  32.     }
  33.    
  34.     public Fraction mult(Fraction other) {
  35.         int numr = this.getNum() * other.getNum();
  36.         int denr = this.getDen() * other.getDen();
  37.         Fraction res = new Fraction(numr, denr);
  38.         return res;
  39.     }
  40.    
  41.     public Fraction divide(Fraction other) {
  42.         int numr = this.getNum() * other.getDen();
  43.         int denr = this.getDen() * other.getNum();
  44.         Fraction res = new Fraction(numr, denr);
  45.         return res;
  46.     }
  47.    
  48.     public Fraction add(Fraction other) {
  49.         int numr = this.getNum() * other.getDen() + other.getNum()*this.getDen();
  50.         int denr = this.getDen() * other.getDen();
  51.         Fraction res = new Fraction(numr, denr);
  52.         return res;
  53.     }
  54.    
  55.     public Fraction subtract(Fraction other) {
  56.         int numr = this.getNum() * other.getDen() - other.getNum()*this.getNum();
  57.         int denr = this.getDen() * other.getDen();
  58.         Fraction res = new Fraction(numr, denr);
  59.         return res;
  60.     }
  61.    
  62.     private int gcdByEuclidsAlgorithm(int n1, int n2) {
  63.         if (n2 == 0) {
  64.             return n1;
  65.         }
  66.         return gcdByEuclidsAlgorithm(n2, n1 % n2);
  67.     }
  68.    
  69.     public void reduce() {
  70.         int d = gcdByEuclidsAlgorithm(this.num, this.den);
  71.         this.num /= d;
  72.         this.den /= d;
  73.     }
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement