【BZOJ2242】计算器

题解:
1.快速幂
2.exgcd/逆元
3.bsgs模板题

//by sdfzchy
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
#include<cmath>
using namespace std;
typedef long long LL;
const int inf=(1<<30);
int n,m;
inline int in()
{
    char ch=getchar();
    int f=1,tmp=0;
    while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') {tmp=(tmp<<1)+(tmp<<3)+(ch-'0');ch=getchar();}
    return tmp*f;
}
LL x,y,p,k;
LL ksm(LL a,LL b)
{
    LL ret=1;
    while(b)
    {
        if(b&1) ret=ret*a%p;
        a=a*a%p;
        b>>=1;  
    }   
    return ret;
}

LL inv(LL a)
{
    if(a%p==0) return -1;
    return ksm(a,p-2);
}
LL ans;
LL bsgs(LL x,LL y)
{
    map<LL,LL> ma;
    x%=p,y%=p;
    if(!x&&!y) return 1;
    if(y==1) return 0;
    if(x%p==0) return -1;
    m=sqrt(p+0.5);
    LL o=y%p;
    for(int i=0;i<m;i++)
    {
        if(!ma.count(o)) ma[o]=i;
        o=o*x%p;
    }
    LL oo=ksm(x,m); o=1;
    for(int i=1;(i-1)*(i-1)<=p;i++)
    {
        o=o*oo%p;
        if(ma.count(o)) return ((i*m-ma[o])%p+p)%p;
    }
    return -1;
} 

int main()
{
    int T=in();k=in();
    while(T--)
    {
        ans=0;
        scanf("%lld%lld%lld",&x,&y,&p);
        if(k==1) ans=ksm(x%p,y); 
        else if(k==2)
        {
            ans=inv(x);
            if(ans!=-1) ans=ans*y%p;
        }
        else ans=bsgs(x,y);
        if(ans==-1) puts("Orz, I cannot find x!");
        else printf("%lld\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值