Skip to content

Commit 509ced8

Browse files
committed
rename frac into rational
1 parent 96bf9cb commit 509ced8

File tree

3 files changed

+82
-78
lines changed

3 files changed

+82
-78
lines changed

cpp/numbertheory/frac.h

Lines changed: 0 additions & 74 deletions
This file was deleted.

cpp/numbertheory/frac.cpp renamed to cpp/numbertheory/rational.cpp

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
#include <bits/stdc++.h>
2-
#include "frac.h"
2+
#include "rational.h"
33

44
using namespace std;
5-
using fracll = frac<long long>;
5+
using rt = rational<long long/*__int128*/>;
66

77
// usage example
88
int main() {
9-
fracll x{1, 2};
10-
fracll y{2, 3};
9+
rt x{1, 2};
10+
rt y{2, 3};
11+
if (y > x)
12+
cout << "y > x" << endl;
1113
x -= y;
1214
x = x.abs();
1315
cout << x.a << "/" << x.b << endl;

cpp/numbertheory/rational.h

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
template<class T>
6+
struct rational {
7+
T a, b;
8+
9+
rational(T a, T b = 1) : a{a}, b{b} {
10+
normalize();
11+
}
12+
13+
void normalize() {
14+
if (b < 0) {
15+
a = -a;
16+
b = -b;
17+
}
18+
auto g = gcd(::abs(a), b);
19+
if (g != 0) {
20+
a /= g;
21+
b /= g;
22+
}
23+
}
24+
25+
bool operator==(rational rhs) const { return a == rhs.a && b == rhs.b; }
26+
27+
bool operator!=(rational rhs) const { return !(*this == rhs); }
28+
29+
bool operator<(rational rhs) const { return a * rhs.b < b * rhs.a; }
30+
31+
bool operator<=(rational rhs) const { return !(rhs < *this); }
32+
33+
bool operator>(rational rhs) const { return rhs < *this; }
34+
35+
bool operator>=(rational rhs) const { return !(*this < rhs); }
36+
37+
rational operator-() const { return rational(-a, b); }
38+
39+
rational abs() const { return rational(::abs(a), b); }
40+
41+
rational &operator+=(rational rhs) {
42+
a = a * rhs.b + b * rhs.a;
43+
b *= rhs.b;
44+
normalize();
45+
return *this;
46+
}
47+
48+
rational &operator-=(rational rhs) {
49+
a = a * rhs.b - b * rhs.a;
50+
b *= rhs.b;
51+
normalize();
52+
return *this;
53+
}
54+
55+
rational &operator*=(rational rhs) {
56+
a *= rhs.a;
57+
b *= rhs.b;
58+
normalize();
59+
return *this;
60+
}
61+
62+
rational &operator/=(rational rhs) {
63+
a *= rhs.b;
64+
b *= rhs.a;
65+
normalize();
66+
return *this;
67+
}
68+
69+
friend rational operator+(rational lhs, rational rhs) { return lhs += rhs; }
70+
71+
friend rational operator-(rational lhs, rational rhs) { return lhs -= rhs; }
72+
73+
friend rational operator*(rational lhs, rational rhs) { return lhs *= rhs; }
74+
75+
friend rational operator/(rational lhs, rational rhs) { return lhs /= rhs; }
76+
};

0 commit comments

Comments
 (0)