LEGRENDS - Legendre symbol

Given 2 integers a and p (1 ≤ a, p ≤ 1000000, p is prime) calculate the Legendre symbol (a/p).

Input

In the first line the number of test cases t < 100000. Then t lines with the 2 integers a and p.

Output

t lines with the Legendre symbol (a/p).

Example

Input:
4
2 7
5 7
14 7
3 2 Output: 1
-1
0
1

Added by:HWK
Date:2011-07-11
Time limit:3.049s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64

hide comments
2011-07-23 10:27:23 Problem Solver
Nice problem, didn't know this symbol :)
2011-07-23 10:27:23 HWK
@Alex Anderson: To allow solutions in languages like Python etc.
@Paulo Roberto Santos de Sousa: Go for 0.12 secs. ;-)
2011-07-23 10:27:23 Alex Anderson
Why is the time limit so high?
2011-07-23 10:27:23 HWK
@setsquare: Interesting things in your solution but with a faster algorithm it could be almost 0.2 secs faster.
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.