[RC - 02] GCD(莫比乌斯反演 + 杜教筛) | 错题本

文章目录

题目

[RC - 02] GCD

分析

枚举 p p p ⌊ N j ⌋ \left\lfloor\frac{N}{j}\right\rfloor jN 实际上就是在枚举 j p jp jp,于是原式变成
∑ i = 1 N ∑ j = 1 N ∑ p = 1 N ∑ q = 1 N [ gcd ⁡ ( i , j ) = 1 ] [ gcd ⁡ ( p , q ) = j ] = ∑ i = 1 N ∑ j = 1 N ∑ p = 1 N ∑ q = 1 N [ gcd ⁡ ( i , p , q ) = 1 ] = ∑ d = 1 N ⌊ N d ⌋ 3 μ ( d ) \begin{aligned}&\sum_{i = 1}^N\sum_{j = 1}^N\sum_{p = 1}^{N}\sum_{q = 1}^{N}[\gcd(i, j) = 1][\gcd(p, q) = j] \\= &\sum_{i = 1}^N\sum_{j = 1}^N\sum_{p = 1}^{N}\sum_{q = 1}^{N}[\gcd(i, p, q) = 1] \\=&\sum_{d = 1}^{N}\left\lfloor\frac{N}{d}\right\rfloor^3\mu(d)\end{aligned} ==i=1Nj=1Np=1Nq=1N[gcd(i,j)=1][gcd(p,q)=j]i=1Nj=1Np=1Nq=1N[gcd(i,p,q)=1]d=1NdN3μ(d) 整数分块 + 杜教筛即可。

代码

#include <bits/stdc++.h>

typedef long long LL;

const int MAXN = 1000000;
const int MOD = 998244353;

int Mu[MAXN + 5];
bool Vis[MAXN + 5];
std::vector<int> Primes;
std::unordered_map<int, int> Sum;

void Init(int n) {
    Mu[1] = 1;
    for (int i = 2; i <= n; i++) {
        if (!Vis[i])
            Mu[i] = -1, Primes.push_back(i);
        for (int j = 0; j < (int)Primes.size() && i * Primes[j] <= n; j++) {
            Vis[i * Primes[j]] = true;
            if (i % Primes[j] == 0) {
                Mu[i * Primes[j]] = 0;
                break;
            }
            Mu[i * Primes[j]] = -Mu[i];
        }
        Mu[i] = ((Mu[i - 1] + Mu[i]) % MOD + MOD) % MOD;
    }
}

int GetSum(int n) {
    if (n <= MAXN) return Mu[n];
    if (Sum.count(n)) return Sum[n];
    int res = 1;
    for (int lft = 2, rgt = 1; lft <= n; lft = rgt + 1) {
        rgt = n / (n / lft);
        res = (res - (LL)(rgt - lft + 1) * GetSum(n / lft) % MOD) % MOD;
    }
    return Sum[n] = (res + MOD) % MOD;
}

int main() {
    Init(MAXN);
    int N, Ans = 0; scanf("%d", &N);
    for (int lft = 1, rgt = 1; lft <= N; lft = rgt + 1) {
        rgt = N / (N / lft);
        Ans = (Ans + ((LL)(GetSum(rgt) - GetSum(lft - 1)) * (N / lft) % MOD * (N / lft) % MOD * (N / lft) % MOD)) % MOD;
    }
    printf("%d", (Ans + MOD) % MOD);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值