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
/*
ID: conicoc1
LANG: C
TASK: frac1
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Number
{
int a;
int b;
float c;
};
int comp(const void*a,const void *b)
{
struct Number *p1,*p2;
p1=(struct Number*)a;
p2=(struct Number*)b;
if(p1->c-p2->c>0)
return 1;
else
return 0;
}
int judge(int a,int b) //默认b>=a
{
if(a==0&&b==1)
return 1;
while(b!=0&&a!=0)
{
if(b>a)
b=b%a;
else
a=a%b;
}
if((a==0&&b==1)||(a==1&&b==0))
return 1;
return 0;
}
int main()
{
FILE *fin,*fout;
fin=fopen("frac1.in","r");
fout=fopen("frac1.out","w");
struct Number A[25600];
int N;
fscanf(fin,"%d",&N);
int i,j;
int k=0;
for(i=1;i<=N;i++)
{
for(j=0;j<=i;j++)
{
if(judge(j,i))
{
A[k].a=j;
A[k].b=i;
A[k++].c=(float)j/(float)i;
}
}
}
qsort(A,k,sizeof(struct Number),comp);
for(i=0;i<k;i++)
fprintf(fout,"%d/%d\n",A[i].a,A[i].b);
return 0;
}
关于qsort的comp函数
分析是这样写的:
int fraccompare (struct fraction *p, struct fraction *q) {
return p->numerator * q->denominator - p->denominator *q->numerator;
}
好吧,这道是超级水题吗。。。