[BZOJ2818]Gcd(数论)

题目描述

传送门

题解

i=1nj=1nd=1prime[0][gcd(i,j)=prime[d]]
=i=1nj=1nd=1prime[0][gcd(iprime[d],jprime[d])=1]
=d=1prime[0]i=1nprime[d]j=1nprime[d][gcd(i,j)=1]
=d=1prime[0]i=1nprime[d]j=1nprime[d]t|gcd(i,j)μ(t)
=d=1prime[0]i=1nprime[d]j=1nprime[d]t=1n[t|i][t|j]μ(t)
=d=1prime[0]t=1ni=1nprime[d][t|i]j=1nprime[d][t|j]μ(t)
=d=1prime[0]t=1nnprime[d]tnprime[d]tμ(t)
枚举质数是必须要枚举的,后面的那一坨根n分块,预处理mu的前缀和。

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define LL long long

const int max_n=1e7+5;

LL n;
LL ans;
LL p[max_n],prime[max_n],mu[max_n];

inline void get_mu(int n){
    mu[1]=1;
    for (int i=2;i<=n;++i){
        if (!p[i]){
            prime[++prime[0]]=i;
            mu[i]=-1;
        }
        for (int j=1;j<=prime[0]&&i*prime[j]<=n;++j){
            p[i*prime[j]]=1;
            if (i%prime[j]==0){
                mu[i*prime[j]]=0;
                break;
            }
            else mu[i*prime[j]]=-mu[i];
        }
        mu[i]+=mu[i-1];
    }
}

int main(){
    scanf("%lld",&n);
    get_mu(n);
    LL j;
    for (LL d=1;d<=prime[0]&&prime[d]<=n;++d){
        LL N=(LL)n/prime[d];
        for (LL i=1;i<=N;i=j+1){
            j=min(N,N/(N/i));
            ans+=(N/i)*(N/i)*(mu[j]-mu[i-1]);
        }
    }
    printf("%lld\n",ans);
}

你可能感兴趣的:(数论,bzoj)