模平方根
对于给定的奇质数 p p p,和正整数 x x x,存在 y y y满足 1 ≤ y ≤ p − 1 1\leq y\leq p-1 1≤y≤p−1,且 x ≡ y 2 ( m o d p ) x\equiv y^2\ (mod\ \ p) x≡y2 (mod p),则称y为x的模平方根
对于正整数m,若同余式 x 2 ≡ a ( m o d m ) x^2\equiv a\ (mod\ \ m) x2≡a (mod m)有解,则称a为模m的平方剩余,否则称为模m平方非剩余。
是否存在模平方根
根据欧拉判别条件:
设p是奇质数,对于
x
2
≡
a
(
m
o
d
p
)
x^2\equiv a\ (mod\ \ p)
x2≡a (mod p)
a
a
a是模
p
p
p的平方剩余的充要条件是
a
p
−
1
2
%
p
=
1
a^{\frac{p-1}{2}}\%p=1
a2p−1%p=1
a
a
a是模
p
p
p的平方非剩余的充要条件是
a
p
−
1
2
%
p
=
−
1
a^{\frac{p-1}{2}}\%p=-1
a2p−1%p=−1
给定
a
,
n
a,n
a,n(n是质数),求
x
2
≡
a
(
m
o
d
n
)
x^2\equiv a(mod\ \ n)
x2≡a(mod n)的最小整数解
x
x
x
代码复杂度
O
(
l
o
g
2
(
n
)
)
O(log^2(n))
O(log2(n))
#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <ctime>
using namespace std;
#define me(x,y) memset(x,y,sizeof x)
#define MIN(x,y) (x) < (y) ? (x) : (y)
#define MAX(x,y) (x) > (y) ? (x) : (y)
#define SGN(x) ((x)>0?1:((x)<0?-1:0))
#define ABS(x) ((x)>0?(x):-(x))
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e5+10;
const ll INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int eps = 1e-8;
ll qpow(ll a,ll b,ll p){
ll ans=1;
while(b){
if(b&1) ans=ans*a%p;
a=a*a%p;
b>>=1;
}
return ans;
}
int modsqr(int a,int n){
int b,k,i,x;
if(n==2) return a%n;
if(qpow(a,(n-1)/2,n) == 1){
if(n%4 == 3){
x=qpow(a,(n+1)/4,n);
}
else{
for(b=1; qpow(b,(n-1)/2,n) == 1; b++);
i = (n-1)/2;
k=0;
while(i%2==0){
i /= 2,k /= 2;
if((qpow(a,i,n)*qpow(b,k,n)+1)%n == 0) k += (n-1)/2;
}
x = qpow(a,(i+1)/2,n)*qpow(b,k/2,n)%n;
}
if(x*2 > n) x = n-x;
return x;
}
return -1;
}
int main(){
int a,n;
while(cin>>a>>n){
cout<<modsqr(a,n)<<endl;
}
return 0;
}