Luogu

BZOJ

分析

为了方便,设素数集为 $\mathrm{P}$ 。

$$ \begin{aligned} &\sum_{i=1}^n\sum_{j=1}^m[\gcd(i,j)\in{\rm P}]\\ =&\sum_{d=1}^n[d\in{\rm P}]\sum_{i=1}^{n/d}\sum_{j=1}^{m/d}[\gcd(i,j)=1]\\ =&\sum_{d=1}^n[d\in{\rm P}]\sum_{i=1}^{n/d}\mu(i)\Big\lfloor\frac{n}{id}\Big\rfloor\Big\lfloor\frac{m}{id}\Big\rfloor \end{aligned} $$

枚举 $d\in{\rm P}$ ,然后数论分块计算后面的东西即可。

代码

//It is made by M_sea
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#define re register
using namespace std;

inline int read() {
    int X=0,w=1; char c=getchar();
    while (c<'0'||c>'9') { if (c=='-') w=-1; c=getchar(); }
    while (c>='0'&&c<='9') X=X*10+c-'0',c=getchar();
    return X*w;
}

const int MAXN=1e7;
typedef long long LL;

int p[MAXN+10],v[MAXN+10],cnt=0;
int mu[MAXN+10];
inline void init() {
    v[1]=mu[1]=1;
    for (re int i=2;i<=MAXN;++i) {
        if (!v[i]) p[++cnt]=i,mu[i]=-1;
        for (re int j=1;j<=cnt&&i*p[j]<=MAXN;++j) {
            v[i*p[j]]=1;
            if (i%p[j]) mu[i*p[j]]=-mu[i];
            else break;
        }
    }
    for (re int i=1;i<=MAXN;++i) mu[i]+=mu[i-1];
}

inline LL calc(int n) {
    LL ans=0;
    for (re int l=1,r;l<=n;l=r+1) {
        r=n/(n/l);
        ans+=1ll*(mu[r]-mu[l-1])*(n/l)*(n/l);
    }
    return ans;
}

int main() {
    init();
    int n=read(); LL ans=0;
    for (re int i=1;p[i]<=n;++i) ans+=calc(n/p[i]);
    printf("%lld\n",ans);
    return 0;
}
最后修改:2019 年 09 月 24 日 08 : 17 PM