Farey Sequence
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 <= 10 6). 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
题意:求欧拉函数的前n项和。
题解:打表筛选即可。
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int oula[1000005];
int main()
{
int n;
int i,j;
memset(oula,0,sizeof(oula));
for(i=2;i<=1000000;i++)
{
if(!oula[i])
{
for(j=i;j<=1000000;j+=i)
{
if(!oula[j])
oula[j]=j;
oula[j]=oula[j]/i*(i-1);
}
}
}
while(cin>>n,n)
{
long long ans=0;
for(i=2;i<=n;i++)
ans+=oula[i];
cout<<ans<<endl;
}
return 0;
}
编程实现:
利用欧拉函数和它本身不同质因数的关系,用筛法计算出某个范围内所有数的欧拉函数值。
欧拉函数和它本身不同质因数的关系:
欧拉函数ψ(N)=N{∏p|N}(1-1/p)
亦即:
(P是数N的质因数)
如:
ψ(10)=10 ×(1-1/2)×(1-1/5)=4;
ψ(30)=30 ×(1-1/2)×(1-1/3)×(1-1/5)=8;
ψ(49)=49 ×(1-1/7)=49 / 7 * (7 - 1)=42。
c++
/*
特性 :
1.若a为质数,phi[a]=a-1;
2.若a为质数,b mod a=0,phi[a*b]=phi[b]*a
3.若a,b互质,phi[a*b]=phi[a]*phi[b](当a为质数时,if b mod a!=0 ,phi[a*b]=phi[a]*phi[b])
*/
int m[n],phi[n],p[n],nump;
//m[i]标记i是否为素数,0为素数,1不为素数;p是存放素数的数组;nump是当前素数个数;phi[i]为欧拉函数
int main()
{
phi[1]=1;
for (int i=2;i<=n;i++)
{
if (!m[i])//i为素数
{
p[++nump]=i;//将i加入素数数组p中
phi[i]=i-1;//因为i是素数,由特性得知
}
for (int j=1;j<=nump&&p[j]*i<=n;j++) //用当前已得到的素数数组p筛,筛去p[j]*i
{
m[p[j]*i]=1;//可以确定i*p[j]不是素数
if (i%p[j]==0) //看p[j]是否是i的约数,因为素数p[j],等于判断i和p[j]是否互质
{
phi[p[j]*i]=phi[i]*p[j]; //特性2
break;
}
else phi[p[j]*i]=phi[i]*(p[j]-1); //互质,特性3其,p[j]-1就是phi[p[j]]
}
}
}
c
#include<stdio.h>
#include<stdlib.h>
int eular(int n)
{
int ret=1,i;
for(i=2;i*i<=n;i++)
{
if(n%i==0)
{
n/=i,ret*=i-1;
while(n%i==0) n/=i,ret*=i;
}
}
if(n>1) ret*=n-1;
return ret;
}
int main ()
{
int n,s;
scanf("%d",&n);
s=eular(n);
printf("%d",s);
return 0;
}