BZOJ 2820 YY的GCD

2820 YY的GCD
思路:
莫比乌斯反演+整除分块
代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#pragma GCC optimize(4)
#include<bits/stdc++.h>
using namespace std;
#define y1 y11
#define fi first
#define se second
#define pi acos(-1.0)
#define LL long long
//#define mp make_pair
#define pb emplace_back
#define ls rt<<1, l, m
#define rs rt<<1|1, m+1, r
#define ULL unsigned LL
#define pll pair<LL, LL>
#define pli pair<LL, int>
#define pii pair<int, int>
#define piii pair<pii, int>
#define pdd pair<double, double>
#define mem(a, b) memset(a, b, sizeof(a))
#define debug(x) cerr << #x << " = " << x << "\n";
#define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
//head

const int N = 1e7 + 10;
int T, n, m;
int prime[N/10], mu[N], sum[N], cnt;
bool not_p[N];
LL s[N];
void seive() {
    mu[1] = 1;
    for (int i = 2; i < N; ++i) {
        if(!not_p[i]) prime[++cnt] = i, mu[i] = -1;
        for (int j = 1; j <= cnt && i*prime[j] < N; ++j) {
            not_p[i*prime[j]] = true;
            if(i%prime[j] == 0) {
                mu[i*prime[j]] = 0;
                break;
            }
            mu[i*prime[j]] = -mu[i];

        }
    }
    for (int i = 2; i < N; ++i) {
        if(!not_p[i])
            for (int j = i; j < N; j += i) sum[j] += mu[j/i];
    }
    for (int i = 1; i < N; ++i) s[i] = s[i-1] + sum[i];
}
int main() {
    seive();
    scanf("%d", &T);
    while(T--) {
        scanf("%d %d", &n, &m);
        LL ans = 0;
        int up = min(n, m);
        for (int l = 1, r; l <= up; l = r+1) {
            r = min(n/(n/l), m/(m/l));
            ans += (n/l)*1LL*(m/l)*(s[r]-s[l-1]);
        }
        printf("%lld\n", ans);
    }
    return 0;
}

posted @ 2019-09-13 14:37  Wisdom+.+  阅读(167)  评论(0编辑  收藏  举报