USCAO Ordered Fractions

来源:互联网 发布:力控组态软件 编辑:程序博客网 时间:2024/04/29 05:14
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.

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/11/51/41/32/51/23/52/33/44/51/1
输出
分母不超过n的
从小到大分数大小的排序
按照分母从1到n
分子从0到分母来录入不同数值的分数(虽然也可以写成1到分母-1,这不重要)
首先分母和分子必须互质,如果有大于1的公因数,那么拥有同样数值的分数则已经在之前的循环被录入
gcd算法使用了辗转相除法
然后把这些分数按小到大sort一次
输出结果
代码如下
/*ID: huangha15LANG: CTASK: frac1*/#include <stdio.h>#include <stdlib.h>struct node{double up;double down;}fraction[30000];int n,cur;int gcd(int a,int b){    if(a==0&&b==1)        return 1;    int c;    c = a%b;    while (c!=0)    {        a=b;        b=c;        c = a%b;    }    return b;}int cmp(const void *a,const void *b){    const struct node *x, *y;    x=a;    y =b;    if(x->up/x->down >y->up/y->down)        return 1;    else        return -1;}int main(){    FILE *fin = fopen("frac1.in","r");    FILE *fout = fopen("frac1.out","w");    double i,j;    fscanf(fin,"%d",&n);    for(i=1;i<=n;i++)    {        for(j=0;j<=i;j++)        {           if(gcd(j,i)==1)           {            fraction[cur].up = j;            fraction[cur].down = i;            cur ++;           }        }    }    qsort(fraction,cur,sizeof(fraction[0]),cmp);    int k;    for(k=0;k<cur;k++)    {        fprintf(fout,"%.0lf%c%.0lf\n",fraction[k].up,'/',fraction[k].down);    }    exit(0);}

0 0
原创粉丝点击