Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 7341 Accepted: 2745
Description
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.
Input
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.
Output
For each test case, you should output one line, which contains N(n) ---- the number of terms in the Farey sequence Fn.
Sample Input
2
3
4
5
0
Sample Output
1
3
5
9
Source
POJ Contest,Author:Mathematica@ZSU
解题思路:
仔细观察题目给的信息便可以发现下面的几组数据之间有联系:
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}
F3的分数的个数为F2的个数加上小于3的与3互质的数的个数,F4的分数的个数为F3的个数加上小于4的与4互质的数……依次类推,便可以得到Fn=Fn-1+k(与n互质的数的个数),于是问题就变为解决小于n的与n互质的数的个数,注意:这里所讲的互质的数的个数已经包括1。
但是,对于n=10^6这样的数据,一个个判断是不是素数显然是不合理的,所以就得找到一种合理的方法,解决这个问题,而后,我发现只要一个数 k 是素数那么与它互质的数(包括1)的个数便是k-1,但是当这个数是合数时上述的规律就不适用,可是,一个合数总能用一连串的素数以相乘的形式表示即n=prime[0]*prime[1]*prime[2]*……prime[k] (这里的prime[0]-prime[k]的数字可以相等)。于是,问题就转换成了研究若干个素数相乘的数的与其互质且小于它本身的数的个数。
为了解决这个问题,可以列举一些数字来说明,看下面的一组数据:
当 prime = 5 m=6 (m>=prime) (prime为素数,m为任意的小于1000000的数)
n=prime*m;
1 5 7 11 13 17 19 23 25 29
n= 6 12 18 24 30
显然5和25不能算作与30互质的数所以应该筛选出来,但是总的数字的个数是有规律的即
w=prime*phi[m] ----phi[m]为小于m的与m互质的数的个数包括1。继续研究下去多找几组数据我们还会发现当m%prime==0时,w= prime*phi[m] 否则 w= (prime-1)*phi[m];于是就得到了下面的代码:
code:
#include <stdio.h>
#define len 1000005
#define le 100000
int phi[len],prime[le];
bool unprime[len];
long long sum[len];
void oular(){
int i,j,k;
for(i=2,k=0;i<len;i++){
if(!unprime[i]){
prime[k++]=i;
phi[i]=i-1;
}
for(j=0;j<k&&prime[j]*i<len;j++){
unprime[prime[j]*i]=true;
if(i%prime[j])
phi[prime[j]*i]=phi[i]*(prime[j]-1);
else{
phi[prime[j]*i]=phi[i]*prime[j];
break;
}
}
}
}
int main(void){
int i,n;
oular();
for(i=1;i<len;i++)
sum[i]=sum[i-1]+phi[i];
while(scanf("%d",&n)==1&&n)
printf("%lld/n",sum[n]);
return 0;
}