Timus1132(二次剩余方程求解)

直接从ACdreamers神的博客里搬过来的(看原创请戳这里)

题意:就是给出方程,p为素数,求在区间内的解。

 

这个思路很简单,详见:http://algo.ftiasch.com/tag/number-theory/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>

using namespace std;
typedef long long LL;

LL quick_mod(LL a,LL b,LL m)
{
    LL ans=1;
    a%=m;
    while(b)
    {
        if(b&1)
        {
            ans=ans*a%m;
            b--;
        }
        b>>=1;
        a=a*a%m;
    }
    return ans;
}

struct T
{
    LL p,d;
};

LL w;

//二次域乘法
T multi_er(T a,T b,LL m)
{
    T ans;
    ans.p=(a.p*b.p%m+a.d*b.d%m*w%m)%m;
    ans.d=(a.p*b.d%m+a.d*b.p%m)%m;
    return ans;
}

//二次域上快速幂
T power(T a,LL b,LL m)
{
    T ans;
    ans.p=1;
    ans.d=0;
    while(b)
    {
        if(b&1)
        {
            ans=multi_er(ans,a,m);
            b--;
        }
        b>>=1;
        a=multi_er(a,a,m);
    }
    return ans;
}

//求勒让德符号
LL Legendre(LL a,LL p)
{
    return quick_mod(a,(p-1)>>1,p);
}

LL mod(LL a,LL m)
{
    a%=m;
    if(a<0) a+=m;
    return a;
}

LL Solve(LL n,LL p)
{
    if(p==2) return 1;
    if (Legendre(n,p)+1==p)
        return -1;
    LL a=-1,t;
    while(true)
    {
        a=rand()%p;
        t=a*a-n;
        w=mod(t,p);
        if(Legendre(w,p)+1==p) break;
    }
    T tmp;
    tmp.p=a;
    tmp.d=1;
    T ans=power(tmp,(p+1)>>1,p);
    return ans.p;
}

int main()
{
    int t,p,n,a,b;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&p);
        n%=p;
        a=Solve(n,p);
        if(a==-1)
        {
            puts("No root");
            continue;
        }
        b=p-a;
        if(a>b) swap(a,b);
        if(a==b)
            printf("%d\n",a);
        else
            printf("%d %d\n",a,b);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值