P4450 双亲数

题目:

题目链接:

题解:
莫比乌斯反演

即求 ∑ i = 1 n ∑ j = 1 m [ g c d ( i , j ) = k ] \sum_{i=1}^{n} \sum_{j=1}^{m} {[gcd(i,j)=k]} ∑i=1n​∑j=1m​[gcd(i,j)=k]

∑ i = 1 n ∑ j = 1 m [ g c d ( i , j ) = k ] \sum_{i=1}^{n} \sum_{j=1}^{m} {[gcd(i,j)=k]} ∑i=1n​∑j=1m​[gcd(i,j)=k]

= ∑ i = 1 [ n / k ] ∑ j = 1 [ m / k ] [ g c d ( i , j ) = 1 ] \sum_{i=1}^{[n/k]} \sum_{j=1}^{[m/k]} {[gcd(i,j)=1]} ∑i=1[n/k]​∑j=1[m/k]​[gcd(i,j)=1]

= ∑ i = 1 [ n / k ] ∑ j = 1 [ m / k ] ∑ d ∣ g c d ( i , j ) μ ( d ) \sum_{i=1}^{[n/k]} \sum_{j=1}^{[m/k]} \sum_{d|gcd(i,j)}{\mu(d)} ∑i=1[n/k]​∑j=1[m/k]​∑d∣gcd(i,j)​μ(d)

= ∑ d = 1 n μ ( d ) ∗ [ n k ∗ d ] ∗ [ m k ∗ d ] \sum_{d=1}^{n}{\mu(d)*[\frac {n} {k*d}]*[\frac {m} {k*d}]} ∑d=1n​μ(d)∗[k∗dn​]∗[k∗dm​]

推导完成

#include <bits/stdc++.h>
using namespace std;
const int N=1e6+10;
int mu[N],st[N],pri[N],con,sum[N];
void getmus()
{
    mu[1]=1;
    for(int i=2;i<=N;i++)
    {
        if(!st[i])
        {
            pri[++con]=i;
            mu[i]=-1;
        }
        for(int j=1;i*pri[j]<=N;j++)
        {
            int t=i*pri[j];
            st[t]=1;
            if(i%pri[j]==0)
            {
                break;
            }
            mu[t]=-mu[i];
        }
    }
    for(int i=1;i<=N;i++) sum[i]=sum[i-1]+mu[i];
}
long long f(int n,int m,int k)
{
    n/=k,m/=k;
    int x=min(n,m);
    long long ans=0;
    for(int i=1,j=1;i<=x;i=j+1)
    {
        j = min(x,min(n/(n/i),m/(m/i)));
        ans += (sum[j] - sum[i-1]) *(long long)(n/i) * (m/i);
    }
    return ans;
}
int main()
{
    getmus();
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    {
        int a,b,k;
        cin>>a>>b>>k;
        long long ans=f(a,b,k);
        cout<<ans<<endl;
    }
    return 0;
}
上一篇:【Codeforces Round #725 (Div. 3)】Codeforces-1538


下一篇:Luogu1829 JZPTAB