Description
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
Output
Sample Input
2 3 4 5 0
Sample Output
1 3 5 9
題意:給定一個數n,求小於或等於n的數中兩兩互質組成的真分數的個數,其實就是求1到n中所有數的歐拉函數值的和,但是這並不需要每個數依次計算,劉汝佳的算法入門經典上有個類似篩法求素數的方法只有O(nloglogn)的複雜度。
代碼:
#include<stdio.h>
#include<string.h>
int phi[1000005];
__int64 ans[1000005];
int i,j,n;
void phi_table()
{
for(i=2;i<=1000005;i++)
phi[i]=0;
phi[1]=1;
for(i=2;i<=1000005;i++)
if(!phi[i])
for(j=i;j<=1000005;j+=i)
{
if(!phi[j])
phi[j]=j;
phi[j]=phi[j]/i*(i-1);
}
}
int main()
{
phi_table();
ans[1]=0;
for(i=2;i<=1000005;i++)
ans[i]=ans[i-1]+phi[i];
while(scanf("%d",&n),n)
{
printf("%I64d\n",ans[n]);
}
return 0;
}