线性筛-三合一,强大O(n)
校内CJOJ2395by Jesse Liu
筛法三合一 Euler、Möbius、Prime函数
基于数论的积性函数
gcd(a,b)=1 则 ƒ(ab)=ƒ(a)ƒ(b)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <algorithm> 2 #include <iostream> 3 #include <cstring> 4 #include <cstdlib> 5 #include <cstdio> 6 #include <vector> 7 #include <cmath> 8 #include <queue> 9 #include <map> 10 #include <set> 11 using namespace std; 12 #define file(x) freopen(x".in","r",stdin),freopen(x".out","w",stdout) 13 inline void read(int &ans){ 14 ans=0;char x=getchar();int f=0; 15 while(x<'0'||x>'9'){if(x=='-')f=1;x=getchar();} 16 while(x>='0'&&x<='9')ans=ans*10+x-'0',x=getchar(); 17 if(f)ans=-ans; 18 } 19 20 const int maxn=(int)1e7+10; 21 int phi[maxn],mu[maxn],p[maxn],flag[maxn],cnt; 22 void sieve(int n){ 23 mu[1]=phi[1]=1; 24 for(int i=2;i<=n;i++){ 25 if(!flag[i])p[++cnt]=i,mu[i]=-1,phi[i]=i-1; 26 for(int j=1;j<=cnt && i*p[j]<=n;j++){ 27 flag[i*p[j]]=1; 28 if(i%p[j]==0){mu[i*p[j]]=0,phi[i*p[j]]=phi[i]*p[j];break;} 29 mu[i*p[j]]=-mu[i],phi[i*p[j]]=phi[i]*(p[j]-1); 30 } 31 } 32 } 33 34 int main(){ 35 sieve((int)1e7); 36 int T,op,n; 37 for(read(T);T--;){ 38 read(op),read(n); 39 printf("%d\n",op==1?p[n]:op==2?mu[n]:phi[n]); 40 } 41 return 0; 42 }
进一步学习的建议,Jesse Liu
~~Jason_liu O(∩_∩)O