BZOJ4805: 欧拉函数求和(杜教筛)

题意

题目链接

Sol

杜教筛板子题。。

#include<bits/stdc++.h>
#define LL long long 
using namespace std;
const int MAXN = 1e7 + 10;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while (c < '0' || c > '9') {if (c == '-')f = -1; c = getchar();}
    while (c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
    return x * f;
}
int N, prime[MAXN], tot, vis[MAXN], Lim;
LL phi[MAXN];
map<LL, LL> mp;
void Get(int N) {
    vis[1] = 1; phi[1] = 1;
    for(int i = 2; i <= N; i++) {
        if(!vis[i]) prime[++tot] = i, phi[i] = i - 1;
        for(int j = 1; j <= tot && (i * prime[j] <= N); j++) {
            vis[i * prime[j]] = 1;
            if(!(i % prime[j])) {
                phi[i * prime[j]] = 1ll * phi[i] * prime[j]; break;
            } else phi[i * prime[j]] = 1ll * phi[i] * (prime[j] - 1);
        }
    }
    for(int i = 2; i <= N; i++) phi[i] += phi[i - 1];
}
LL sieve(LL x) {
    if(x <= Lim) return phi[x];
    if(mp.find(x) != mp.end()) return mp[x];
    LL ans = 1ll * x * (x + 1) / 2;
    for(LL i = 2, nxt; i <= x; i = nxt + 1) {
        nxt = min(x, x / (x / i));
        ans -= 1ll * sieve(x / i) * (nxt - i + 1);
    }
    return mp[x] = ans;
}
signed main() {
    N = read();
    Get(Lim = 1e6);
    cout << sieve(N);
    return 0;
}
/*
1000000000
*/
posted @ 2018-12-07 11:01  自为风月马前卒  阅读(299)  评论(2编辑  收藏  举报

Contact with me