2019牛客暑期多校9B:Quadratic equation【二次剩余模板】

题目:

2019牛客暑假多校9B:Quadratic equation

题意:

求得x,y,使得(x + y)= b (mod p),x*y = c (mod p)

分析:

先令:

b' = x+yc' =x*y

根据同余式的性质得到(t1,t2为整数):

b'=b+p*t_1c'=c+p*t_2

根据韦达定理,x,y的值等价下列于方程的两个根:

x^2-b'x+c'=0

再根据求根公式,令:

\Delta =\sqrt{b'^2-4c'}

那么代入b' = b+pt1,c' = c+pt2可以得到:

\dpi{150} \Delta ^2\equiv b^2-4c~(mod~p)

题目要求x,y为整数,那么\Delta的值必然为整数,转化成求同余方程 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值