码迷,mamicode.com
首页 > 其他好文 > 详细

Timus 1132 Square Root(二次剩余 解法2)

时间:2018-04-28 23:42:22      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:size   include   for   timus   open   while   else   root   names   

不理解,背板子

#include<cstdio>

using namespace std;

int Pow(int a,int b,int p)
{
    int res=1;
    for(;b;a=1LL*a*a%p,b>>=1)
        if(b&1) res=1LL*a*res%p;
    return res;
}

bool Legendre(int a,int p)
{
    return Pow(a,p-1>>1,p)==1;
}

void modsqr(int a,int p)
{
    int x;
    int i,k,b;
    if(p==2) x=a%p;
    else if(p%4==3) x=Pow(a,p+1>>2,p);
    else
    {
        for(b=1;Legendre(b,p);++b);
        i=p-1>>1;
        k=0;
        do
        {
            i>>=1;
            k>>=1;
            if(!((1LL*Pow(a,i,p)*Pow(b,k,p)+1)%p)) k+=p-1>>1;
        }while(!(i&1));
        x=1LL*Pow(a,i+1>>1,p)*Pow(b,k>>1,p)%p;
    }
    if(p-x<x) x=p-x;
    if(x==p-x) printf("%d\n",x);
    else printf("%d %d\n",x,p-x);
}        

int main()
{
    freopen("data.txt","r",stdin);
    freopen("aa.txt","w",stdout);
    int T;
    scanf("%d",&T);
    int a,n;
    while(T--)
    {
        scanf("%d%d",&a,&n);
        a%=n;
        if(!Legendre(a,n)) 
        {
            puts("No root");
            continue;
        }
        modsqr(a,n);
    }
    return 0;
}

 

Timus 1132 Square Root(二次剩余 解法2)

标签:size   include   for   timus   open   while   else   root   names   

原文地址:https://www.cnblogs.com/TheRoadToTheGold/p/8969735.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!