【bzoj2480】Mod 扩展大步小步

http://blog.miskcoo.com/2015/05/discrete-logarithm-problem 

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#define Rep(i, x, y) for (int i = x; i <= y; i ++)
#define Dwn(i, x, y) for (int i = x; i >= y; i --)
#define RepE(i, x) for(int i = pos[x]; i; i = g[i].nex)
using namespace std;
typedef long long LL;
map<LL, int> m1;
int a, b, p, ans;
int Pow(LL x, int y, int m) {
	LL z = 1;
	while (y) {
		if (y & 1) (z *= x) %= m;
		y >>= 1, (x *= x) %= m;
	}
	return z;
}
LL gcd(LL x, LL y) { return !y ? x : gcd(y, x % y); }
int Baby_step_gaint_step() {
	a %= p, b %= p, m1.clear();
	int k0 = 0; LL t = 1, k;
	while ((k = gcd(a, p)) > 1) {
		if (b % k != 0) return -1;
		p /= k, b /= k, t = (t * a / k) % p; k0 ++;
		if (b == t) return k0;
	}
	int u = sqrt(p) + 1;
	LL x = 1, z, num, z0;
	Rep(i, 1, u) { LL p1 = x * b % p;
		m1[p1] = i, x = a * x % p;
	}
	z = x * t % p, z0 = x, num = u;
	Rep(i, 1, u) {
		if (m1[z]) return num - m1[z] + k0 + 1;
		z = z * z0 % p, num += u;
	}
	return -1;
}
int main()
{
	while (scanf ("%d%d%d", &a, &p, &b) != EOF) {
		if (!a && !b && !p) break ;
		ans = 0; LL x = 1;
		while (x != b && ans <= 32) x = x * a % p, ans ++;
		if (x != b) ans = Baby_step_gaint_step();
		if (ans == -1) 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、付费专栏及课程。

余额充值