Skip to content

Commit 96bf9cb

Browse files
committed
add c++ fraction class
1 parent e2ef617 commit 96bf9cb

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

cpp/numbertheory/frac.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#include <bits/stdc++.h>
2+
#include "frac.h"
3+
4+
using namespace std;
5+
using fracll = frac<long long>;
6+
7+
// usage example
8+
int main() {
9+
fracll x{1, 2};
10+
fracll y{2, 3};
11+
x -= y;
12+
x = x.abs();
13+
cout << x.a << "/" << x.b << endl;
14+
}

cpp/numbertheory/frac.h

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

0 commit comments

Comments
 (0)