合法分数的组合

来源:互联网 发布:腾讯云免费域名 编辑:程序博客网 时间:2024/05/01 06:19

输入一个自然数N,我们总可以得到一些满足“1≤b≤N,0≤a/b≤1”条件的最简分数a/b(分子和分母互质的分数),请找出所有满足条件的分数。

比方说,当N=5时,所有解为:

0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1

现在,你需要对于一个给定的自然数N,1≤N≤160,请编程按分数值递增的顺序输出所有解。

注:0和任意自然数的最大公约数就是那个自然数、互质指最大公约数等于1的两个自然数。

输入包括一个给个给定的自然数N

输出为一个列表,每个分数单独占一行,按照实际大小从小到大排列

样例输入

5

样例输出

0/11/51/41/32/51/23/52/33/44/51/1

思路:

枚举分子分子(分子分母的关系要控制好), 在将每组结果保存结构体中,按结果进行排序

代码:

#include<iostream>#include<string.h>#include<algorithm>#include<cstdio>using namespace std;struct node{int aa;int bb;double s;}st[10000];int check(int a,int b){int t,i;if (a==0){if (b!=1)return 0;elsereturn 1;}if (a<=b){t = a;    }    else    {t = b;    }    for (i=2; i<=t; i++)    {if (a%i==0 && b%i==0)return 0;    }    return 1;}bool cmp(const struct node &x,const struct node &y){return x.s<y.s;}int main(){int a,b,n,k=0,i;cin>>n;for (b=1; b<=n; b++){for (a=0; a*1.0/b<=1; a++){if (check(a,b)){st[k].aa=a;st[k].bb=b;st[k].s = a*1.0/b;k++;}}}sort(st,st+k,cmp);for (i=0; i<k; i++){cout<<st[i].aa<<"/"<<st[i].bb<<endl;}return 0;}


0 0