题目:
2019牛客暑假多校9B:Quadratic equation
题意:
求得x,y,使得(x + y)= b (mod p),x*y = c (mod p)
分析:
先令:
,
根据同余式的性质得到(t1,t2为整数):
,
根据韦达定理,x,y的值等价下列于方程的两个根:
再根据求根公式,令:
那么代入b' = b+pt1,c' = c+pt2可以得到:
题目要求x,y为整数,那么的值必然为整数,转化成求同余方程 x^2 = b^2-4c (mod p) 的整数解,这就是二次剩余的模板了
这里有一篇二次剩余的文章:二次剩余Cipolla算法学习小记
这里存个板子,下面模板只能在p为奇素数时适用
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int p = 1e9+7;
LL w,b,c;
struct Inumber{ //表示复数a+bi (i=sqrt(w))
LL a,b;
};
inline Inumber operator*(Inumber x,Inumber y){ //复数乘法
return (Inumber){(x.a*y.a+x.b*y.b%p*w)%p,(x.a*y.b+x.b*y.a)%p};
}
LL qpow(LL a,LL x,LL mod){
LL res = 1;
while(x){
if(x&1) res = res*a%mod;
a = a*a%mod;
x >>= 1;
}
return res;
}
Inumber iqpow(Inumber A,LL x){ //复数快速幂
Inumber res = (Inumber){1,0};
while(x){
if(x&1) res = res*A;
A = A*A;
x >>= 1;
}
return res;
}
int Legendre(LL a,LL p){
if(qpow(a,(p-1)>>1,p)==1) return 1;
else return -1;
}
LL solve(LL n,LL mod){ //求解x^2 = n (mod p)
LL a;
if(n == 0) return 0;
if(Legendre(n,mod) == -1) return -1;
while(true){
a = rand()%mod;
w = (a*a%mod-n+mod)%mod;
if(Legendre(w,mod) == -1) break;
}
Inumber ans = iqpow((Inumber){a,1},(p+1)>>1);
return ans.a%mod;
}
int main(){
srand(time(0));
int Case; cin >> Case;
LL inv2 = qpow(2,p-2,p);
while(Case--){
cin >> b >> c;
LL x = solve(((b*b-4*c)%p+p)%p,p);
if(x == -1) puts("-1 -1");
else{
LL ansx = ((b-x)%p+p)%p*inv2%p;
LL ansy = (b+x)%p*inv2%p;
cout << min(ansx,ansy) << " " << max(ansx,ansy) << '\n';
}
}
return 0;
}