This page is still under construction.

Parts of this page are still being built. What you see may change.

Quadratic Residue

Time limit1sMemory limit128 MB

Summary
For each test case, compute the Legendre symbol (a/p) for an odd prime p and integer a, using quadratic reciprocity.
Level

Medium7 of 10

Topics
Number theory, Math, Divide and conquer
Solved
No attempts yet

Problem

In 1801, Carl Friedrich Gauss (1777-1855) published "Disquisitiones Arithmeticae", which laid the foundations of modern number theory and is still in print today. One of the topics it treats most often is the quadratic residue.

You are given a prime pp and an integer aa with a≢0(modp)a \not\equiv 0 \pmod{p}. For aa to be a quadratic residue modulo pp, there must exist an integer xx such that

x2≡a(modp)x^2 \equiv a \pmod{p}

Legendre (1752-1833) introduced the following Legendre symbol.

(ap)={1a is a quadratic residue mod p−1a is not a quadratic residue mod p\left(\frac{a}{p}\right) = \begin{cases} 1 & a \text{ is a quadratic residue mod } p \\ -1 & a \text{ is not a quadratic residue mod } p \end{cases}

The Legendre symbol can be computed using the following properties, which hold only for distinct odd primes pp, qq and integers aa, bb not divisible by pp.

  1. (abp)=(ap)(bp)\left(\frac{ab}{p}\right) = \left(\frac{a}{p}\right)\left(\frac{b}{p}\right)
  2. (1p)=1\left(\frac{1}{p}\right) = 1
  3. a≡b(modp)⇒(ap)=(bp)a \equiv b \pmod{p} \Rightarrow \left(\frac{a}{p}\right) = \left(\frac{b}{p}\right)
  4. (−1p)=(−1)(p−1)/2,(2p)=(−1)(p2−1)/8\left(\frac{-1}{p}\right) = (-1)^{(p-1)/2}, \quad \left(\frac{2}{p}\right) = (-1)^{(p^2-1)/8}
  5. (pq)(qp)=(−1)(p−1)(q−1)/4\left(\frac{p}{q}\right)\left(\frac{q}{p}\right) = (-1)^{(p-1)(q-1)/4}

For example, the Legendre symbol can be computed as follows.

(2979)=(−1)78⋅28/4(7929)=(7929)=(−829)=(−129)(229)3=(−129)(229)=(−1)28/2(−1)(292−1)/8=(−1)14(−1)105=−1\left(\frac{29}{79}\right) = (-1)^{78\cdot28/4} \left(\frac{79}{29}\right) = \left(\frac{79}{29}\right) = \left(\frac{-8}{29}\right) = \left(\frac{-1}{29}\right) \left(\frac{2}{29}\right)^{3} = \left(\frac{-1}{29}\right) \left(\frac{2}{29}\right) = (-1)^{28/2}(-1)^{(29^2-1)/8} = (-1)^{14}(-1)^{105} = -1

Input

The input consists of several test cases. The first line contains the number of test cases TT. Each of the following test cases consists of two integers aa and pp. Here pp (2<p<109)(2 < p < 10^9) is an odd prime, and aa satisfies a≢0(modp)a \not\equiv 0 \pmod{p} and ∣a∣≤109\left| a \right| \le 10^9.

Output

For each test case, print "Scenario #i:" on the first line, where ii is the test case number starting from 1. On the next line, print the value of the Legendre symbol (ap)\left(\frac{a}{p}\right) (either 1 or -1). Print one blank line between the outputs of consecutive test cases.

Examples1

  1. Example 1

    Input
    3
    29 79
    2 29
    1 3
    
    Expected output
    Scenario #1:
    -1
    
    Scenario #2:
    -1
    
    Scenario #3:
    1