atanasovetr

class Fraction

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