一叶落寞,万物失色。
Description
BL == N (mod P)
Input
Output
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
Hint
The solution to this problem requires a well known result in number theory that is probably expected of you for Putnam but not ACM competitions. It is Fermat's theorem that states
题意:给定
a,b,p
,求最小的非负整数
x
,满足
ax≡b(modp)
令
x=im−j
,
m=⌈p√⌉
,则
aim−j≡b(modp)
移项,得
(am)i≡baj(modp)
首先,从
0−m
枚举
j
,将得到的
baj
的值存入hash表;
然后,从
1−m
枚举
i
,计算
(am)i
,查表,如果有值与之相等,则当时得到的
im−j
是最小值。
bsgs算法
bsgs算法,又称大小步算法(某大神称拔山盖世算法)。
主要用来解决 A^x=B(mod C)(C是质数),都是整数,已知A、B、C求x。(poj 2417 Discrete Logging)
具体步骤如下:
先把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) 得证。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<cmath>
using namespace std;
long long a,b,c,m,f[10000000];
map<long long,int> mp;
long long qsm(long long x)
{
long long sum=1; long long aa=a;
while (x>0)
{
if (x&1)
sum=(sum*aa)%c;
x=x>>1;
aa=(aa*aa)%c;
}
return sum;
}
int main()
{
mp.clear();
while (scanf("%lld%lld%lld",&c,&a,&b)!=EOF)
{
mp.clear();
if (a%c==0)
{
printf("no solution\n");
continue;
}
int p=false;
m=ceil(sqrt(c));
long long ans;
for (int i=0;i<=m;i++)
{
if (i==0)
{
ans=b%c; mp[ans]=i; continue;
}
ans=(ans*a)%c;
mp[ans]=i;
}
long long t=qsm(m); ans=1;
for (int i=1;i<=m;i++)
{
ans=(ans*t)%c;
if (mp[ans])
{
int t=i*m-mp[ans];
printf("%d\n",(t%c+c)%c);
p=true;
break;
}
}
if (!p)
printf("no solution\n");
}
}