[51nod1237] 最大公约数之和 V3(杜教筛)

题面

传送门

题解

我好像做过这题……

\[\begin{align} ans &=\sum_{i=1}^n\sum_{j=1}^n\gcd(i,j)\\ &=\sum_{d=1}^nd\sum_{i=1}^{\left\lfloor{n\over d}\right\rfloor}\sum_{j=1}^{\left\lfloor{n\over d}\right\rfloor}[\gcd(i,j)=1]\\ &=\sum_{d=1}^nd\left(\varphi({\left\lfloor{n\over d}\right\rfloor})*2-1\right)\\ \end{align} \]

最后一步就是根据欧拉函数的定义推的

然后杜教筛+整除分块就行了

//minamoto
#include<bits/stdc++.h>
#define R register
#define ll long long
#define IT map<ll,int>::iterator
#define fp(i,a,b) for(R int i=a,I=b+1;i<I;++i)
#define fd(i,a,b) for(R int i=a,I=b-1;i>I;--i)
#define go(u) for(int i=head[u],v=e[i].v;i;i=e[i].nx,v=e[i].v)
using namespace std;
const int N=6e6+5,P=1e9+7,inv2=500000004;
inline int add(R int x,R int y){return x+y>=P?x+y-P:x+y;}
inline int dec(R int x,R int y){return x-y<0?x-y+P:x-y;}
inline int mul(R int x,R int y){return 1ll*x*y-1ll*x*y/P*P;}
inline int calc(R int x){return (1ll*x*(x+1)>>1)%P;}
bitset<N>vis;int p[N],phi[N],m,sqr,res;ll n;map<ll,int>mp;IT it;
void init(int n){
	phi[1]=1;
	fp(i,2,n){
		if(!vis[i])p[++m]=i,phi[i]=i-1;
		for(R int j=1;j<=m&&1ll*i*p[j]<=n;++j){
			vis[i*p[j]]=1;
			if(i%p[j]==0){phi[i*p[j]]=phi[i]*p[j];break;}
			phi[i*p[j]]=phi[i]*(p[j]-1);
		}
	}
	fp(i,2,n)phi[i]=add(phi[i],phi[i-1]);
}
int Phi(ll n){
	if(n<=sqr)return phi[n];
	it=mp.find(n);
	if(it!=mp.end())return it->second;
	int res=calc(n%P);
	for(R ll i=2,j;i<=n;i=j+1)
		j=n/(n/i),res=dec(res,mul((j-i+1)%P,Phi(n/i)));
	return mp[n]=res;
}
int main(){
//	freopen("testdata.in","r",stdin);
	scanf("%lld",&n),init(sqr=N-5);
	for(R ll i=1,j;i<=n;i=j+1)
		j=n/(n/i),res=add(res,mul(dec(calc(j%P),calc((i-1)%P)),(Phi(n/i)<<1)-1));
	printf("%d\n",res);
	return 0;
}
posted @ 2019-02-25 22:16  bztMinamoto  阅读(200)  评论(0编辑  收藏  举报
Live2D