POJ 2417 Discrete Logging (Baby Step Giant Step算法)

题目:LINK 

求 a^x = b (mod n) (n是质数) O(sqrt(n)) 
原理: m = ceil(sqrt(n));  

令x = i*m + j (0<= i < m, 0<= j < m); 

则a^x = (a^m)^i * a^j= b(mod n); 

枚举i(O(n)) 之后检测是否存在a^j 使得(a^m)^i * a^j = b(mod n)成立,为了检测时复杂度低一些可以建立哈希表(a^j, j) ,或者二分也可以.对于已知(a^m)^i 和b 

求a^j值, 可以利用扩展欧几里得解出,或者利用逆元,式子可以写为a^j = b*(a^(-m))^i (mod n) 先求得a^(-m)= (a^(-1))^m = (a^(n-2))^m (mod n)//费马小定理;
如果n是合数,在求a^j的值时会出现问题.

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<cmath>
#include<queue>
#include<map>
#include<set>
using namespace std;
#define INF 1000000000
typedef __int64 LL;
#define MOD 76543
int hh[MOD], tot;
LL p, b, l;
struct node
{
    int hs, id, next;
}dd[MOD];
void init()
{
    memset(hh, -1, sizeof(hh));
    tot = 1;
}
void insert(int x, int y )
{
    int k = x %MOD;
    dd[tot].hs = x; dd[tot].id = y; dd[tot].next = hh[k];
    hh[k] = tot ++;
}
int find(int x)
{
    int k = x % MOD;
    for(int i = hh[k]; i != -1; i= dd[i].next) {
        if(dd[i].hs == x) return dd[i].id;
    }
    return -1;
}
LL pow_(LL x, LL y, LL mod)
{
    LL ret = 1;
    while(y) {
        if(y&1) {
            ret *= x; ret %= mod;
        }
        x *= x; x %= mod;
        y >>= 1;
    }
    return ret;
}
int BSGS(int a, int b, int n)
{
    init();
    if(b == 1) {
        return 0;
    }
    int m = (int)ceil(sqrt(1.0 * n));
    LL p = 1, t = 1;
    for(int i = 0; i < m; i++, p = p * a % n) insert(p, i);// p相同也可以先后存入,因为要的是取模后i最小的
    LL bn = pow_(pow_(a, n-2, n), m, n); // to get a^(-m)
    LL tmp = b;
    int w ;
    for(int i = 0; i < m; i++, t = t * p % n) {
        if((w = find(tmp)) != -1) return i*m + w;
        tmp = tmp * bn % n;
    }
    return -1;
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
	while(scanf("%I64d%I64d%I64d", &p, &b, &l) != EOF) {
        int ans = BSGS(b, l, p);
        if(ans < 0) puts("no solution");
        else printf("%d\n", ans);
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值