您的位置:首页 > 其它

BZOJ 2242: [SDOI2011]计算器 [快速幂 BSGS]

2017-03-31 18:21 393 查看

2242: [SDOI2011]计算器

题意:求\(a^b \mod p,\ ax \equiv b \mod p,\ a^x \equiv b \mod p\),p是质数

这种裸题我竟然WA了好多次

第三个注意判断a和b整除p的情况

#pragma GCC optimize ("O2")
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
using namespace std;
typedef long long ll;
#define fir first
#define sec second
inline int read() {
char c=getchar(); int x=0, f=1;
while(c<'0' || c>'9') {if(c=='-')f=-1; c=getchar();}
while(c>='0' && c<='9') {x=x*10+c-'0'; c=getchar();}
return x*f;
}

int a, b, p;
ll Pow(ll a, int b, int p) {
a%=p; ll ans=1;
for(; b; b>>=1, a=a*a%p)
if(b&1) ans=ans*a%p;
return ans;
}
ll inv(int a, int p) {
if(a%p==0) return -1;
return Pow(a, p-2, p);
}
map<int, int> ma;
ll ind(int a, int b, int p) {
a%=p; b%=p;
ma.clear();
ll e=1; int m=sqrt(p)+0.5;
for(int i=0; i<m; i++) {
if(!ma.count(e)) ma[e]=i;
e=e*a%p;
}
e=Pow(e, p-2, p);
for(int i=0; i<m; i++) {
if(ma.count(b)) return i*m + ma[b];
b=b*e%p;
}
return -1;
}
int main() {
//freopen("in","r",stdin);
freopen("calc.in","r",stdin);
freopen("calc.out","w",stdout);
int T=read(), type=read();
while(T--) {
a=read(); b=read(); p=read();
ll ans;
if(type==1) ans=Pow(a, b, p);
else if(type==2) {ans=inv(a, p);if(ans!=-1) ans=ans*b%p;}
else ans=ind(a, b, p);
if(ans==-1) puts("Orz, I cannot find x!");
else printf("%lld\n", ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: