Link: http://poj.org/problem? Id = 1808
Http://acm.timus.ru/problem.aspx? Space = 1 & num = 1132
Question: both questions are template questions. The first is to determine whether there is square surplus, and the second is to calculate the square surplus.
Train of Thought: The square surplus is given a, n (n is the prime number) Ask x ^ 2 then a (mod n) whether there is a solution, you can use a ^ (n-1)/2) when mod n is 1, it is a quadratic residue, and-1 is a non-quadratic residue.
MATERIALS: http://blog.csdn.net/acdreamers/article/details/10182281
The references are basically correct. Note that the same and equal relationships are distinguished.
Code:
LL w;LL pow_mod(LL aa,LL ii,LL nn){ if(ii==0) return 1%nn; LL temp=pow_mod(aa,ii>>1,nn); temp=temp*temp%nn; if(ii&1) temp=temp*aa%nn; return temp;}struct comp{ LL r,i;};comp multi(comp a, comp b, LL m) { comp ans; ans.r = (a.r * b.r % m + a.i * b.i % m * w % m) % m; ans.i = (a.r * b.i % m + a.i * b.r% m) % m; return ans; } comp pow_mod(comp a, LL b,LL m) { comp ans; ans.r = 1; ans.i = 0; while(b) { if(b & 1) { ans = multi(ans, a, m); b--; } b >>= 1; a = multi(a, a, m); } return ans; }LL Legendre(LL a, LL p){ return pow_mod(a, (p-1)>>1, p);}LL Quadratic_residue(LL n,LL p){ if(p==2) return 1; if (Legendre(n, p) + 1 == p) return -1; LL a = -1, t; while(1) { a = rand() % p; t = a * a - n; w=(t%p+p)%p; if(Legendre(w, p) + 1 == p) break; } comp temp; temp.r=a; temp.i=1; comp ans; ans=pow_mod(temp,(p+1)>>1,p); return ans.r;}