Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cassert>
- #include <algorithm>
- #include <ostream>
- template <class T>
- class efrac {
- T num, den;
- static T gcd_internal(T a, T b) {
- return a == 0 ? b : gcd(b - b/a*a, a);
- }
- public:
- efrac (T pnum, T pden) {
- assert(pnum >= 0 and pden >= 0);
- T c = gcd(pnum, pden);
- num = c ? pnum / c : 0;
- den = c ? pden / c : 0;
- }
- T get_num() { return num; }
- T get_den() { return den; }
- static T gcd(T a, T b) {
- assert(a >= 0 and b >= 0);
- return a < b ? gcd_internal(a, b) : gcd_internal(b, a);
- }
- static const efrac<T> null(0, 0);
- static const efrac<T> zero(0, 1);
- static const efrac<T> infty(1, 0);
- bool is_null() const { return num == 0 and den == 0; }
- bool is_zero() const { return num == 0 and den != 0; }
- bool is_infty() const { return num != 0 and den == 0; }
- bool is_regular() const { return num != 0 and den != 0; }
- efrac<T> inv() {
- return efrac<T>(den, num);
- }
- friend efrac<T>
- operator+(const efrac<T>& a, const efrac<T>& b) {
- if (a.is_null() or b.is_null()) return null;
- if (a.is_infty() or b.is_infty()) return infty;
- T c = gcd(a.den, b.den);
- return efrac<T>(a.num*(b.den/c) + b.num*(a.den/c), a.den*(b.den/c));
- }
- friend efrac<T>
- operator*(const efrac<T>& a, const efrac<T>& b) {
- T c = gcd(a.num, b.den);
- T d = gcd(b.num, a.den);
- if (c == 0 or d == 0) return null;
- return efrac<T>((a.num/c)*(b.num/d), (a.den/d)*(b.den/c));
- }
- friend std::ostream&
- operator<<(std::ostream& os, const efrac<T>& a) {
- return os << a.num << "/" << a.den;
- }
- friend bool
- operator==(const efrac<T>& a, const efrac<T>& b) {
- return a.num == b.num and a.den == b.den;
- }
- friend bool
- operator!=(const efrac<T>& a, const efrac<T>& b) {
- return not (a == b);
- }
- friend efrac<T>
- operator/(const efrac<T>& a, const efrac<T>& b) {
- return a*b.inv();
- }
- friend bool
- operator<=(const efrac<T>& a, const efrac<T>& b) {
- efrac c = a/b;
- return c.num <= c.den;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement