欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

BZOJ4804: 欧拉心算(莫比乌斯反演 线性筛)

程序员文章站 2022-06-03 08:31:30
题意 求$$\sum_1^n \sum_1^n \phi(gcd(i, j))$$ $T \leqslant 5000, N \leqslant 10^7$ Sol 延用BZOJ4407的做法 化到最后可以得到 $$\sum_{T = 1}^n \frac{n}{T} \frac{n}{T} \su ......

题意

求$$\sum_1^n \sum_1^n \phi(gcd(i, j))$$

$T \leqslant 5000, N \leqslant 10^7$


Sol

延用BZOJ4407的做法

化到最后可以得到

$$\sum_{T = 1}^n \frac{n}{T} \frac{n}{T} \sum_{d \mid T}^n \phi(d) \mu(\frac{T}{d})$$

后面的那个是积性函数,直接筛出来

注意这个函数比较特殊,筛的时候需要分几种情况讨论

1. $H(p) = p - 2$

2. $H(p^2) = p^2 - 2p + 1$

3. $H(p^{k + 1}) = H(p^k) * p$

// luogu-judger-enable-o2
#include<cstdio>
#include<algorithm>
#define LL long long 
using namespace std;
const int MAXN = 1e7 + 10, mod = 1e9 + 7;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int prime[MAXN], vis[MAXN], tot;
LL H[MAXN], low[MAXN];
void GetH(int N) {
    H[1] = vis[1] = 1;
    for(int i = 2; i <= N; i++) {
        if(!vis[i]) prime[++tot] = i, H[i] = i - 2, low[i] = i;
        for(int j = 1; j <= tot && i * prime[j] <= N; j++) {
            vis[i * prime[j]] = 1;
            if(!(i % prime[j])) {
                low[i * prime[j]] = low[i] * prime[j];
                if(low[i] == i) {
                    if(low[i] == prime[j]) H[i * prime[j]] = (H[i] * prime[j] + 1);
                    else H[i * prime[j]] = H[i] * prime[j];
                } 
                else H[i * prime[j]] = H[i / low[i]] * H[low[i] * prime[j]];
                break;
            }
            H[i * prime[j]] = H[i] * H[prime[j]];
            low[i * prime[j]] = prime[j];
        }
    }
    for(int i = 2; i <= N; i++) 
        H[i] = H[i - 1] + H[i];
}
int main() {
    GetH(1e7 + 5);
    int T = read();
    while(T--) {
        int N = read(), last;
        LL ans = 0;
        for(int i = 1; i <= N; i = last + 1) {
            last = N / (N / i);
            ans = ans + 1ll * (N / i) * (N / i) * (H[last] - H[i - 1]);
        } 
        printf("%lld\n", ans);
    }
    return 0;
}
/*
3
7001
123000
10000000
*/