链接:
http://poj.org/problem?id=1808
题意:
判断x^2同余a(modn)是否存在
题解:
平方剩余
代码:
31 ll mod_pow(ll x, ll n, ll mod) { 32 int res = 1; 33 while (n) { 34 if (n & 1) res = res * x % mod; 35 x = x * x % mod; 36 n >>= 1; 37 } 38 return res; 39 } 40 41 ll mod_sqr(ll a, ll n) { 42 ll b, k, i, x; 43 //if (n == 2) return a%n; 44 if(mod_pow(a, (n - 1) / 2, n) == 1) { 45 return 1; 46 if (n % 4 == 3) x = mod_pow(a, (n + 1) / 4, n); 47 else { 48 for (b = 1; mod_pow(b, (n - 1) / 2, n) == 1; b++); 49 i = (n - 1) / 2; 50 k = 0; 51 do { 52 i /= 2; 53 k /= 2; 54 if ((mod_pow(a, i, n)*mod_pow(b, k, n) + 1) % n == 0) 55 k += (n - 1) / 2; 56 } while (i % 2 == 0); 57 x = mod_pow(a, (i + 1) / 2, n)*mod_pow(b, k / 2, n) % n; 58 } 59 if (x * 2 > n) x = n - x; 60 } 61 return -1; 62 } 63 64 int main() { 65 ios::sync_with_stdio(false), cin.tie(0); 66 int T; 67 cin >> T; 68 rep(cas, 1, T + 1) { 69 ll a, p; 70 cin >> a >> p; 71 a = (a%p + p) % p; 72 cout << "Scenario #" << cas << ":" << endl; 73 cout << mod_sqr(a, p) << endl << endl; 74 } 75 return 0; 76 }