欧拉心算

传送门

解法:

\[\begin{align} \sum_{i=1}^n\sum_{j=1}^n\phi(gcd(i,j))&=\sum_{d=1}\phi(d)\sum_{i=1}^n\sum_{j=1}^n[d==gcd(i,j)]\\ &=\sum_{d=1}^n\phi(d)\sum_{i=1}^{\lfloor\frac{n}{d}\rfloor}\sum_{j=1}^{\lfloor\frac{n}{d}\rfloor}\sum_{k=1}^{\lfloor\frac{n}{d}\rfloor}\mu(k)[k|gcd(i,j)]\\ &=\sum_{T=1}^n\lfloor\frac{n}{T}\rfloor^2\mu*\phi(T)\\ \end{align} \]

下面考虑转化这个式子

\[\sum_{i=1}^nf*g(i)=\sum_{i=1}^nf(i)\sum_{j=1}^{\lfloor\frac{n}{i}\rfloor}g(j)\\ \begin{align} \sum_{i=1}^n\phi(i)\sum_{j=1}^{\lfloor\frac{n}{i}\rfloor}\phi(j)&=\sum_{i=1}^n\mu*\phi(i)\sum_{j=1}^{\lfloor\frac{n}{i}\rfloor}id(j)\\ &=\sum_{i=1}^n\mu*\phi(i)\frac{\lfloor\frac{n}{i}\rfloor(\lfloor\frac{n}{i}\rfloor+1)}{2}\\ &=\frac{\sum_{i=1}^n\lfloor\frac{n}{i}\rfloor^2\mu*\phi(i)+\sum_{i=1}^n\lfloor\frac{n}{i}\rfloor\mu*\phi(i)}{2}\\ &=\frac{\sum_{i=1}^n\lfloor\frac{n}{i}\rfloor^2\mu*\phi(i)+\sum_{i=1}^n\phi(i)}{2}\\ \end{align}\\ \sum_{i=1}^n\lfloor\frac{n}{i}\rfloor^2\mu*\phi(i)=2\times\sum_{i=1}^n\phi(i)\sum_{j=1}^{\lfloor\frac{n}{i}\rfloor}\phi(j)-\sum_{i=1}^n\phi(i) \]

代码:

//https://www.lydsy.com/JudgeOnline/problem.php?id=4804
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<cmath>
#include<map>
#include<queue>
#include<bitset>
#include<set>
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define dwn(i,a,b) for(int i=(a);i>=(b);--i)
using namespace std;
typedef long long ll;
const int N=10000000;
int T,n,cnt,prime[1000010];
bool v[N+10];
ll phi[N+10];
inline void init(int n)
{
    phi[1]=1;
    rep(i,2,n)
    {
        if(!v[i])
        {
            prime[++cnt]=i;
            phi[i]=i-1;
        }
        for(int j=1;j<=cnt&&prime[j]*i<=n;++j)
        {
            v[prime[j]*i]=1;
            if(i%prime[j]==0)
            {
                phi[prime[j]*i]=phi[i]*prime[j];
                break;
            }
            phi[prime[j]*i]=phi[i]*(prime[j]-1);
        }
    }
    rep(i,2,n)
    {
        phi[i]+=phi[i-1];
    }
}
int main()
{
    init(N);
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        ll ans=0;
        for(int l=1,r;l<=n;l=r+1)
        {
            r=n/(n/l);
            ans+=phi[n/l]*(phi[r]-phi[l-1]);
        }
        printf("%lld\n",2*ans-phi[n]);
    }
    return 0;
}
posted @ 2019-08-31 19:34  zmy蒟蒻  阅读(480)  评论(1编辑  收藏  举报