Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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