# 线性筛积性函数

#### 积性函数

$$f(n),\ g(n)$$都是积性函数，则$$f(x^p),\ f^p(x),\ f(x)g(x),\ (f*g)(n)$$也是积性函数。

#### 线性筛积性函数

int pri[N], tot, vis[N];

void sieve(int n)
{
for (int i = 2; i <= n; ++i)
{
if (!vis[i])
{
pri[++tot] = i;
//1
}
for (int j = 1; j <= tot && pri[j] * i <= n; ++j)
{
vis[pri[j] * i] = 1;
//2
if (i % pri[j] == 0) break;
}
}
}


$$1$$$$i$$为素数，$$f(x)$$可以$$O(1)$$求出。

$$2$$处复杂一点，其实是要求出$$f(pri_j*i)$$的值。

$$pri_j<p_1$$，则$$f(pri_j*i)=f(pri_j)f(i)$$

$$pri_j=p_1$$，设$$low_i=p_1^{\alpha_1}$$（就是上面唯一分解$$i$$中的第一项），$$f(pri_j*i)=f(\frac{i}{low_i})f(low_i*pri_j)$$

void Sieve(int N)
{
f[1] = ...;//求f(1)
low[1] = 1;

for (int i = 2; i <= N; ++i)
{
if (!vis[i])
{
low[i] = pri[++tot] = i;
f[i] = ...;//求f(p)
}
for (int j = 1; j <= tot && pri[j] * i <= N; ++j)
{
vis[pri[j] * i] = 1;
if (i % pri[j] == 0)
{
low[pri[j] * i] = low[i] * pri[j];

if (low[i] == i)
f[pri[j] * i] = ...;//求f(p^k)(一般由f(p^(k-1))推出)
else
f[pri[j] * i] = f[i / low[i]] * f[low[i] * pri[j]];
break;
}

low[pri[j] * i] = pri[j];
f[pri[j] * i] = f[i] * f[pri[j]];
}
}
}


#### 例题

$$\rm{SPOJ}\ 5971\ \rm{LCMSUM}$$

$\sum_{i=1}^{n}lcm(i,n)=\frac{1}{2}n(\sum_{d|n}d\cdot\varphi(d) + 1)$

$$f(n)=\sum_{d|n}d\cdot\varphi(d)$$，不难证$$f(n)$$为积性函数。

\begin{align} f(n)f(m) & = \sum_{d|n}d\cdot\varphi(d)\sum_{d'|m}d'\cdot\varphi(d') \\ & = \sum_{dd'|nm}dd'\cdot\varphi(d)\varphi(d')\\ & = \sum_{dd'|nm}dd'\cdot\varphi(dd') \\ & = f(nm) \end{align}

#include<bits/stdc++.h>
using namespace std;

#define int long long

{
int x = 0, f = 1; char ch = getchar();
for (; ch < '0' || ch > '9'; ch = getchar()) if (ch == '-') f = -1;
for (; ch >= '0' && ch <= '9'; ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
return x * f;
}

const int N = 1e6 + 5;
int p[N], tot, f[N], low[N]; //f_n = \sum_{d | n} phi_d * d;
bool vis[N];

void Sieve()
{
f[1] = 1;
low[1] = 1;

for (int i = 2; i < N; ++i)
{
if (!vis[i])
{
low[i] = p[++tot] = i;
f[i] = i * (i - 1) + 1;
}
for (int j = 1; j <= tot && p[j] * i < N; ++j)
{
vis[p[j] * i] = 1;
if (i % p[j] == 0)
{
low[p[j] * i] = low[i] * p[j];

if (low[i] == i)
f[p[j] * i] = f[i] + p[j] * i * i * (p[j] - 1);
else
f[p[j] * i] = f[i / low[i]] * f[low[i] * p[j]];
break;
}

low[p[j] * i] = p[j];
f[p[j] * i] = f[i] * f[p[j]];
}
}
}

signed main()
{
Sieve();