[Luogu] P3708 koishi的数学题

(Link)

Description

输入一个整数(n),设(f(x) = sumlimits_{i=1}^n x mod {i}),你需要输出(f(1), f(2), ldots , f(n))((nle{10^6}))

Solution

(f(x)=sumlimits_{i=1}^n x mod {i}=sumlimits_{i=1}^n x-ilfloor{frac{x}{i}} floor=nx-sumlimits_{i=1}^nilfloor{frac{x}{i}} floor)

(f(x-1)=n(x-1)-sumlimits_{i=1}^nilfloor{frac{x-1}{i}} floor)

(f(x)-f(x-1)=n-sumlimits_{i=1}^ni(lfloor{frac{x}{i}} floor-lfloor{frac{x-1}{i}} floor)=n-sumlimits_{i=1}^ni[i|x]=n-sigma(x))

累加,有(f(x)=nx-sumlimits_{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;
}
原文地址:https://www.cnblogs.com/andysj/p/13963329.html