BZOJ 1968: [Ahoi2005]COMMON 约数研究
线性筛求约数个数
一般跟质因子或者质因子个数有关的积性函数都可以用线性筛求
比如欧拉函数、莫比乌斯反演函数、约数个数函数、约数和函数等函数
考虑最小的质因子对转移的影响
代码:
#pragma GCC optimize(2) #pragma GCC optimize(3) #pragma GCC optimize(4) #include<bits/stdc++.h> using namespace std; #define fi first #define se second #define pi acos(-1.0) #define LL long long //#define mp make_pair #define pb push_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<long double, long double> #define mem(a, b) memset(a, b, sizeof(a)) #define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define fopen freopen("in.txt", "r", stdin);freopen("out.txt", "w", stout); //head const int N = 1e6 + 5; int f[N], num[N], prime[N]; bool not_p[N]; void seive(int n) { int tot = 0; f[1] = 1; for (int i = 2; i <= n; i++) { if(!not_p[i]) { prime[++tot] = i; f[i] = 2; num[i] = 1; } for (int j = 1; i*prime[j] <= n; j++) { not_p[i*prime[j]] = true; if(i%prime[j]) { f[i*prime[j]] = f[i]*2; num[i*prime[j]] = 1; } else { f[i*prime[j]] = f[i]/(num[i]+1)*(num[i]+2); num[i*prime[j]] = num[i] + 1; break; } } } LL ans = 1; for (int i = 2; i <= n; i++) ans += f[i]; printf("%lld\n", ans); } int main() { int n; scanf("%d", &n); seive(n); return 0; }