-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFraction.java
More file actions
118 lines (96 loc) · 1.74 KB
/
Copy pathFraction.java
File metadata and controls
118 lines (96 loc) · 1.74 KB
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
import java.lang.Math;
public class Fraction
{
int num;
int denom;
public Fraction(int newNum, int newDenom)
{
num = newNum;
denom = newDenom;
if(denom == 0)
throw new ArithmeticException();
reduce();
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
public void setNum(int n)
{
num = n;
reduce();
}
public void setDenom(int n)
{
denom = n;
if(denom == 0)
throw new ArithmeticException();
reduce();
}
//We sum the fractions a/b and c/d as (a*d+b*c)/b*d then reduce.
public Fraction add(Fraction a)
{
//Fraction newFrac = new Fraction(3, 4);
Fraction added = new Fraction((a.num * denom + a.denom * num),
a.denom * denom);
// int g = gcd(added.num, added.denom);
//
// num /= g;
// denom /= g;
//
// added.num = num;
// added.denom = denom;
//
// if(added.denom == 0)
// throw new ArithmeticException();
return added;
}
/*
*
*/
public void reduce()
{
int n = gcd(num, denom);
num /= n;
denom /= n;
}
public int gcd(int num, int denom)
{
// if(denom == 0)
// {
// return Math.abs(num);
// }
// else
// {
// return reduce(denom, num%denom);
// }
while(denom != 0)
{
int temp = denom;
denom = num % denom;
num = temp;
}
return num;
//
//while(num != denom)
// if(num > denom)
// num = num - denom;
// else
// denom = denom - num;
// return num;
}
public boolean equals(Fraction a)
{
if(num * a.denom == denom * a.num || num == a.num && denom == a.denom)
return true;
return false;
}
public String toString()
{
return num + " / " + denom;
}
}