您的位置:首页 > 产品设计 > UI/UE

POJ 2478 Farey Sequence

2014-01-21 21:10 453 查看
[align=left]Problem Description[/align]
The Farey Sequence Fn for any integer n with n >= 2 is the set of irreducible rational numbers a/b with 0 < a < b <= n and gcd(a,b) = 1 arranged in increasing order. The first few are
F2 = {1/2}
F3 = {1/3, 1/2, 2/3}
F4 = {1/4, 1/3, 1/2, 2/3, 3/4}
F5 = {1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5}

You task is to calculate the number of terms in the Farey sequence Fn.

[align=left]Input[/align]
There are several test cases. Each test case has only one line, which contains a positive integer n (2 <= n <= 106). There are no blank lines between cases. A line with a single 0 terminates the input.

[align=left]Output[/align]
For each test case, you should output one line, which contains N(n) ---- the number of terms in the Farey sequence Fn.

[align=left]Sample Input[/align]

2

3

4

5

0

[align=left]Sample Output[/align]

1

3

5

9
Fi中含分母i的项数为fi。由于每项的分子与分母互质,因此与i互质的整数的个数即为fi。显然,fi等于欧拉函数f(i)的值。
代码如下:

#include<stdio.h>
#include<math.h>
#include<string.h>
int s[32767],num=1;
bool u[32767];
void preper()
{
int i,j;
memset(u,true,sizeof(u));
for(i=2;i<=32767;i++)
{
if(u[i]) s[num++]=i;
for(j=1;j<num;j++)
{
if(i*s[j]>32767) break;
u[i*s[j]]=false;
if(i%s[j]==0) break;
}
}
}
int main()
{
int i,a,b,sum=1,count=0;
char c;
preper();
while(1)
{
scanf("%d",&a);
if(a==0) break;
scanf("%d",&b);
sum*=floor(pow(a,b)+0.5);
c=getchar();
if(c=='\n')
{
sum-=1;
for(i=num-1;i>=1;i--)
{
if(sum%s[i]==0)
{
count=0;
while(sum%s[i]==0)
{
count++;
sum/=s[i];
}
if(sum!=1)    printf("%d %d ",s[i],count);
else {printf("%d %d\n",s[i],count); break;}
}
}
sum=1;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: