DCEPC11B - Boring Factorials


Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot. Aman, their friend has been helping them out. But as it goes, Sameer and Arpit have got bored of problems involving factorials. Reason being, the factorials are too easy to calculate in problems as they only require the residue modulo some prime and that is easy to calculate in linear time. So to make things interesting for them, Aman - The Mathemagician, gives them an interesting task. He gives them a prime number P and an integer N close to P, and asks them to find N! modulo P. He asks T such queries.

Input

First line contains an integer T, the number of queries asked.

Next T lines contains T queries of the form “N P”. (quotes for clarity)

Output

Output exactly T lines, containing N! modulo P.

Example

Input:
3
2 5
5 11
21 71

Output:
2
10
6
Constraints:

1 <= T <= 1000

1 < P <= 2*10^9

1 <= N <= 2*10^9

Abs(N-P) <= 1000

hide comments
ANKIT KUMAR CODOPEDIAC: 2014-08-18 19:58:36

the time limit is so bad that if you do mod more times then it will give tle... in my ac soln i just redused the no. of mod i was taking

shiva: 2014-07-28 22:22:06

IS there any tricky test case...??
running on ideone but here getting wa
plj check my solution
<snip>

Last edit: 2022-07-20 11:58:14
sarelfeniel: 2014-07-07 06:45:04

What a great problem.

Samar Holkar: 2014-07-02 20:14:45

Wow .....brilliant concept...

ABHISHEK004: 2014-06-03 15:54:35

finally my 200th problem on spoj!!!!! :D

Sam Winchester: 2014-05-25 20:23:00

really a nice question ...

P_Quantum: 2014-05-18 21:37:26

Learn a lot.. nice ques..!!


Added by:dce coders
Date:2013-10-01
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:C CSHARP C++ 4.3.2 CPP C99 HASK JAVA PAS-GPC PAS-FPC PYTHON PYTHON3 PY_NBC
Resource:Own Problem