線性篩求歐拉函數


蒟蒻要開始打數論模板了。

歐拉函數:小於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];
}

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM