This repository has been archived by the owner on Oct 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRational.java
64 lines (47 loc) · 1.76 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
import java.lang.*;
import java.math.*;
public class Rational {
private int numerator;
private int denominator;
public Rational(int n, int d) {
if(d > 0 && n >= 0) {
this.numerator = n;
this.denominator = d;
}
else
System.out.println("The denominator must be above 0 and the denominator cannot be negative");
}
public Rational add(Rational r2) {
Rational r = new Rational((this.numerator * r2.denominator) + (r2.numerator * this.denominator), (this.denominator * r2.denominator));
return r;
}
public Rational subtract(Rational r2) {
Rational r = new Rational((this.numerator * r2.denominator) - (r2.numerator * this.denominator), (this.denominator * r2.denominator));
return r;
}
public Rational multiply(Rational r2) {
Rational r = new Rational(this.numerator * r2.numerator, this.denominator * r2.denominator);
return r;
}
public Rational divide(Rational r2) {
Rational r = new Rational(this.numerator * r2.denominator, this.denominator * r2.numerator);
return r;
}
public Rational simplify() {
BigInteger bn = new BigInteger(String.valueOf(this.numerator));
BigInteger bd = new BigInteger(String.valueOf(this.denominator));
BigInteger gcd = bn.gcd(bd);
int gcdInt = gcd.intValue();
Rational r;
if(gcdInt > 0) {
r = new Rational(this.numerator/gcdInt, this.denominator/gcdInt);
}
else
r = new Rational(this.numerator, this.denominator);
return r;
}
public String printRational() {
String r = (Integer.toString(this.numerator) + "/" + Integer.toString(this.denominator));
return r;
}
}