线性筛求欧拉函数

蒟蒻要开始打数论模板了。

欧拉函数:小于n且与n互素的数个数,记为φ(n)

 它有这样几个优越的性质:转自https://yq.aliyun.com/articles/15314


1.  phi(p) == p-1 因为素数p除了1以外的因子只有p,所以与 p 互素的个数是 p - 1个

2. phi(p^k) == p^k - p^(k-1) == (p-1) * p^(k-1)

证明:

令n == p^k,小于 n 的正整数共有 p^k-1 个,其中与 p 不互素的个数共 p^(k-1)-1 个,它们是 1*p,2*p,3*p ... (p^(k-1)-1)*p

所以phi(p^k) == (p^k-1) - (p^(k-1)-1) == p^k - p^(k-1) == (p-1) * p^(k-1)。


3. 如果i mod p == 0, 那么 phi(i * p) == p * phi(i) (证明略)

举个例子:

假设 p = 3,i = 6,p * i = 18 = 2 * 3^2;

phi(3 * 6) == 18*(1-1/2)*(1-1/3) = 6

p * phi(i) = 3 * phi(6) = 3 * 6 * (1-1/2) *  (1-1/3) = 6 = phi(i * p) 正确

4. 如果i mod p != 0, 那么 phi(i * p) == phi(i) * (p-1) 

证明:

i mod p 不为0且p为质数, 所以i与p互质, 那么根据积性函数的性质 phi(i * p) == phi(i) * phi(p) 其中phi(p) == p-1

所以 phi(i * p) == phi(i) * (p-1).

再举个例子:

假设i = 4, p = 3, i * p = 3 * 4 = 12

phi(12) = 12 * (1-1/2) * (1-1/3) = 4

phi(i) * (p-1) = phi(4) * (3-1) = 4 * (1-1/2) * 2 = 4 = phi(i * p)正确

那么直接给出实现代码

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<ctime>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<bitset>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
using namespace std;
#define N 100001
typedef long long ll;
char xB[1<<15],*xT=xB,*xS=xB;
//#define getchar() (xS==xT&&(xT=(xS=xB)+fread(xB,1,1<<15,stdin),xS==xT)?0:*xS++)
inline int read()
{
    int f=1,x=0;char ch=getchar();
    while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=getchar();}
    while(ch<='9'&&ch>='0'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
    return f*x;
}
bool nop[N*11];
ll phi[N*11],pri[N];
int size;
void getprime(int lim)
{
    nop[1]=1,phi[1]=0;
    for(int i=2;i<=lim;i++)
    {
        if(!nop[i])pri[++size]=i,phi[i]=i-1;
        for(int j=1;j<=size&&i*pri[j]<=lim;j++)
        {
            nop[i*pri[j]]=1;
            if(i%pri[j]==0)
            {
                phi[i*pri[j]]=phi[i]*pri[j];
                break;
            }
            else phi[i*pri[j]]=phi[i]*(pri[j]-1);
        }
    }
}
int main()
{
    int n=read();
    getprime(n+1);
    cout<<phi[n];
}

 

  

 

posted @ 2017-09-13 19:11  a799091501  阅读(1884)  评论(0编辑  收藏  举报