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.
Description
题意就是让你求二次剩余嘛。
这个时候就轮到Cipolla出马了。
用Cipolla轻松搞定。
Code
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define fo(i,a,b) for(i=a;i<=b;i++)
using namespace std;
typedef long long ll;
ll i,j,k,l,t,m,ans,w,a;
ll n,p;
struct CN{
ll x,y;
CN friend operator *(CN x,CN y){
CN z;
z.x=(x.x*y.x%p+x.y*y.y%p*w%p)%p;
z.y=(x.x*y.y%p+x.y*y.x%p)%p;
return z;
}
}u,v;
ll qsm(ll x,ll y){
ll z=1;
while(y){
if(y&1)z=z*x%p;
x=x*x%p;
y/=2;
}
return z;
}
CN Cqsm(CN x,ll y){
CN z;z.x=1,z.y=0;
while(y){
if(y&1)z=z*x;
x=x*x;
y/=2;
}
return z;
}
int main(){
for(scanf("%lld",&t);t;t--){
scanf("%lld%lld",&n,&p);
n%=p;
if(p==2){
printf("1\n");
continue;
}
if(qsm(n,(p-1)/2)==p-1){
printf("No root\n");
continue;
}
while(1){
a=rand()%p;
w=(a*a-n+p)%p;
if(qsm(w,(p-1)/2)==p-1)break;
}
u.x=a,u.y=1;
u=Cqsm(u,(p+1)/2);
ll yi=u.x,er=p-u.x;
if(yi>er)swap(yi,er);
if(yi==er){
printf("%lld\n",yi);
}
else{
printf("%lld %lld\n",yi,er);
}
}
}