Problem Description
Farey序列是一个这样的序列:其第一级序列定义为(0/1,1/1),这一序列扩展到第二级形成序列(0/1,1/2,1/1),扩展到第三极形成序列(0/1,1/3,1/2,2/3,1/1),扩展到第四级则形成序列(0/1,1/4,1/3,1/2,2/3,3/4,1/1)。以后在每一级n,如果上一级的任何两个相邻分数a/c与b/d满足(c+d)<=n,就将一个新的分数(a+b)/(c+d)插入在两个分数之间。对于给定的n值,依次输出其第n级序列所包含的每一个分数。
Input
输入一个整数n(0<n<=100)
Output
依次输出第n级序列所包含的每一个分数,每行输出10个分数,同一行的两个相邻分数间隔一个制表符的距离。
Example Input
6
Example Output
0/1 1/6 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 5/6 1/1
Hint
#include<stdio.h>
#include<stdlib.h>
struct hh
{
int a;
int b;
struct hh *next;
};
int main()
{
int n,k;
struct hh *head,*p,*t,*p1,*p2;
scanf("%d",&n);
head=(struct hh *)malloc(sizeof(struct hh));
head->next=NULL;
t=head;
p=(struct hh *)malloc(sizeof(struct hh));
p->a=0;
p->b=1;
p->next=t->next;
t->next=p;
t=p;
p=(struct hh *)malloc(sizeof(struct hh));
p->a=1;
p->b=1;
p->next=t->next;
t->next=p;
t=p;
k=1;
while(k==1)
{
p1=head->next;
p2=p1->next;
p=NULL;
while(p2!=NULL)
{
if((p1->b+p2->b)<=n)
{
p=(struct hh *)malloc(sizeof(struct hh));
p->a=p1->a+p2->a;
p->b=p1->b+p2->b;
p->next=p1->next;
p1->next=p;
}
p1=p2;
p2=p2->next;
}
if(p==NULL)
k=0;
}
k=0;
p=head->next;
while(p!=NULL)
{
k++;
if(k<10)
printf("%d/%d\t",p->a,p->b);
else if(k==10)
{
printf("%d/%d\n",p->a,p->b);
k=0;
}
p=p->next;
}
return 0;
}
本文介绍了一种生成Farey序列的算法实现,并通过C语言代码详细展示了如何递增地构建序列,从初始的(0/1, 1/1)开始,逐步扩展到任意等级n的完整序列。该算法利用链表存储中间结果,便于理解和实现。

被折叠的 条评论
为什么被折叠?



