---
# System prepended metadata

title: fraction
tags: [codebook]

---

---
tags: codebook
---

{%hackmd theme-dark %}

# fraction

```cpp=
#include<iostream>
#include<algorithm>
#include<cmath>
#include<sstream>
using namespace std;
struct fraction {
	int numerator;
	int denominator;
	fraction(int a = 0, int b = 1): numerator(a), denominator(b) {
		auto gcd = __gcd(numerator, denominator);
		numerator /= gcd, denominator /= gcd;
		if ((numerator < 0) ^ (denominator < 0))
			numerator = -abs(numerator), denominator = abs(denominator);
		else
			numerator = abs(numerator), denominator = abs(denominator);
	}
	friend fraction operator+(fraction a, fraction b) {
		auto gcd = __gcd(a.denominator, b.denominator);
		a.numerator *= b.denominator / gcd;
		b.numerator *= a.denominator / gcd;
		return fraction(a.numerator + b.numerator, a.denominator * b.denominator / gcd);
	}
	friend fraction operator-(fraction a, fraction b) {
		auto gcd = __gcd(a.denominator, b.denominator);
		a.numerator *= b.denominator / gcd;
		b.numerator *= a.denominator / gcd;
		return fraction(a.numerator - b.numerator, a.denominator * b.denominator / gcd);
	}
	friend istream& operator>>(istream& is, fraction& f) {
		string str;
		is >> str;
		replace(str.begin(), str.end(), '/', ' ');
		stringstream ss(str);
		int a, b;
		ss >> a >> b;
		f = fraction(a, b);
		return is;
	}
	friend ostream& operator<<(ostream& os, const fraction& f) {
		cout << f.numerator << '/' << f.denominator << endl;
		return os;
	}
};
int main() {
	fraction ans, tmp;
	char op;
	cin >> ans;
	while (cin >> op >> tmp)
		switch (op) {
		case '+':
			ans = ans + tmp;
			break;
		case'-':
			ans = ans - tmp;
			break;
		}
	cout << ans << endl;
	return 0;
}
```