some programs!
This commit is contained in:
1 parent
5d30e847c1
commit
ed054247d5
32 files changed
+1882
-149
No files matched your search
@@ -0,0 +1,76 @@
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
long long gcd(long long x, long long y) {
|
||||
if (x < y) swap(x, y);
|
||||
if (x % y == 0) { return y; }
|
||||
return gcd(y, x % y);
|
||||
}
|
||||
|
||||
class Fraction {
|
||||
public:
|
||||
long long numerator = 0, denominator = 1;
|
||||
|
||||
void simplify() {
|
||||
if (numerator == 0) { denominator = 1; }
|
||||
long long g = gcd(numerator, denominator);
|
||||
numerator /= g, denominator /= g;
|
||||
}
|
||||
|
||||
Fraction operator+(const Fraction& other) const {
|
||||
Fraction result{
|
||||
numerator * other.denominator + denominator * other.numerator,
|
||||
denominator * other.denominator
|
||||
};
|
||||
result.simplify();
|
||||
return result;
|
||||
}
|
||||
|
||||
Fraction operator+=(const Fraction& other) {
|
||||
return *this = *this + other;
|
||||
}
|
||||
|
||||
Fraction() = default;
|
||||
Fraction(const long long n, const long long d) : numerator(n), denominator(d) { simplify(); }
|
||||
|
||||
Fraction(const string& s) {
|
||||
stringstream ss(s);
|
||||
long long n, d;
|
||||
char slash;
|
||||
if (ss >> n >> slash >> d && slash == '/') {
|
||||
numerator = n, denominator = d;
|
||||
simplify();
|
||||
} else {
|
||||
throw invalid_argument("String is not a fraction");
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] string to_string() const {
|
||||
if (denominator == 1) {
|
||||
return std::to_string(numerator);
|
||||
}
|
||||
return std::to_string(numerator) + '/' + std::to_string(denominator);
|
||||
}
|
||||
};
|
||||
|
||||
int n;
|
||||
string s;
|
||||
Fraction ans;
|
||||
|
||||
int main() {
|
||||
ios::sync_with_stdio(false);
|
||||
cin.tie(nullptr);
|
||||
|
||||
cin >> n;
|
||||
for (int _ = 0; _ < n; _++) {
|
||||
// clog << ans.numerator << '/' << ans.denominator << endl;
|
||||
cin >> s;
|
||||
ans += Fraction(s);
|
||||
}
|
||||
|
||||
cout << ans.to_string() << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user