二次剩余求x^2=a(mod p) 的x模板

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int p=1e9+7;
struct hh{
	ll x,y;
	hh(){};
	hh(ll _x,ll _y){
		x=_x;y=_y;
	}
};
ll w;
hh mul(hh a,hh b,ll p){
	hh ans;
	ans.x=(a.x*b.x%p+a.y*b.y%p*w%p)%p;
	ans.y=(a.x*b.y%p+a.y*b.x%p)%p;
	return ans;
}
hh quick1(hh a,ll b,ll p){
	hh ans=hh(1,0);
	while(b){
		if(b&1) ans=mul(ans,a,p);
		a=mul(a,a,p);
		b>>=1;
	}
	return ans;
}
ll quick2(ll a,ll b,ll p){
	ll ans=1;
	while(b){
		if(b&1) ans=(ans*a)%p;
		b>>=1;
		a=(a*a)%p;
	}
	return ans;
}
ll solve(ll a,ll p){//求解 x^2=a(mod p) 的x的值 
	a%=p;//注意这句话 
	if(a==0) return 0;//注意这句话 
	if(p==2) return a;
	if(quick2(a,(p-1)/2,p)==p-1) return -1;
	ll b,t;
	while(1){
		b=rand()%p;
		t=b*b-a;
		w=(t%p+p)%p;
		if(quick2(w,(p-1)/2,p)==p-1) break;
	}
	hh ans=hh(b,1);
	ans=quick1(ans,(p+1)/2,p);
	return ans.x;
}
int main(){
	return 0;
} 
发布了195 篇原创文章 · 获赞 27 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/lgz0921/article/details/99651768