1852. Ordered Fractions
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.
输入
One line with a single integer N.
输出
One fraction per line, sorted in order of magnitude.
样例
input
5
output
0/1
1/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1
题目大意:
对分子,分母小于或等于N的分数集合进行排序,值相同的分数不计入最后的序列。
题目解析:
利用一个结构体存储分数的分子、分母,用二重循环读入各分数,最大公约数大于1的不保存。排序时可以将两分数通分,便于比较大小。
具体代码:
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int a;//分子
int b;//分母
}arr[100010];
bool cmp(node x,node y){
return x.a*y.b<y.a*x.b;
}
int measure(int x, int y)
{
int z = y;
while(x%y!=0)
{
z = x%y;
x = y;
y = z;
}
return z;
}
int main() {
freopen("data.in","r",stdin);
int n,k=0;
cin>>n;
cout<<"0/1"<<endl;
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(measure(i,j)<=1){
arr[k].a=i;
arr[k].b=j;
k++;
}
}
}
sort(arr,arr+k,cmp);
for(int i=0;i<k;i++)
cout<<arr[i].a<<"/"<<arr[i].b<<endl;
cout<<"1/1"<<endl;
return 0;
}