Calculation of Mobius inversion

Picked from other people's courseware (qwq


problem:

Knowing \ (f (1) \ cdots f (n) \) , and \ (g = f * \ mu \) , calculate \ (g (1) \ cdots g (n) \) .


Solution 1

Calculate according to the definition, ie directly according to \ (g (n) = \ sum_ {d | n} f (d) \ mu (\ frac {n} d) \) .
Code ( pseudo ):

for(int i=1; i<=n; ++i)
	for(int j=1; j<=n/i; ++j)
		g[i*j] += f[i] * mu[j];

The complexity is \ (O (n \ log n) \) .


Solution 2
Define number-theoretic functions

\[q_i(n) = \begin{cases} 1 \quad n=1 \\ -1 \quad n = p_i \\ 0 \quad else \end{cases} \]

Where \ (p_i \) is the \ (i \) prime number.
You can find \ (\ mu = q_1 * q_2 * q_3 * \ cdots \) , so \ (g = f * q_1 * q_2 * q_3 * \ cdots \) .

To roll a function into \ (q_i \) , it only takes \ (O (\ frac {n} {p_i}) \) time, so the total complexity is \ (\ sum_ {p \ leq n} \ frac { n} p = O (n \ log \ log n) \) .

Code ( pseudo )

for(int i=1; i<=n; ++i) g[i] = f[i];
for(int i=1; i<=pr_cnt; ++i)
	for(int j = n/prime[i]; j>0; --j) //这样算的原因类似0/1背包qwq
		g[j * prime[i]] -= g[j];

Guess you like

Origin www.cnblogs.com/tztqwq/p/12760647.html