51Nod - 1244 莫比乌斯函数之和——杜教筛

版权声明:欢迎大家转载,转载请注明出处 https://blog.csdn.net/hao_zong_yin/article/details/82563335
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5e6+10;
bool vis[maxn];
int mu[maxn], sum[maxn], prime_cnt, prime[maxn];
map<ll, ll> MAP;
void init() {
    mu[1] = sum[1] = 1;
    for (int i = 2; i < maxn; i++) {
        if (!vis[i]) prime[++prime_cnt] = i, mu[i] = -1;
        for (int j = 1; j <= prime_cnt && i * prime[j] < maxn; j++) {
            vis[i*prime[j]] = 1;
            if (i % prime[j] == 0) break;
            mu[i*prime[j]] = -mu[i];
        }
        sum[i] = sum[i-1]+mu[i];
    }
}
ll cal(ll x) {
    if (x < maxn) return sum[x];
    if (MAP[x]) return MAP[x];
    ll ans = 0;
    for (ll i = 2, j; i <= x; i = j+1) {
        j = x / (x/i);
        ans += (j-i+1)*cal(x/i);
    }
    return MAP[x] = 1-ans;
}
int main() {
    init();
    ll x, y;
    scanf("%lld%lld", &x, &y);
    printf("%lld\n", cal(y) - cal(x-1));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hao_zong_yin/article/details/82563335