poj 1808 Quadratic Residues


平方剩余的问题,题目只要判断是否存在平方剩余就行啦。。

int solve(LL a, LL p) {  //判断x*x (-=) a(mod p) 是否存在
    LL res = pow_mod(a , (p - 1) >> 1, p);  
    if (res == p - 1)  
        return false;  
    return ture;  
}  

如果要求最小的解x,的话就要复杂一些

int modsqr(int a,int n)
{
    int b,k,i,x;
    if(n == 2) return a % n;
    if(pow_mod(a,(n-1)/2,n) == 1)
    {
        if(n%4 == 3)   x=pow_mod(a,(n+1)/4,n);
        else
        {
            for(b=1;pow_mod(b,(n-1)/2,n) == 1 ; b++)

            i=(n - 1)/2;
            k=0;
            do
            {
                i/=2;
                k/=2;
                if( (pow_mod(a,i,n)* (ll)pow_mod(b,k,n)+1)%n == 0 )
                {
                    k+=(n-1)/2;
                }
            }
            while(i%2 == 0);

            x=(pow_mod(a,(i+1)/2,n)*(ll)pow_mod(b,k/2,n)) % n;
        }
        if(x*2 > n) x=n-x;
        return x;
    }
    return -1;
}

不知道 为什么我用这个打答案错误。。但是上面的代码输出的x是正确的。。所以还是用了上面那个。

AC代码:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
typedef long long ll;
ll pow_mod(ll a,ll b,ll c)
{
    ll res=1;
    while(b)
    {
        if(b&1) res=res*a%c;
        a=a*a%c;
        b>>=1;
    }
    return res;
}

int main()
{
    int a,n,ant=1,ans,t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&a,&n);
        ans=pow_mod(a,(n-1)/2,n);
        printf("Scenario #%d:\n",ant++);
        if(ans == n-1) printf("-1\n");
        else printf("1\n");
        printf("\n");
    }
    return 0;
}
路途。。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值