#P5282. 【模板】快速阶乘算法

    ID: 6003 远端评测题 2000ms 256MiB 尝试: 0 已通过: 0 难度: 9 上传者: 标签>数学倍增O2优化快速傅里叶变换 FFT快速数论变换 NTT

【模板】快速阶乘算法

Background

One day, NaCly_Fish happened to see an efficient algorithm for computing factorial modulo a large prime, but she was too inexperienced to code it.
So she generated testdata by brute force, and asks you to help write the std.

What, you ask why it is not guaranteed that the modulus can be used for NTT?
If it were, people might pass by precomputing a table, or the answer might overflow int.

Anyway, you are a genius, so you can surely solve this problem instantly.

Problem Description

You are given a positive integer nn and a prime pp. You need to compute:

n! mod pn! \text{ mod } p

There are TT test cases.

Input Format

The first line contains a positive integer TT, the number of test cases.
The next TT lines each contain two positive integers n,pn, p, with the meaning described above.

Output Format

Output TT lines, each being the answer for one test case.

4
16777216 998244353
72267859 998244353
2333333 19260817
1919810 2147481811
789885751
569626621
16351109
1416439247

Hint

Constraints:

For 10%10\% of the testdata: p=998244353p = 998244353.
For another 10%10\% of the testdata: p=1004535809p = 1004535809.
For 100%100\% of the testdata: 1n<p23111 \le n < p \le 2^{31}-1, 1T51 \le T \le 5.
It is guaranteed that pp is prime.

[Hint]
Please make sure your algorithm runs in no more than Θ(nlogn)\Theta(\sqrt n \log n) time complexity. The time limit is more than ten times that of the std.

Translated by ChatGPT 5