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×109

1 ≤ N ≤ 2×109

Abs(N-P) ≤ 1000

hide comments
Murad Al Wajed: 2016-04-24 18:09:42

awesome problem. learned something new

Parul Yadav: 2015-09-05 05:11:41

learned something new

sakshi: 2015-09-03 16:53:05

my 50th :)

Tej Bahadur Singh : 2015-08-11 16:25:34

tle tle tle...finally accepted using less number of % operator..learned new thing

Tej Bahadur Singh : 2015-08-01 13:18:37

still giving tle used wilson and fermat's theorum. what do???

uptoyou: 2015-06-26 09:12:59

what theorem should i learn so that i'm able to solve this problem?

kp: 2015-06-26 06:50:09

After high optimization AC at 0.02 :)

Diksha Jaiswal: 2015-05-31 07:34:57

nice mathematical problem

karan: 2015-04-25 15:50:01

i dont know why the name is boring.. its an interesting factorial :D

Madhav: 2015-03-31 16:22:34

New concepts learned!!


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