BZOJ4833: [Lydsy1704 Monthly Contest] Least Common Multiple of Pell Numbers — Solution
Main Idea
Although it's a standard-trick problem, I decided to write a blog post to reinforce it, so as to fully appreciate the charm of min-max inversion.
If we roughly work it out, we find:
\[ f_n = 2f_{n - 1} + f_{n - 2} \]
So, what we now need to compute is:
\[ \sum_{i = 1}^n i \text{lcm}_{j = 1}^i f_j \]
How can we optimize the process of taking the LCM of many numbers with min-max inversion? First, we regard each number as a set; then the weight of that set is the product of the factors in it. Then, the greatest common divisor of two numbers can be understood as the intersection of the two sets. Since we want the largest set (the least common multiple), we can write down the relation:
\[ \begin{gathered} \max(S)=\sum_{\emptyset\neq T\subseteq S}(-1)^{|T|-1}\min(T) \\ \text{lcm}_{i = 1}^n f_i = \prod_{T \subset S, T \neq \emptyset} \gcd(T)^{(-1)^{|T| - 1}} \end{gathered} \]
Then we know one thing, namely \(\gcd(f_a, f_b) = f_{\gcd(a, b)}\), and we substitute it in:
\[ \text{lcm}_{i = 1}^n f_i = \prod_{T \subset S, T \neq \emptyset} f_{\gcd(T)}^{(-1)^{|T| - 1}} \]
Ever-popular step: we can consider computing that contribution in the exponent:
\[ \text{lcm}_{i = 1}^n f_i = \prod_{d = 1}^n f_d^{\sum_{d | x} [x \leq n] \mu(\frac{x}{d})} \]
Just flip it around:
\[ \text{lcm}_{i = 1}^n f_i = \prod_{d = 1}^n \prod_{i | d} f_i^{\mu(\frac{d}{i})} \]
Code
// BZ4833.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e6 + 200;
int T, n, mod, primes[MAX_N], tot, mu[MAX_N], f[MAX_N], finv[MAX_N], units[MAX_N];
bool vis[MAX_N];
int fpow(int bas, int tim)
{
int ret = 1;
while (tim)
{
if (tim & 1)
ret = 1LL * ret * bas % mod;
bas = 1LL * bas * bas % mod;
tim >>= 1;
}
return ret;
}
void sieve()
{
mu[1] = 1;
for (int i = 2; i < MAX_N; i++)
{
if (!vis[i])
primes[++tot] = i, mu[i] = -1;
for (int j = 1; j <= tot && 1LL * i * primes[j] < MAX_N; j++)
{
vis[i * primes[j]] = true;
if (i % primes[j] == 0)
{
mu[i * primes[j]] = 0;
break;
}
mu[i * primes[j]] = -mu[i];
}
}
}
int main()
{
scanf("%d", &T), sieve();
while (T--)
{
scanf("%d%d", &n, &mod);
f[1] = 1, finv[1] = 1;
for (int i = 2; i <= n; i++)
f[i] = (2LL * f[i - 1] + f[i - 2]) % mod, finv[i] = fpow(f[i], mod - 2);
for (int i = 1; i <= n; i++)
units[i] = 1;
for (int i = 1; i <= n; i++)
for (int j = i; j <= n; j += i)
if (mu[j / i] < 0)
units[j] = 1LL * units[j] * finv[i] % mod;
else if (mu[j / i] > 0)
units[j] = 1LL * units[j] * f[i] % mod;
for (int i = 2; i <= n; i++)
units[i] = 1LL * units[i - 1] * units[i] % mod;
int ans = 0;
for (int i = 1; i <= n; i++)
ans = (0LL + ans + 1LL * units[i] * i % mod) % mod;
printf("%d\n", ans);
}
return 0;
}