模平方根/平方剩余

模平方根

对于给定的奇质数 p p p,和正整数 x x x,存在 y y y满足 1 ≤ y ≤ p − 1 1\leq y\leq p-1 1yp1,且 x ≡ y 2   ( m o d    p ) x\equiv y^2\ (mod\ \ p) xy2 (mod  p),则称y为x的模平方根

对于正整数m,若同余式 x 2 ≡ a   ( m o d    m ) x^2\equiv a\ (mod\ \ m) x2a (mod  m)有解,则称a为模m的平方剩余,否则称为模m平方非剩余。

是否存在模平方根
根据欧拉判别条件:
设p是奇质数,对于 x 2 ≡ a   ( m o d    p ) x^2\equiv a\ (mod\ \ p) x2a (mod  p)
a a a是模 p p p的平方剩余的充要条件是 a p − 1 2 % p = 1 a^{\frac{p-1}{2}}\%p=1 a2p1%p=1
a a a是模 p p p的平方非剩余的充要条件是 a p − 1 2 % p = − 1 a^{\frac{p-1}{2}}\%p=-1 a2p1%p=1

给定 a , n a,n a,n(n是质数),求 x 2 ≡ a ( m o d    n ) x^2\equiv a(mod\ \ n) x2a(mod  n)的最小整数解 x x x
代码复杂度 O ( l o g 2 ( n ) ) O(log^2(n)) O(log2(n))

#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <ctime>
using namespace std;
#define me(x,y) memset(x,y,sizeof x)
#define MIN(x,y) (x) < (y) ? (x) : (y)
#define MAX(x,y) (x) > (y) ? (x) : (y)
#define SGN(x) ((x)>0?1:((x)<0?-1:0))
#define ABS(x) ((x)>0?(x):-(x))

typedef long long ll;
typedef unsigned long long ull;

const int maxn = 1e5+10;
const ll INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int eps = 1e-8;

ll qpow(ll a,ll b,ll p){
    ll ans=1;
    while(b){
        if(b&1) ans=ans*a%p;
        a=a*a%p;
        b>>=1;
    }
    return ans;
}
int modsqr(int a,int n){
    int b,k,i,x;
    if(n==2) return a%n;
    if(qpow(a,(n-1)/2,n) == 1){
        if(n%4 == 3){
            x=qpow(a,(n+1)/4,n);
        }
        else{
            for(b=1; qpow(b,(n-1)/2,n) == 1; b++);
            i = (n-1)/2;
            k=0;
            while(i%2==0){
                i /= 2,k /= 2;
                if((qpow(a,i,n)*qpow(b,k,n)+1)%n == 0) k += (n-1)/2;
            }
            x = qpow(a,(i+1)/2,n)*qpow(b,k/2,n)%n;
        }
        if(x*2 > n) x = n-x;
        return x;
    }
    return -1;
}

int main(){
    int a,n;
    while(cin>>a>>n){
        cout<<modsqr(a,n)<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值