-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFraction.java
143 lines (139 loc) · 2.63 KB
/
Fraction.java
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package jl223vy_assign3;
public class Fraction {
private int n;
private int d;
public Fraction(){
n=0;
d=0;
}
public Fraction(int newN, int newD){
if(newD==0){
System.out.println("error! The denominator cannot be 0.");
//or
//throw new IllegalStateException("error! The denominator cannot be 0.");
}
else{
setND(newN,newD);
rightMinusPosition();
mostSimplifiedForm();
}
}
private void setND(int newN, int newD){
n=newN;
d=newD;
}
private void rightMinusPosition(){
if(!isNegative()){
n=Math.abs(n);
d=Math.abs(d);
}
else{
n=-(Math.abs(n));
d=Math.abs(d);
}
}
private void mostSimplifiedForm(){
int gCD=getGreatestCommonDivisor(n,d);
n=n/gCD;
d=d/gCD;
}
private int getGreatestCommonDivisor(int a, int b){
a=Math.abs(a);
b=Math.abs(b);
if(a<b){
int t=a;
a=b;
b=t;
}
int r;
while(a%b!=0){
r=a%b;
a=b;
b=r;
}
return b;
}
public int getNumerator(){ return n; }
public int getDenominator(){ return d; }
public boolean isNegative(){
if(n>0 && d>0 || n<0 && d<0)
return false;
else
return true;
}
private Fraction reductionOfFraction(int n, int d){
int gCD=getGreatestCommonDivisor(n,d);
n=n/gCD;
d=d/gCD;
return new Fraction(n,d);
}
public Fraction add(Fraction fOA){
int nOA,dOA;
Fraction tempF;
if(fOA.d==d){
nOA=fOA.n+n;
dOA=d;
}
else{
int lCM=d*fOA.d/getGreatestCommonDivisor(d,fOA.d); //lowest common multiple
nOA=n*(lCM/d)+fOA.n*(lCM/fOA.d);
dOA=lCM;
}
if(nOA==0)
tempF=new Fraction();
else{
tempF=reductionOfFraction(nOA,dOA);
}
return tempF;
}
public Fraction subtract(Fraction fOS){
int nOS,dOS;
Fraction tempF;
if(fOS.d==d){
nOS=fOS.n-n;
dOS=d;
}
else{
int lCM=d*fOS.d/getGreatestCommonDivisor(d,fOS.d);
nOS=n*(lCM/d)-fOS.n*(lCM/fOS.d);
dOS=lCM;
}
if(nOS==0)
tempF=new Fraction();
else{
tempF=reductionOfFraction(nOS,dOS);
}
return tempF;
}
public Fraction multiply(Fraction fOM){
int nOM,dOM;
Fraction tempF;
nOM=n*fOM.n;
dOM=d*fOM.d;
if(nOM==0)
tempF=new Fraction();
else{
tempF=reductionOfFraction(nOM,dOM);
}
return tempF;
}
public Fraction divide(Fraction fOD){
Fraction tempF;
if(d==0 || fOD.d==0){
throw new IllegalStateException("error! The denominator cannot be 0.");
}
else{
int nOD,dOD;
nOD=n*fOD.d;
dOD=d*fOD.n;
tempF=reductionOfFraction(nOD,dOD);
}
return tempF;
}
public boolean isEqualTo(Fraction fOE){
return n==fOE.n && d==fOE.d;
}
public String toString(){
return n + "/" + d;
}
}