2018徐州网络赛 D-Easy Math(反演 杜教筛)
#include<bits/stdc++.h> #define me(a,x) memset(a,x,sizeof(a)) #define sc scanf #define itn int #define IN freopen("in.txt","r",stdin); #define OUT freopen("out.txt","w",stdout); #define STR clock_t startTime = clock(); #define END clock_t endTime = clock();cout << double(endTime - startTime) / CLOCKS_PER_SEC *1000<< "ms" << endl; using namespace std; const int N=1e7+5; const long long mod=1e9+7; const long long mod2=998244353; const int oo=0x7fffffff; const int sup=0x80000000; typedef long long ll; typedef unsigned long long ull; template <typename it>void db(it *begin,it *end){while(begin!=end)cout<<(*begin++)<<" ";puts("");} template <typename it> string to_str(it n){string s="";while(n)s+=n%10+'0',n/=10;reverse(s.begin(),s.end());return s;} template <typename it>int o(it a){cout<<a<<endl;return 0;} inline ll mul_64(ll x,ll y,ll c){return (x*y-(ll)((long double)x/c*y)*c+c)%c;} ll ksm(ll a,ll b,ll c){ll ans=1;for(;b;b>>=1,a=a*a%c)if(b&1)ans=ans*a%c;return ans;} void exgcd(ll a,ll b,ll &x,ll &y){if(!b)x=1,y=0;else exgcd(b,a%b,y,x),y-=(a/b)*x;} int prime[N],tot=0; bool vis[N]={0}; short int mu[N]; int f[N]; void pre(){ mu[1]=1;f[1]=1; for(int i=2;i<N;i++){ if(!vis[i])prime[++tot]=i,mu[i]=-1; for(int j=1;j<N&&i*prime[j]<N;j++){ vis[i*prime[j]]=1; if(i%prime[j]==0){ mu[i*prime[j]]=0; break; }else mu[i*prime[j]]=-mu[i]; } f[i]=f[i-1]+mu[i]; } } int get_mu(ll n){ if(n==1)return 1; int cnt=0; for(int i=1;i<=tot&&1LL*prime[i]*prime[i]<=n;i++){ if(n%prime[i]==0){ n/=prime[i]; if(n%prime[i]==0)return 0; cnt++; } } if(n>1)cnt++; return cnt%2==1?-1:1; } map<ll,ll>p; map<ll,bool>q; ll cal(ll n){ if(n<N)return f[n]; if(q[n])return p[n]; ll ans=1; for(ll d=2,last;d<=n;d=last+1){ last=n/(n/d); ans-=1LL*(last-d+1)*cal(n/d); } q[n]=true; return p[n]=ans; } map<ll,short int>MU; ll F(int m,ll n){ if(m==0)return 0; if(n==1)return cal(m); ll ans=0; for(ll d=1;d*d<=n;d++){ if(n%d==0){ ans+=1LL*MU[d]*F(m/d,d); if(d!=n/d)ans+=1LL*MU[n/d]*F(m/(n/d),n/d); } } return ans*MU[n]; } int main(){ pre(); int m;ll n; sc("%d%lld",&m,&n); for(int i=1;1LL*i*i<=n;i++){ if(n%i==0){ MU[i]=mu[i]; if(n/i<N)MU[n/i]=mu[n/i]; else MU[n/i]=get_mu(n/i); } } if(MU[n]==0)return o(0); printf("%lld\n",F(m,n)); }