Skip to content

Instantly share code, notes, and snippets.

@MasterAlish
Created February 13, 2017 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MasterAlish/880ab508a01c23e665f15a0a35397997 to your computer and use it in GitHub Desktop.
Save MasterAlish/880ab508a01c23e665f15a0a35397997 to your computer and use it in GitHub Desktop.
Fractions in single file
public class Fraction { //Дробь
public int denominator; //Знаменатель
public int numerator; //Числитель
public Fraction(int numerator, int denominator) {
this.denominator = denominator;
this.numerator = numerator;
}
public String toString() {
return numerator + "/" + denominator;
}
public Fraction add(Fraction other) {
Fraction result = new Fraction(1, 1);
if (this.denominator == other.denominator) { //если знаменатели одинаковые
result.denominator = this.denominator;
result.numerator = this.numerator + other.numerator;
} else {
int nok = nok(this.denominator, other.denominator);
result.denominator = nok;
result.numerator = this.numerator * (nok / this.denominator) + other.numerator * (nok / other.denominator);
}
return result;
}
public Fraction multiply(Fraction other) {
Fraction result = new Fraction(1, 1);
result.denominator = this.denominator * other.denominator;
result.numerator = this.numerator * other.numerator;
return result;
}
private int nod(int a, int b) { // Наибольший общий делитель
return b == 0 ? a : nod(b, a % b);
}
private int nok(int a, int b) { // Наименьшее общее кратное
return a / nod(a, b) * b;
}
}
public class FractionTest {
public static void main(String[] args) {
Fraction frac1 = new Fraction(3, 4);
Fraction frac2 = new Fraction(1, 5);
Fraction sum = frac1.add(frac2);
System.out.println(frac1 + " + " + frac2 +" = " + sum);
Fraction mult = frac1.multiply(frac2);
System.out.println(frac1 + " * " + frac2 +" = " + mult);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment