1. 程式人生 > >#莫比烏斯反演,整除分塊#洛谷 3455 ZAP-Queries

#莫比烏斯反演,整除分塊#洛谷 3455 ZAP-Queries

題目

給定n,mn,m,求1xn1\leq x\leq n,1ym1\leq y\leq m滿足gcd(x,y)=dgcd(x,y)=d(x,y)(x,y)個數

分析

f(d)=i=1nj=1m[gcd(i,j)=d]f(d)=\sum_{i=1}^{n}\sum_{j=1}^{m}[gcd(i,j)=d] F(d)=ndmdF(d)=\lfloor\frac{n}{d}\rfloor\lfloor\frac{m}{d}\rfloor

dm 根據莫比烏斯反演 =dnμ(nd)F(nd)答案=\sum_{d|n}\mu (\frac{n}{d})F(\frac{n}{d}) 然後列舉nd\frac{n}{d}可以發現可以用整除分塊解決,then

程式碼

    #include <cstdio>
    #include <vector>
    #define rr register
    #define N 50001
    using namespace std;
    int sum[N],v[N],mobius[N];
    inline
int in(){ rr int ans=0; rr char c=getchar(); while (c<48||c>57) c=getchar(); while (c>47&&c<58) ans=(ans<<3)+(ans<<1)+c-48,c=getchar(); return ans; } void print(int ans){ if (ans>9) print(ans/10); putchar(ans%10+48); } void
prepare(int n){ mobius[1]=1; vector<int>prime; for (rr int i=2;i<=n;++i){ if (!v[i]) v[i]=i,mobius[i]=-1,prime.push_back(i); for (rr int j=0;j<prime.size();++j){ if (prime[j]>v[i]||prime[j]>n/i) break; v[i*prime[j]]=prime[j]; if (i%prime[j]==0) break; mobius[i*prime[j]]=-mobius[i]; } } for (rr int i=1;i<=n;i++) sum[i]=sum[i-1]+mobius[i];//線性篩求莫比烏斯字首和 } int main(){ rr int t=in(); prepare(N-1); while (t--){ rr int n=in(),m=in(),d=in(); if (n>m) n^=m,m^=n,n^=m; rr long long ans=0; for (rr int l=1,r;l<=n;l=r+1){//整除分塊 r=min(n/(n/l),m/(m/l)); ans+=(n/l/d)*(m/l/d)*(sum[r]-sum[l-1]);//計算答案字首和 } print(ans); putchar(10); } return 0; }