Luogu

BZOJ

分析

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

线性筛 $\mu$ 的前缀和,然后数论分块计算即可。

代码

// ===================================
//   author: M_sea
//   website: http://m-sea-blog.com/
// ===================================
#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 N=50000+10;

int p[N],v[N],mu[N],cnt=0;

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

inline int calc(int n,int m) {
    if (n>m) swap(n,m);
    int ans=0;
    for (re int l=1,r;l<=n;l=r+1) {
        r=min(n/(n/l),m/(m/l));
        ans+=(mu[r]-mu[l-1])*(n/l)*(m/l);
    }
    return ans;
}

int main() { sieve(50000);
    int T=read();
    while (T--) {
        int n=read(),m=read(),d=read();
        printf("%d\n",calc(n/d,m/d));
    }
    return 0;
}
最后修改:2019 年 10 月 24 日 08 : 16 AM