-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfraction.java
77 lines (74 loc) · 1.29 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
public class fraction
{
private int num,den;
public fraction(int num,int den) throws Exception
{
this.num=num;
if(den==0)
{
Exception e=new Exception("Denominator can't be 0");
throw e;
}
this.den=den;
simplify();
}
public int getDenominator()
{
return den;
}
public int getNumerator()
{
return num;
}
public void setNumerator(int num)
{
this.num=num;
simplify();
}
public void setDenominator(int den) throws Exception
{
if(den==0)
{
Exception e=new Exception("Denominator can't be 0");
throw e;
}
this.den=den;
simplify();
}
public void print()
{
if(den==1)
System.out.println(num);
else
System.out.println(num+"/"+den);
}
private void simplify()
{
int gcd=1;
int smaller=Math.min(num, den);
for(int i=2;i<=smaller;++i)
if(num%i==0 && den%i==0)
gcd=i;
num=num/gcd;
den=den/gcd;
}
public static fraction add(fraction f1, fraction f2) throws Exception
{
int newnum=f1.num*f2.den+f1.den*f2.num;
int newden=f1.den*f2.den;
fraction f4=new fraction(newnum,newden);
return f4;
}
public void add(fraction f2)
{
this.num=this.num*f2.den+this.den*f2.num;
this.den=this.den*f2.den;
simplify();
}
public void multiply(fraction f2)
{
this.num=this.num*f2.num;
this.den=this.den*f2.den;
simplify();
}
}