bzoj 3239 poj 2417 BSGS

本文介绍了一种解决离散对数问题的有效算法——Baby Step Giant Step (BSGS)算法。通过预处理并使用哈希表存储特定值,在O(√c)的时间复杂度内寻找解。该算法适用于求解形如a^x ≡ b (mod c)的问题。

BSGS算法,预处理出ϕ(c)内的a的幂,每次再一块一块的往上找,转移时将b乘上逆元,哈希表里O(1)查询即可

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<map>
#define LL long long
long long a,b,c,m;
bool bo=0;
std::map<long long,int> pp;
std::map<long long,bool> vis;
LL exgcd(LL o,LL p,LL &x,LL &y){
    if(p==0){
        x=1;y=0;
        return o;
    }
    LL gcd=exgcd(p,o%p,x,y);
    LL t=x;
    x=y;
    y=t-(o/p)*x;
    return gcd;
}
int main(){
    while(scanf("%lld%lld%lld",&c,&a,&b)==3){
        pp.clear(); vis.clear(); bo=0;
        if(a%c==0){printf("no solution\n");continue;}
        m=(LL)ceil(sqrt((double)c));
        LL now=1;
        pp[now]=0; vis[now]=1;
        for(int i=1;i<m;i++){
            now=(now*a)%c;
            if(!vis[now]){vis[now]=1;pp[now]=i;}
        }
        now=(now*a)%c;
        LL x,y;
        LL d=exgcd(now,c,x,y);
        x=(x%c+c)%c;
        for(int i=0;i<=m;i++){
            if(vis[b]){
                printf("%lld\n",i*m+pp[b]);
                bo=1; break;
            }
            b=(b*x)%c;
        }
        if(bo==1)continue;
        printf("no solution\n");
    }
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值