-
Notifications
You must be signed in to change notification settings - Fork 117
/
Fraction class
82 lines (65 loc) · 1.61 KB
/
Fraction class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package classes_and_objects;
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
if (denominator == 0) {
// TODO error out
}
this.denominator = denominator;
simplify();
}
public int getDenominator() {
return denominator;
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int n) {
this.numerator = n;
simplify();
}
public void setDenominator(int d) {
if (d == 0){
// TODO error out
return;
}
this.denominator = d;
this.simplify();
}
public void print() {
if (denominator == 1) {
System.out.println(numerator);
} else {
System.out.println(numerator + "/" + denominator);
}
}
private void simplify() {
int gcd = 1;
int smaller = Math.min(numerator, denominator);
for (int i = 2; i <= smaller; i++) {
if (numerator % i == 0 && denominator % i == 0) {
gcd = i;
}
}
numerator = numerator/gcd;
denominator = denominator/gcd;
}
public static Fraction add(Fraction f1, Fraction f2) {
int newNum = f1.numerator * f2.denominator + f2.numerator * f1.denominator;
int newDen = f1.denominator * f2.denominator;
Fraction f = new Fraction(newNum, newDen);
return f;
}
public void add(Fraction f2) {
this.numerator = this.numerator * f2.denominator + this.denominator*f2.numerator;
this.denominator = this.denominator * f2.denominator;
simplify();
}
public void multiply(Fraction f2) {
this.numerator = this.numerator * f2.numerator;
this.denominator = this.denominator * f2.denominator;
simplify();
}
}