Description
输入一个整数\(n\),设\(f(x) = \sum\limits_{i=1}^n x \bmod {i}\),你需要输出\(f(1), f(2), \ldots , f(n)\)。\((n\le{10^6})\)
Solution
\(f(x)=\sum\limits_{i=1}^n x \bmod {i}=\sum\limits_{i=1}^n x-i\lfloor{\frac{x}{i}}\rfloor=nx-\sum\limits_{i=1}^ni\lfloor{\frac{x}{i}}\rfloor\)
\(f(x-1)=n(x-1)-\sum\limits_{i=1}^ni\lfloor{\frac{x-1}{i}}\rfloor\)
\(f(x)-f(x-1)=n-\sum\limits_{i=1}^ni(\lfloor{\frac{x}{i}}\rfloor-\lfloor{\frac{x-1}{i}}\rfloor)=n-\sum\limits_{i=1}^ni[i|x]=n-\sigma(x)\)
累加,有\(f(x)=nx-\sum\limits_{i=1}^{x}\sigma(i)\)
\(O(n)\)求出约数和即可。
(约数和及约数个数和见一个巨佬的博客)
Code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int n, tot, vis[1000005], pr[250005];
ll low[1000005], sd[1000005], sum[1000005];
int read()
{
int x = 0, fl = 1; char ch = getchar();
while (ch < '0' || ch > '9') { if (ch == '-') fl = -1; ch = getchar();}
while (ch >= '0' && ch <= '9') {x = (x << 1) + (x << 3) + ch - '0'; ch = getchar();}
return x * fl;
}
int main()
{
n = read();
sd[1] = 1; low[1] = 1;
for (int i = 2; i <= n; i ++ )
{
if (!vis[i])
{
vis[i] = i;
pr[ ++ tot] = i;
low[i] = i + 1;
sd[i] = i + 1;
}
for (int j = 1; j <= tot; j ++ )
{
if (i * pr[j] > n || pr[j] > vis[i]) break;
vis[i * pr[j]] = pr[j];
if (i % pr[j]) sd[i * pr[j]] = 1ll * sd[i] * (1ll + pr[j]), low[i * pr[j]] = 1ll + pr[j];
else sd[i * pr[j]] = 1ll * sd[i] / low[i] * (low[i] * pr[j] + 1ll), low[i * pr[j]] = 1ll * low[i] * pr[j] + 1ll;
}
}
for (int i = 1; i <= n; i ++ )
sum[i] = sum[i - 1] + sd[i];
for (int i = 1; i <= n; i ++ )
printf("%lld ", 1ll * n * i - sum[i]);
return 0;
}