P2568 GCD

骑猪看日落 2021-12-10 02:53 274阅读 0赞

传送门

设 $f[x]=\sum_i^N\sum_j^N[gcd(i,j)==x]$

那么答案就是 $Ans=\sum_{prime}f(prime)$

显然 $f$ 可以反演,设 $F[x]=\sum_i^N\sum_j^N[x|gcd(i,j)]$

那么 $F[x]=\sum_{x|d}f[d]$,并且容易得到 $F[x]=\left \lfloor \frac{N}{x} \right \rfloor \left \lfloor \frac{N}{x} \right \rfloor$

直接反演得到 $f[x]=\sum_{x|d}\mu(d/x)F[d]=\sum_{x|d}\mu(d/x)\left \lfloor \frac{N}{x} \right \rfloor \left \lfloor \frac{N}{x} \right \rfloor$

枚举 $x$ 的倍数 $k$,得到 $f[x]=\sum_k\mu(k)\left \lfloor \frac{N}{kx} \right \rfloor \left \lfloor \frac{N}{kx} \right \rfloor$

因为 $\left \lfloor \frac{N}{kx} \right \rfloor=\left \lfloor \frac{\left \lfloor \frac{N}{x} \right \rfloor}{k} \right \rfloor$

所以 $f[x]==\sum_k\mu(k)\left \lfloor \frac{\left \lfloor \frac{N}{x} \right \rfloor}{k} \right \rfloor\left \lfloor \frac{\left \lfloor \frac{N}{x} \right \rfloor}{k} \right \rfloor$

可以数论分块,然后枚举质数 $p$ 并把所有的 $f[p]$ 加起来就是答案了

质数约有 $sqrt(n)$ 个,单次求 $f$ 复杂度 $sqrt(n)$,总复杂度 $O(n)$

  1. #include<iostream>
  2. #include<cstdio>
  3. #include<algorithm>
  4. #include<cmath>
  5. #include<cstring>
  6. using namespace std;
  7. typedef long long ll;
  8. inline int read()
  9. {
  10. int x=0,f=1; char ch=getchar();
  11. while(ch<'0'||ch>'9') { if(ch=='-') f=-1; ch=getchar(); }
  12. while(ch>='0'&&ch<='9') { x=(x<<1)+(x<<3)+(ch^48); ch=getchar(); }
  13. return x*f;
  14. }
  15. const int N=2e7+7;
  16. int n,pri[N],mu[N],tot;
  17. bool not_pri[N];
  18. ll ans;
  19. void pre()
  20. {
  21. mu[1]=1;
  22. for(int i=2;i<=n;i++)
  23. {
  24. if(!not_pri[i]) pri[++tot]=i,mu[i]=-1;
  25. for(int j=1;j<=tot;j++)
  26. {
  27. ll g=1ll*i*pri[j]; if(g>n) break;
  28. not_pri[g]=1; if(!(i%pri[j])) break;
  29. mu[g]=-mu[i];
  30. }
  31. }
  32. for(int i=2;i<=n;i++) mu[i]+=mu[i-1];
  33. }
  34. int main()
  35. {
  36. n=read(); pre();
  37. for(int i=1;i<=tot;i++)
  38. {
  39. int p=pri[i],m=n/p;
  40. for(int l=1,r;l<=m;l=r+1)
  41. {
  42. r=m/(m/l);
  43. ans+=1ll*(mu[r]-mu[l-1])*(m/l)*(m/l);
  44. }
  45. }
  46. printf("%lld\n",ans);
  47. return 0;
  48. }

转载于:https://www.cnblogs.com/LLTYYC/p/11136444.html

发表评论

表情:
评论列表 (有 0 条评论,274人围观)

还没有评论,来说两句吧...

相关阅读

    相关 GCD

    [GCD][] 什么是GCD 全称是Grand Central Dispatch。GCD 所有的API都在libdispatch.dylib动态库里面Xcode自动

    相关 洛谷P2257 YY的GCD

    莫比乌斯反演 还是把gcd换成莫比乌斯函数,在最外层枚举素数p,对于每个素数p,gcd莫比乌斯反演 include <bits/stdc++.h> de