其他分享
首页 > 其他分享> > luogu P2522-Problem b (莫比乌斯反演)

luogu P2522-Problem b (莫比乌斯反演)

作者:互联网

题意:

求 x 在[a, b]范围内,y 在[c, d]范围内的满足 gcd(x, y) = k 的x,y对数。

题解:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int N = 1e6 + 5;

int T, k, a, b, c, d;
int pri[N], cnt;
int mu[N];
int vis[N];
int sum[N];

void prime(){
    mu[1] = 1;
    sum[1] = 1;
    for(int i = 2; i <= 4e5; ++ i){
        if(!vis[i]){
            pri[++ cnt] = i;
            mu[i] = -1;
        }
        for(int j = 1; j <= cnt && pri[j] * i <= 4e5; ++ j){
            vis[pri[j] * i] = 1;
            if(i % pri[j] == 0){
                mu[pri[j] * i] = 0;
                break;
            }
            mu[pri[j] * i] = -mu[i];
        }
        sum[i] = sum[i - 1] + mu[i];
    }
}


ll sol(ll n, ll m, ll k){
    n /= k, m /= k;
    ll res = 0;
    if(n > m) swap(n, m);
    for(int i = 1, last = 1; i <= n; i = last + 1){
        last = min(n / (n / i), m / (m / i));
        res += (ll)(sum[last] - sum[i - 1]) * (n / i) * (m / i);
    }
    return res;
}

int main()
{
    prime();
    scanf("%d",&T);
    for(int Case = 1; Case <= T; ++ Case){
        scanf("%d%d%d%d%d", &a, &b, &c, &d, &k);
        ll ans = sol(b, d, k) - sol(a - 1, d, k) - sol(b, c - 1, k) + sol(a - 1, c - 1, k);
        printf("%lld\n", ans);
    }
    return 0;
}

标签:gcd,int,luogu,sol,long,反演,P2522,include
来源: https://www.cnblogs.com/A-sc/p/12626514.html