Dyd's Blog

He who has a strong enough why can bear almost any how.

luoguP2155 [SDOI2008] 沙拉公主的困惑

感觉式子很有用

沙拉公主的困惑

思路

先给式子: $Ans = \frac{n!}{m!} * \varphi(m!)$ ,打开就是 $n!\frac{\prod(p - 1)}{\prod p},其中p是m!的约数$

直接预处理即可,注意当 $n!$ 里包含模数而且分母没有约掉的话直接输出 $0$

看起来很简单,但式子不好推,比较简单的推法是写成 $\gcd(x, y) == 1$ 然后上欧拉反演即得

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>
using LL = long long;
const int N = 1e7 + 100;
int n, m, P, ans;
int fac[N], pr[N], cnt, imp[N], mp[N];
bool vis[N];
int qpow(int x, int y)
{
int res = 1;
for (; y; y >>= 1, x = LL(x) * x % P) if (y & 1) res = LL(res) * x % P;
return res;
}
void prev()
{
fac[0] = fac[1] = 1;
for (int i = 2; i < N; ++i) fac[i] = LL(fac[i - 1]) * i % P;
for (int i = 2; i < N; ++i)
{
if (!vis[i]) pr[++cnt] = i;
for (int j = 1; j <= cnt && LL(pr[j]) * i < N; ++j)
{
vis[pr[j] * i] = true;
if (i % pr[j] == 0) break;
}
}
for (int i = 1, j = 1, sum = 1, is = 1; i < N; ++i)
{
if (pr[j] == P) ++j;
if (j <= cnt && pr[j] <= i) sum = LL(pr[j++]) * sum % P, is = qpow(sum, P - 2);
imp[i] = is;
}
for (int i = 1, j = 1, sum = 1; i < N; ++i)
{
if (j <= cnt && pr[j] <= i) sum = LL(pr[j++] - 1) * sum % P;
mp[i] = sum;
}
}
int main()
{
int T;
scanf("%d %d", &T, &P);
prev();
while (T--)
{
scanf("%d %d", &n, &m);
if (n >= P && m < P) puts("0");
else
{
ans = LL(fac[n]) * imp[m] % P * mp[m] % P;
printf("%d\n", ans);
}
}
return 0;
}