跳到正文

个人记录

二次剩余

MoCaRabbit约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

P5491

随机找到一个 aa 使得 a2−na^2-n 是非二次剩余。

定义 i2=a2−ni^2=a^2-n。

可以证明 ip=−ii^p=-i。

可以证明 (A+B)p=Ap+Bp(A+B)^p=A^p+B^p(二项式展开后直接模 pp)。

于是可以推出 (a+i)p+1=n(a+i)^{p+1}=n。

于是 nn 的二次剩余就是 (a+i)p+12(a+i)^{\frac{p+1}{2}}。

可以证明,这一定是整数。

写个复数类就行了。

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,p;
int dt;
struct fcp{
	int x,y;
	inline fcp(int _x=0,int _y=0){x=_x,y=_y;}
};
inline fcp operator * (fcp x,fcp y){return fcp((x.x*y.x%p+dt*x.y%p*y.y%p)%p,(x.x*y.y%p+x.y*y.x%p)%p);}
inline fcp operator + (fcp x,fcp y){return fcp((x.x+y.x)%p,(x.y+y.y)%p);}
inline int power(int x,int y){
	if(y==0) return 1;
	int tot=power(x,y>>1);
	if(y&1) return tot*tot%p*x%p;
	else return tot*tot%p;
}
inline fcp fpower(fcp x,int y){
	if(y==0) return fcp(1,0);
	fcp tot=fpower(x,y>>1);
	if(y&1) return tot*tot*x;
	else return tot*tot;
}
inline void solve(){
	cin>>n>>p;
	n%=p;
	if(power(n,(p-1)>>1)==p-1){
		cout<<"Hola!\n";
		return;
	}
	int a=(int)(rand())*rand()%p;
	while(power((a*a%p-n+p)%p,(p-1)>>1)==1) a=(int)(rand())*rand()%p;
	dt=(a*a%p-n+p)%p;
	int x=fpower(fcp(a,1),(p+1)>>1).x;
	int y=(p-x)%p;
	if(x>y) swap(x,y);
	if(x!=y) cout<<x<<" "<<y<<"\n";
	else cout<<x<<"\n";
}
signed main() {
	int t;
	cin>>t;
	while(t--) solve();
	return 0;
}
原文