-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRational.cpp
78 lines (62 loc) · 2.49 KB
/
Rational.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "Rational.h"
unsigned GCD_Impl(unsigned a, unsigned b)noexcept
{
return b == 0 ? a : GCD_Impl(b, a % b);
}
unsigned GCD(signed a, signed b)
{
a = a >= 0 ? a : -a;
b = b >= 0 ? b : -b;
if (a == b)return a;
return GCD_Impl(a, b);
}
rational::rational(int numerator, int denominator)
:numerator(numerator), denominator(denominator) {};
void rational::add(const rational& other)
{
numerator = numerator * other.denominator +
other.numerator * denominator;
denominator *= other.denominator;
int factor = GCD(numerator, denominator);
numerator /= factor;
denominator /= factor;
}
void rational::mul(const rational& other)
{
int factor = GCD(
numerator *= other.numerator,
denominator *= other.denominator);
numerator /= factor;
denominator /= factor;
}
void rational::div(const rational& other)
{
mul(rational(other.denominator, other.numerator));
}
void rational::sub(const rational& other) { add(-other); }
bool rational::check_equal(const rational& other)const
{
return numerator == other.numerator &&
denominator == other.denominator ?
true : false;
}
bool rational::check_greater(const rational& other)const
{
return other.denominator * numerator > other.numerator * denominator;
}
rational& rational::operator+=(const rational& other) { add(other); return *this; }
rational& rational::operator-=(const rational& other) { sub(other); return *this; }
rational& rational::operator*=(const rational& other) { mul(other); return *this; }
rational& rational::operator/=(const rational& other) { div(other); return *this; }
rational rational::operator-()const { return rational(-numerator, denominator); }
rational rational::operator+()const { return *this; }
rational operator+(rational dst, rational const& src) { dst.add(src); return dst; }
rational operator-(rational dst, rational const& src) { dst.sub(src); return dst; }
rational operator*(rational dst, rational const& src) { dst.mul(src); return dst; }
rational operator/(rational dst, rational const& src) { dst.div(src); return dst; }
bool operator==(const rational& lhs, const rational& rhs) { return lhs.check_equal(rhs); }
bool operator>(const rational& lhs, const rational& rhs) { return lhs.check_greater(rhs); }
bool operator<(const rational& lhs, const rational& rhs) { return rhs > lhs; }
bool operator!=(const rational& lhs, const rational& rhs) { return !(lhs == rhs); }
bool operator<=(const rational& lhs, const rational& rhs) { return !(lhs > rhs); }
bool operator>=(const rational& lhs, const rational& rhs) { return !(rhs > lhs); }