P2568 GCD

纯粹的發表於2024-07-11

原題連結

題解

\(g=gcd(i,j)\)\(i=t_1g,j=t_2g\)
所以原題等價於求 \(\sum_{i\in prime} \sum gcd(x,y)==1,x\in[1,n/i],y\in[1,n/i]\)

也就是對於每個素數 \(i\),求 \([1,n/i]\) 內有幾對數互質,我們可以求尤拉函式字首和得出

code

#include<bits/stdc++.h>
#define ll long long
using namespace std;

vector<ll> prime;
bool mark[10000005]={0};
ll phi[10000005]={0};
ll sumgcd1[10000005]={0};

void solve()
{
    ll n;
    cin>>n;
    ll ans=0;
    for(auto it:prime)
    {
        if(it>n) break;
        ans+=sumgcd1[n/it];
    }
    cout<<ans<<'\n';

}
int main()
{

    sumgcd1[1]=1;
    for(ll i=2;i<=1e7;i++)
    {
        if(!mark[i])
        {
            prime.push_back(i);
            phi[i]=i-1;
        }

        for(auto it:prime)
        {
            if(it*i>1e7) break;
            mark[it*i]=1;

            if(i%it==0)
            {
                phi[it*i]=it*phi[i];
                break;
            }
            else
            {
                phi[it*i]=phi[it]*phi[i];
            }
        }

        sumgcd1[i]=sumgcd1[i-1]+2LL*phi[i];
    }

    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t=1;
    //cin>>t;
    while(t--) solve();
    return 0;
}