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
*/
作者:自为风月马前卒
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。