[洛谷 P6055] [RC-02] GCD (莫比乌斯反演 杜教筛)

题意

∑ i = 1 n ∑ j = 1 n ∑ p = 1 ⌊ n j ⌋ ∑ q = 1 ⌊ n j ⌋ [ gcd ⁡ ( i , j ) = 1 ] [ gcd ⁡ ( p , q ) = 1 ] \sum_{i=1}^{n}\sum_{j=1}^{n}\sum_{p=1}^{\lfloor \frac{n}{j} \rfloor} \sum_{q=1}^{\lfloor \frac{n}{j} \rfloor}[\gcd(i,j)=1][\gcd(p,q)=1] i=1nj=1np=1jnq=1jn[gcd(i,j)=1][gcd(p,q)=1]

998244353 998244353 998244353 取模

分析:

常规套用莫比乌斯反演式子会很麻烦,所以这里反向把上界拿下来

∑ i = 1 n ∑ j = 1 n ∑ p = 1 n ∑ 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,j)=1][\gcd(p,q)=j] i=1nj=1np=1nq=1n[gcd(i,j)=1][gcd(p,q)=j]

那么就是

∑ i = 1 n ∑ j = 1 n ∑ k = 1 n [ gcd ⁡ ( i , j , k ) = 1 ] \sum_{i=1}^{n}\sum_{j=1}^{n}\sum_{k=1}^{n} [\gcd(i,j,k)=1] i=1nj=1nk=1n[gcd(i,j,k)=1]

再来莫比乌斯反演

∑ i = 1 n ∑ j = 1 n ∑ k = 1 n ∑ d ∣ gcd ⁡ ( i , j , k ) μ ( d ) \sum_{i=1}^{n}\sum_{j=1}^{n}\sum_{k=1}^{n} \sum_{d \mid \gcd(i,j,k)}\mu(d) i=1nj=1nk=1ndgcd(i,j,k)μ(d)

化简一下

∑ d = 1 n μ ( d ) ⌊ n d ⌋ 3 \sum_{d=1}^{n}\mu(d) \lfloor\frac{n}{d}\rfloor^3 d=1nμ(d)dn3

就可以用杜教筛了

代码:

#include 
#define int long long
using namespace std;
const int N = 2e6 + 5, mod = 998244353;
int n, mobius[N], primes[N], cnt, sum[N], res;
bool st[N];
unordered_map<int, int> mp;
void get_mobius(int n) {
    mobius[1] = 1;
    for (int i = 2; i <= n; i ++) {
        if (!st[i]) {
            primes[cnt ++] = i;
            mobius[i] = -1;
        }
        for (int j = 0; primes[j] * i <= n; j ++) {
            int t = primes[j] * i;
            st[t] = 1;
            if (i % primes[j] == 0) {
                mobius[t] = 0;
                break;
            }
            mobius[t] = -mobius[i];
        }
    }
    for (int i = 1; i <= n; i ++) sum[i] = (sum[i - 1] + mobius[i] + mod) % mod;
}
int Sum(int n) {
    if (n < N) return sum[n];
    if (mp[n]) return mp[n];
    int res = 1;
    for (int l = 2, r; l <= n; l = r + 1) {
        r = n / (n / l);
        res = (res - Sum(n / l) * (r - l + 1) % mod + mod) % mod;
    }
    return mp[n] = res;
}
signed main() {
    get_mobius(N - 1);
    cin >> n;
    for (int l = 1, r; l <= n; l = r + 1) {
        r = n / (n / l);
        res = (res + (Sum(r) - Sum(l - 1)) * (n / l) % mod * (n / l) % mod * (n / l) % mod + mod) % mod;
    }
    cout << res << endl;
}

你可能感兴趣的:(数论题,算法,数论,杜教筛)