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

本文深入探讨了模数运算在计算机科学中的应用,特别是快速幂算法的实现及其在解决特定数学问题上的效率。通过定义结构体和自定义乘法、快速幂函数,文章详细解释了如何求解形如x^2=a(modp)的问题,为读者提供了理解和实现这类算法的基础。
#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;
} 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心脏dance

如果解决了您的疑惑,谢谢打赏呦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值