定义:
对于方程 为p的二次剩余 , x为该二次同余方程的解
就如字面意思一样 , n就是一个二次项%p后的剩余
应用:
求 若n为p的二次剩余 , 那么很明显
简单的说 , 如果该二次同余方程有解,那么n可以在模p的意义下开根号。
二次同余方程求解(%奇素数):
勒让德符号(legender symbol)
表示n是否为p的二次剩余 , 1和-1表示是与否 , 0表示n为0的情况
定理 1:
也就是说知道了n和p相当于知道了这个符号的值
定理 2:
若找到一个a使
则 为 的解
定理3可以证明随意找一个a就有50%的几率符合要求
定理 3:
对于二次同余方程 有 个n使此方程有解
本篇博客不进行定理的证明 , 因为过程打出来会过于冗长 , 很多初学者都会对这种一大段的证明心生畏惧 .
代码实现:
#include <iostream>
#include <ctime>
using namespace std;
typedef long long LL;
#define random(a,b) (rand()%(b-a+1)+a)
LL quick_mod(LL a, LL b, LL c)
{ LL ans = 1;
while (b) { if (b % 2 == 1)ans = (ans*a) % c; b /= 2; a = (a*a) % c;
}return ans;
}
LL p;
LL w;//二次域的D值
bool ok;//是否有解
struct QuadraticField//二次域
{
LL x, y;
QuadraticField operator*(QuadraticField T)//二次域乘法重载
{
QuadraticField ans;
ans.x = (this->x*T.x%p + this->y*T.y%p*w%p) % p;
ans.y = (this->x*T.y%p + this->y*T.x%p) % p;
return ans;
}
QuadraticField operator^(LL b)//二次域快速幂
{
QuadraticField ans;
QuadraticField a = *this;
ans.x = 1;
ans.y = 0;
while (b)
{
if (b & 1)
{
ans = ans*a;
b--;
}
b /= 2;
a = a*a;
}
return ans;
}
};
LL Legender(LL a)//求勒让德符号
{
LL ans=quick_mod(a, (p - 1) / 2, p);
if (ans + 1 == p)//如果ans的值为-1,%p之后会变成p-1。
return -1;
else
return ans;
}
LL Getw(LL n, LL a)//根据随机出来a的值确定对应w的值
{
return ((a*a - n) % p + p) % p;//防爆处理
}
LL Solve(LL n)
{
LL a;
if (p == 2)//当p为2的时候,n只会是0或1,然后0和1就是对应的解
return n;
if (Legender(n) == -1)//无解
ok = false;
srand((unsigned)time(NULL));
while (1)//随机a的值直到有解
{
a = random(0, p - 1);
w = Getw(n, a);
if (Legender(w) == -1)
break;
}
QuadraticField ans,res;
res.x = a;
res.y = 1;//res的值就是a+根号w
ans = res ^ ((p + 1) / 2);
return ans.x;
}
int main()
{
LL n,ans1,ans2;
while (scanf("%lld%lld",&n,&p)!=EOF)
{
ok = true;
n %= p;
ans1 = Solve(n);
ans2 = p - ans1;//一组解的和是p
if (!ok)
{
printf("No root\n");
continue;
}
if (ans1 == ans2)
printf("%lld\n", ans1);
else
printf("%lld %lld\n", ans1, ans2);
}
}