Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Fraction {
- private int num;
- private int den;
- public int getNum() {
- return this.num;
- }
- public void setNum(int num) {
- this.num = num;
- }
- public int getDen() {
- return this.den;
- }
- public void setDen(int den) {
- if (den != 0){
- this.den = den;
- } else {
- this.den = -1;
- System.out.println("Error!!!");
- }
- }
- public Fraction(int num, int den) {
- this.setNum(num);
- this.setDen(den);
- }
- @Override
- public String toString() {
- return this.getNum() + "/" + this.getDen();
- }
- public Fraction mult(Fraction other) {
- int numr = this.getNum() * other.getNum();
- int denr = this.getDen() * other.getDen();
- Fraction res = new Fraction(numr, denr);
- return res;
- }
- public Fraction divide(Fraction other) {
- int numr = this.getNum() * other.getDen();
- int denr = this.getDen() * other.getNum();
- Fraction res = new Fraction(numr, denr);
- return res;
- }
- public Fraction add(Fraction other) {
- int numr = this.getNum() * other.getDen() + other.getNum()*this.getDen();
- int denr = this.getDen() * other.getDen();
- Fraction res = new Fraction(numr, denr);
- return res;
- }
- public Fraction subtract(Fraction other) {
- int numr = this.getNum() * other.getDen() - other.getNum()*this.getNum();
- int denr = this.getDen() * other.getDen();
- Fraction res = new Fraction(numr, denr);
- return res;
- }
- private int gcdByEuclidsAlgorithm(int n1, int n2) {
- if (n2 == 0) {
- return n1;
- }
- return gcdByEuclidsAlgorithm(n2, n1 % n2);
- }
- public void reduce() {
- int d = gcdByEuclidsAlgorithm(this.num, this.den);
- this.num /= d;
- this.den /= d;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement