杜教筛的模板题:
推出式子就可以了。
具体的怎么推放到杜教筛里讲。
这题主要常数卡得厉害,把预处理的范围开大后冲过去了
还有两种情况,n * (n + 1) 可能会爆long long。
然后r = 2147483647时,L + 1就爆int了,所以也要特判。
#include<bits/stdc++.h> using namespace std; typedef long long LL; typedef pair<int,int> pii; typedef unsigned long long ULL; const int N = 5e6+5; const int M = 1e6+5; const LL Mod = 9999999967; #define rg register #define pi acos(-1) #define INF 1e18 #define CT0 cin.tie(0),cout.tie(0) #define IO ios::sync_with_stdio(false) #define dbg(ax) cout << "now this num is " << ax << endl; namespace FASTIO{ inline LL read() { LL x = 0,f = 1;char c = getchar(); while(c < '0' || c > '9'){if(c == '-')f = -1;c = getchar();} while(c >= '0' && c <= '9'){x = (x << 1) + (x << 3) + (c ^ 48);c = getchar();} return x * f; } void print(int x){ if(x < 0){x = -x;putchar('-');} if(x > 9) print(x/10); putchar(x%10+'0'); } } using namespace FASTIO; int m = 5000000; int prime[N],tot = 0; LL phi[N],mu[N]; bool vis[N]; unordered_map<int,LL> mp1,mp2; void init() { mu[1] = 1,phi[1] = 1; for(rg int i = 2;i <= m;++i) { if(!vis[i]) { prime[++tot] = i; phi[i] = i - 1; mu[i] = -1; } for(rg int j = 1;j <= tot && prime[j] * i <= m;++j) { vis[prime[j] * i] = 1; if(i % prime[j] == 0){phi[prime[j] * i] = phi[i] * prime[j];break;} else { mu[prime[j] * i] = -mu[i]; phi[prime[j] * i] = phi[prime[j]] * phi[i]; } } } for(rg int i = 1;i <= m;++i) phi[i] += phi[i - 1]; for(rg int i = 1;i <= m;++i) mu[i] += mu[i - 1]; } LL solve1(int n)//欧拉函数前缀和 { if(n <= m) return phi[n]; if(mp1[n]) return mp1[n]; LL ans = 0; for(rg int L = 2,r = 0;L <= n && r < 2147483647;L = r + 1) { r = n / (n / L); ans += (r - L + 1) * solve1(n / L); } return mp1[n] = ((ULL)n * (n + 1) / 2) - ans; } LL solve2(int n)//莫比乌斯函数前缀和 { if(n <= m) return mu[n]; if(mp2[n]) return mp2[n]; LL ans = 1; for(rg int L = 2,r = 0;L <= n && r < 2147483647;L = r + 1) { r = n / (n / L); ans -= (r - L + 1) * solve2(n / L); } return mp2[n] = ans; } int main() { init(); int ca;ca = read(); while(ca--) { int n;n = read(); printf("%lld %lld ",solve1(n),solve2(n)); } system("pause"); return 0; }