Consider the set of all reduced fractions between 0 and 1 inclusive with denominators less than or equal to N.
Here is the set when N = 5:
0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1
Write a program that, given an integer N between 1 and 160 inclusive, prints the fractions in order of increasing magnitude.
PROGRAM NAME: frac1
INPUT FORMAT
One line with a single integer N.
SAMPLE INPUT (file frac1.in)
5
OUTPUT FORMAT
One fraction per line, sorted in order of magnitude.
SAMPLE OUTPUT (file frac1.out)
0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1
Compiling...
Compile: OK
Executing...
Test 1: TEST OK [0.004 secs limit:1s, 1740 KB]
Test 2: TEST OK [0.007 secs limit:1s, 1704 KB]
Test 3: TEST OK [0.007 secs limit:1s, 1724 KB]
Test 4: TEST OK [0.007 secs limit:1s, 1688 KB]
Test 5: TEST OK [0.007 secs limit:1s, 1676 KB]
Test 6: TEST OK [0.011 secs limit:1s, 1716 KB]
Test 7: TEST OK [0.011 secs limit:1s, 1744 KB]
Test 8: TEST OK [0.028 secs limit:1s, 1780 KB]
Test 9: TEST OK [0.074 secs limit:1s, 1736 KB]
Test 10: TEST OK [0.119 secs limit:1s, 1716 KB]
Test 11: TEST OK [0.308 secs limit:1s, 1684 KB]
All tests OK.
YOUR PROGRAM ('frac1') WORKED FIRST TIME! That's fantastic
-- and a rare thing. Please accept these special automated
congratulations.
那么接下来看代码
/*
ID: choiyin1
TASK:frac1
LANG:C++
*/
#include <bits/stdc++.h>
using namespace std;
int n, bt;
struct PII
{
int f, s;
}b[7810];
inline bool operator < (PII A, PII B)
{
return ((double)A.f/(double)A.s) < ((double)B.f/(double)B.s);
}
inline int gcd(int x, int y)
{
int tmp;
do{
tmp = x % y;
x = y;
y = tmp;
}while(tmp);
return x;
}
int main(){
freopen("frac1.in", "r", stdin);
freopen("frac1.out", "w", stdout);
cin >> n;
for (int i = 2; i <= n; ++ i)
for (int j = 1; j < i; ++ j)
if (gcd(i, j) == 1)
{
++ bt;
b[bt].f = j;
b[bt].s = i;
}
sort(b + 1, b + 1 + bt);
cout<<"0/1"<<endl;
for (int i = 1; i <= bt; ++ i) cout<<b[i].f<<"/"<<b[i].s<<endl;
cout<<"1/1"<<endl;
}