【TOJ1132】Square Root

2 篇文章 0 订阅
2 篇文章 0 订阅

Description

The number x is called a square root of a modulo n (root(a,n)) if x*x = a (mod n). Write the program to find the square root of number a by given modulo n.

Description

题意就是让你求二次剩余嘛。
这个时候就轮到Cipolla出马了。
用Cipolla轻松搞定。

Code

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define fo(i,a,b) for(i=a;i<=b;i++)
using namespace std;
typedef long long ll;
ll i,j,k,l,t,m,ans,w,a;
ll n,p;
struct CN{
    ll x,y;
    CN friend operator *(CN x,CN y){
        CN z;
        z.x=(x.x*y.x%p+x.y*y.y%p*w%p)%p;
        z.y=(x.x*y.y%p+x.y*y.x%p)%p;
        return z;    
    }
}u,v;
ll qsm(ll x,ll y){
    ll z=1;
    while(y){
        if(y&1)z=z*x%p;
        x=x*x%p;
        y/=2;
    }
    return z;
}
CN Cqsm(CN x,ll y){
    CN z;z.x=1,z.y=0;
    while(y){
        if(y&1)z=z*x;
        x=x*x;
        y/=2;
    }
    return z;
}
int main(){
    for(scanf("%lld",&t);t;t--){
        scanf("%lld%lld",&n,&p);
        n%=p;
        if(p==2){
            printf("1\n");
            continue;
        }
        if(qsm(n,(p-1)/2)==p-1){
            printf("No root\n"); 
            continue;   
        }
        while(1){
            a=rand()%p;
            w=(a*a-n+p)%p;
            if(qsm(w,(p-1)/2)==p-1)break;
        }
        u.x=a,u.y=1;
        u=Cqsm(u,(p+1)/2);
        ll yi=u.x,er=p-u.x;
        if(yi>er)swap(yi,er);
        if(yi==er){
            printf("%lld\n",yi);
        }
        else{
            printf("%lld %lld\n",yi,er);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值