-
Notifications
You must be signed in to change notification settings - Fork 0
/
Recurring_Fractions.cpp
92 lines (87 loc) · 2.27 KB
/
Recurring_Fractions.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int a, b, num1, num2;
char ch = '+';
cin >> a >> b;
// checking whether the final answer will be -ve or +ve
if (a * b < 0)
ch = '-';
a = abs(a);
b = abs(b);
if (a % b == 0) // Case 1 : When the numerator is completely divisible by
// denominator
{
if (ch == '-')
cout << ch << a / b << endl;
else
cout << a / b << endl;
}
else
{
// Case 2 and 3 , Terminating and recurring
// Using a map to store the repetition of remainders and their positions
map<int, int> m1;
int i = 0, pos;
string s = "";
bool flag = true;
num1 = a / b;
a = a % b;
m1.insert({a, i});
a = a * 10;
++i;
while (1)
{
int x, rem;
x = a / b;
rem = a % b;
if (rem == 0) // If rem is 0 that means terminating decimal
{
s += char(x + 48);
break;
}
else if (m1.count(rem)) // Checking if the rem has occured previously
{
s += char(x + 48);
pos = m1[rem]; // position for opening parenthesis
flag = false;
break;
}
// When rem is neither zero or not repeated just insert rem in map
else
{
m1.insert({rem, i});
++i;
s += char(x + 48);
a = rem * 10;
}
}
if (flag == false)
{
if (ch == '-')
cout << ch << num1 << '.' << s.substr(0, pos) << '('
<< s.substr(pos, s.length() - pos) << ')' << endl;
else
cout << num1 << '.' << s.substr(0, pos) << '('
<< s.substr(pos, s.length() - pos) << ')' << endl;
}
else
{
if (ch == '-')
cout << ch << num1 << '.' << s << endl;
else
cout << num1 << '.' << s << endl;
}
}
}
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int _t;
cin >> _t;
while (_t--)
solve();
}