URAL 1132. Square Root
传送门
description
The number x is called a square root of a modulo n (root(a,n)) if x*x = a (mod n). Write the program to find the square root of number a by given modulo n.
Input
One number K in the first line is an amount of tests (K ≤ 100000). Each next line represents separate test, which contains integers a and n (1 ≤ a, n ≤ 32767, n is prime, a and n are relatively prime).
Output
For each input test the program must evaluate all possible values root(a,n) in the range from 1 to n − 1 and output them in increasing order in one separate line using spaces. If there is no square root for current test, the program must print in separate line: ‘No root’.
Sample
input
5
4 17
3 7
2 7
14 31
10007 20011
output
2 15
No root
3 4
13 18
5382 14629
首先这道题要我们找x满足x2=a(mod n)
这个就是典型的二次剩余,题目已经说过n为质数,所以n一定和a互质,所以我们只需要n为质数的情况就行了,首先考虑n为2的特殊情况,由于n和a范围都是1到32767,故当n为2的时候答案为0或者1,因为答案规定在0~n-1范围内,所以当a为偶数的时候就是0,奇数就是1.
其次考虑一般情况,n为奇素数:
勒让德符号
( n p ) = { 1 , n 在 模 p 意 义 下 是 二 次 剩 余 − 1 , n 在 模 p 意 义 下 是 非 二 次 剩 余 0 , n ≡ 0 ( m o d p ) (\frac{n}{p})= \begin{cases} 1,n在模p意义下是二次剩余\\-1,n在模p意义下是非二次剩余\\0,n\equiv0(mod~p) \end{cases} (pn)=⎩⎪⎨⎪⎧1,n在模p意义下是二次剩余−1,n在模p意义下是非二次剩余0,n≡0(mod p)
对于勒让德符号有 ( n p ) = n p − 1 2 ( m o d p ) (\frac{n}{p})=n^\frac{p-1}{2}(mod~p) (pn)=n