【题目地址】
题意简述
求当 n = 1 0 11 n=10^{11} n=1011时的如下式子在 m o d 998244353 {\rm mod}\ 998244353 mod 998244353后的值。
∑ i = 1 n ∑ j = 1 i g c d ( i , j ) \sum_{i=1}^n\sum_{j=1}^igcd(i,j) i=1∑nj=1∑igcd(i,j)
我们可以枚举 g c d gcd gcd,将式子转化为:
∑ d = 1 n d ∑ i = 1 n ∑ j = 1 i [ g c d ( i , j ) = d ] ∑ d = 1 n d ∑ i = 1 ⌊ n d ⌋ ∑ j = 1 i [ g c d ( i , j ) = 1 ] \sum_{d=1}^nd\sum_{i=1}^n\sum_{j=1}^i[gcd(i,j)=d] \\ \sum_{d=1}^nd\sum_{i=1}^{\lfloor\frac{n}{d}\rfloor}\sum_{j=1}^{i}[gcd(i,j)=1] d=1∑ndi=1∑nj=1∑i[gcd(i,j)=d]d=1∑ndi=1∑⌊dn⌋j=1∑i[gcd(i,j)=1]
根据定义可知,后面的 ∑ j = 1 i [ g c d ( i , j ) = 1 ] = φ ( i ) \sum_{j=1}^i[gcd(i,j)=1]=\varphi(i) ∑j=1i[gcd(i,j)=1]=φ(i)
所以原式可以继续化简为:
∑ d = 1 n d ∑ i = 1 ⌊ n d ⌋ φ ( i ) \sum_{d=1}^nd\sum_{i=1}^{\lfloor\frac{n}{d}\rfloor}\varphi(i) d=1∑ndi=1∑⌊dn⌋φ(i)
然后我们对于后面的 φ \varphi φ的前缀和用杜教筛,前面分块就可以在 O ( n 2 3 ) O(n^{\frac{2}{3}}) O(n32)时间内解决,大概 n = 1 0 11 n=10^{11} n=1011的时候大约5s左右可以跑出来。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#define ll long long
using namespace std;
const ll M=3e7+10;
const ll Mod=998244353ll;
ll phi[M],prime[M],cnt,inv_2;
bool vis[M];
map<ll,ll> mp;
ll fpow(ll a,ll b){
ll ans=1ll;
for(;b;b>>=1ll,a=(a*a)%Mod){
if(b&1ll)ans=(a*ans)%Mod;
}
return ans;
}
void init(){
phi[1ll]=1ll;
inv_2=fpow(2ll,Mod-2ll);
for(ll i=2ll;i<M;i++){
if(!vis[i]){prime[++cnt]=i;phi[i]=i-1ll;}
for(ll j=1,v;j<=cnt&&i*prime[j]<M;j++){
v=i*prime[j];
vis[v]=1;
if(!(i%prime[j])){
phi[v]=phi[i]*prime[j];
break;
}
phi[v]=phi[i]*phi[prime[j]];
}
}
for(ll i=2ll;i<M;i++)(phi[i]+=phi[i-1ll])%=Mod;
}
#include<cmath>
ll S(ll a){if(a>=Mod)a%=Mod;return ((a*(a+1))%Mod)*inv_2%Mod;}
ll calc(ll x){
if(x<M) return phi[x];
if(mp.count(x)) return mp[x];
ll ans=S(x);
for(ll i=2ll,j;i<=x;i=j+1ll){
j=x/(x/i);
ans=((ans-((j-i+1)%Mod*calc(x/i)%Mod))%Mod+Mod)%Mod;
}
return mp[x]=ans;
}
ll solve(ll x){
ll ans=0,ls;
for(ll i=1,j;i<=x;i=j+1ll){
j=(x/(x/i));
ls=(S(j)-S(i-1ll))%Mod;
if(ls<0)ls+=Mod;
ans=(ans+ls*(calc(x/i))%Mod)%Mod;
}
return (ans)%Mod;
}
int main(){
init();
ll x=1e11;
printf("%lld\n",solve(x));
return 0;
}