forked from Kotlin-Polytech/FromKotlinToJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRational.java
More file actions
86 lines (69 loc) · 2.21 KB
/
Copy pathRational.java
File metadata and controls
86 lines (69 loc) · 2.21 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
package part1;
import static java.lang.Math.abs;
@SuppressWarnings("WeakerAccess")
public final class Rational {
private final int numerator;
private final int denominator;
static private int gcd(int a, int b) {
if (a == b || b == 0) return a;
else if (a == 0) return b;
else if (a > b) return gcd(a % b, b);
else return gcd(a, b % a);
}
public Rational(int numerator, int denominator) {
if (denominator == 0) throw new ArithmeticException("Denominator cannot be zero");
int gcd = gcd(abs(numerator), abs(denominator));
if (denominator < 0) gcd = -gcd;
this.numerator = numerator / gcd;
this.denominator = denominator / gcd;
}
public int getNumerator() {
return numerator;
}
public int getDenominator() {
return denominator;
}
public Rational plus(Rational other) {
return new Rational(
numerator * other.denominator + denominator * other.numerator,
denominator * other.denominator
);
}
public Rational unaryMinus() {
return new Rational(-numerator, denominator);
}
public Rational minus(Rational other) {
return plus(other.unaryMinus());
}
public Rational times(Rational other) {
return new Rational(numerator * other.numerator, denominator * other.denominator);
}
public Rational div(Rational other) {
return new Rational(numerator * other.denominator, denominator * other.numerator);
}
public int toInt() {
return numerator / denominator;
}
public double toDouble() {
return ((double) numerator ) / denominator;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj instanceof Rational) {
Rational other = (Rational) obj;
return numerator == other.numerator && denominator == other.denominator;
}
return false;
}
@Override
public int hashCode() {
int result = numerator;
result = 31 * result + denominator;
return result;
}
@Override
public String toString() {
return "" + numerator + "/" + denominator;
}
}