Skip to content

Commit c15b453

Browse files
committed
USTC-ACM-Prob1014
/** * Solve it using the standard equation, that a smaller difference should be reached * each time. * Be careful about the output format and extreme cases. * Either one is zero, second is the factor of the first one, equal. * Take of the case of ceil and floor function when the argument is integer * itself. */
1 parent b00f5df commit c15b453

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

USTC-ACM-Prob1014.cpp

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
2+
/**
3+
* Solve it using the standard equation, that a smaller difference should be reached
4+
* each time.
5+
* Be careful about the output format and extreme cases.
6+
* Either one is zero, second is the factor of the first one, equal.
7+
* Take of the case of ceil and floor function when the argument is integer
8+
* itself.
9+
*/
10+
11+
#include <iostream>
12+
#include <cmath>
13+
14+
using namespace std;
15+
16+
int gcd(int lhs, int rhs)
17+
{
18+
if (lhs == rhs)
19+
return lhs;
20+
while(rhs)
21+
{
22+
lhs ^= rhs;
23+
rhs ^= lhs; /* rhs = lhs */
24+
lhs ^= rhs; /* lhs = rhs */
25+
rhs %= lhs;
26+
}
27+
return lhs;
28+
}
29+
30+
int main()
31+
{
32+
int a,b; /* input two numbers */
33+
int divisor;
34+
int nom, den;
35+
36+
int nom_next, den_next; //
37+
38+
int nom_1, nom_2;
39+
40+
double prev;
41+
double next;
42+
43+
// int up_limit;
44+
// int down_limit;
45+
bool is_last = false;
46+
47+
while (cin>>a>>b)
48+
{
49+
if (is_last)
50+
cout<<endl;
51+
is_last = true;
52+
53+
if (a== 0 || b == 0)
54+
{
55+
cout<<a<<"/"<<b<<endl;
56+
continue;
57+
}
58+
else if (a == b)
59+
{
60+
cout<<1<<"/"<<1<<endl;
61+
continue;
62+
}
63+
64+
divisor = gcd(a,b);
65+
a /= divisor;
66+
b /= divisor;
67+
68+
if (b == 1)
69+
{
70+
cout<<a<<"/"<<b<<endl;
71+
continue;
72+
}
73+
74+
den = 1;
75+
if( (a%b) > (b>>1) )
76+
{
77+
nom = a/b + 1;
78+
}
79+
else
80+
nom = a/b == 0?1:a/b;
81+
cout<<nom<<"/"<<den<<endl;
82+
for (den_next = 2; den_next < b; ++den_next)
83+
{
84+
prev = double(nom) /den;
85+
next = double(a)/b;
86+
prev = abs(next - prev);
87+
88+
nom_1 = (int)ceil(den_next * (next - prev)+0.00001);
89+
nom_2 = (int)floor(den_next * (next + prev)-0.00001);
90+
91+
// nom_next = nom > den? den:nom;
92+
nom_1 = nom_1 < 1?1:nom_1;
93+
if (nom_2 < nom_1) continue;
94+
// nom = nom_next;
95+
den = den_next;
96+
nom = nom_1;
97+
cout<<nom<<"/"<<den<<endl;
98+
99+
}
100+
cout<<a<<"/"<<b<<endl;
101+
102+
}
103+
return 0;
104+
}

0 commit comments

Comments
 (0)