Skip to content

Commit 10ba4fb

Browse files
committed
线性时间预处理[1,n]阶乘的逆元
1 parent ee5d83d commit 10ba4fb

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include <cstdio>
2+
3+
#define MAX_N 10000000
4+
5+
typedef long long ll;
6+
7+
using namespace std;
8+
9+
// p must be a prime greater than n.
10+
ll n, fac_inv[MAX_N], p;
11+
12+
ll qpow(ll x, ll y)
13+
{
14+
if (y == 1) return x;
15+
ll t = qpow(x, y >> 1);
16+
t = t * t % p;
17+
if ((y & 1) == 0) return t;
18+
else return t * x % p;
19+
}
20+
21+
ll fac(ll x)
22+
{
23+
ll res = 1;
24+
for (int i = 2; i <= x; i++)
25+
{
26+
res = res * i % p;
27+
}
28+
return res;
29+
}
30+
31+
void fac_inv_sieve()
32+
{
33+
fac_inv[n] = qpow(fac(n), p - 2);
34+
for (ll i = n - 1; i >= 1; i--)
35+
{
36+
fac_inv[i] = fac_inv[i + 1] * (i + 1) % p;
37+
}
38+
}
39+
40+
int main()
41+
{
42+
scanf("%lld%lld", &n, &p);
43+
fac_inv_sieve();
44+
for (int i = 1; i <= n; i++)
45+
{
46+
printf("inv(fac(%d)) mod %lld = %lld\n", i, p, fac_inv[i]);
47+
}
48+
return 0;
49+
}

0 commit comments

Comments
 (0)