-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rational.java
66 lines (65 loc) · 1.17 KB
/
Rational.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
class Rational{
int num,den;
public void set(int a,int b){
if(b==0)
b=1;
if(b<0)
{
b=-b;
a=-a;
}
int h=gcd(a,b);
num=a/h;
den=b/h;
}
public int gcd(int c,int d){
int min,g=1;
if(c>d)
min=d;
else
min=c;
for(int i=2;i<=min;i++)
if(c%i==0 && d%i==0)
g=i;
return g;
}
public Rational add(Rational a){
Rational r=new Rational();
r.den=den*a.den;
r.num=num*a.den + a.num*den;
int i=gcd(r.num,r.den);
r.num=r.num/i;
r.den=r.den/i;
return r;
}
public Rational less(Rational a){
Rational r=new Rational();
r.den=den*a.den;
r.num=num*a.den - a.num*den;
int i=gcd(r.num,r.den);
r.num=r.num/i;
r.den=r.den/i;
return r;
}
public Rational mul(Rational a){
Rational r=new Rational();
r.den=den*a.den;
r.num=num*a.num;
int i=gcd(r.num,r.den);
r.num=r.num/i;
r.den=r.den/i;
return r;
}
public Rational divide(Rational a){
Rational r=new Rational();
r.den=den*a.num;
r.num=num*a.den;
int i=gcd(r.num,r.den);
r.num=r.num/i;
r.den=r.den/i;
return r;
}
public void show(){
System.out.println("The rational no is"+num+"/"+den);
}
}