POJ 2417 BSGS裸题

题目描述:

Given a prime P, 2 <= P < 231, an integer B, 2 <= B < P, and an integer N, 1 <= N < P, compute the discrete logarithm of N, base B, modulo P. That is, find an integer L such that
    B^L == N (mod P)

Input

Read several lines of input, each containing P,B,N separated by a space.


Output

For each line print the logarithm on a separate line. If there are several, print the smallest; if there is none, print "no solution".


Sample Input

5 2 1
5 2 2
5 2 3
5 2 4
5 3 1
5 3 2
5 3 3
5 3 4
5 4 1
5 4 2
5 4 3
5 4 4
12345701 2 1111111
1111111121 65537 1111111111


Sample Output

0
1
3
2
0
3
1
2
0
no solution
no solution
1
9584351
462803587


题意:给定 P,B,N三个整数,求解L的值,简单的大步小步(BSGS)裸题。

求解思路:首先,从枚举,将得到的的值存入hash表;
  然后,从枚举,计算,查表,如果有值与之相等,则当时得到的是最小值。

 

下面先来讲解一下bsgs算法:

       bsgs算法,又称大小步算法(某大神称拔山盖世算法)。

主要用来解决   A^x=B(mod C)(C是质数),都是整数,已知A、B、C求x。

具体步骤如下:

先把x=i*m-j,其中m=ceil(sqrt(C)),(ceil是向上取整)。

这样原式就变为A^(i*m-j)=B(mod C),

再变为A^j×B=A^(m*i) (mod C)。

枚举j(范围0-m),将A^j×B存入hash表

枚举i(范围1-m),从hash表中寻找第一个满足A^j×B=A^(m*i) (mod C)。

此时x=i*m-j即为所求。

在网上看到的其他题解大多用的是x=i*m+j,也可以做,只是会牵扯的求逆元,所以比较麻烦。使x=i*m-j就可以轻松避免这个问题了。

那么肯定有人会有疑问为何只计算到m=ceil(sqrt(C))就可以确定答案呢?

x=i*m-j  也就是x 的最大值不会超过p,那超过p的怎么办 ?

有一个公式  a^(k mod p-1)=a^k (mod p)     这个公式的推导需要用到费马小定理

k mod p-1可以看做 k-m(p-1)  ,原式可化成  a^k/(a^(p-1))^m=a^k (mod p)   

根据费马小定理 a^(p-1)=1  (mod p) 其中p为质数 ,a,p 互质,可得a^k/1^m=a^k  (mod p)   a^k=a^k (mod p) 得证。

本题代码读者可在理解的情况下自行解决   hahahaha~

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值