DESCRIPTION
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.
OUTPUT FORMAT
One fraction per line, sorted in order of magnitude.
题意
给定n,求分母不大于n的所有真分数,从小到大输出
题解
双重枚举分子分母,同时算出分数值,排序去重然后输出,注意分子分母化简
代码
/*
ID:wjp13241
PROG:frac1
LANG:C++
*/
#include <stdio.h>
#include <algorithm>
using namespace std;
struct frac
{
int x,y;
double v;
};
frac f[13001];
bool cmp(frac x,frac y)
{
return x.v<y.v;
}
int gcd(int x,int y)
{
return !y?x:gcd(y,x%y);
}
int main()
{
freopen("frac1.in","r",stdin);
freopen("frac1.out","w",stdout);
int n,count=0;
scanf("%d",&n);
for (int i=1;i<=n;i++)
for (int j=0;j<=i;j++)
{
int tmp=gcd(i,j);
f[++count]=(frac){i/tmp,j/tmp,(double)(j)/(double)(i)};
}
sort(f+1,f+count+1,cmp);
int i=0;
while (++i<=count)
{
while(f[i].v==f[i+1].v&&i<count)
i++;
printf("%d/%d\n",f[i].y,f[i].x);
}
fclose(stdin);
fclose(stdout);
return 0;
}