BZOJ2995同余方程
2016-03-27 09:08
447 查看
2995: 同余方程
Time Limit: 10 Sec Memory Limit: 128 MB
Submit: 183 Solved: 66
Description
经典
已知数a,p,b,求满足a^x≡b(mod p)的最小自然数x。
Input
每个测试文件中最多包含100组测试数据。
每组数据中,每行包含3个正整数a,p,b。
当a=p=b=0时,表示测试数据读入完全。
Output
对于每组数据,输出一行。
如果无解,输出“No Solution”(不含引号),否则输出最小自然数解。
Sample Input
5 58 33
2 4 3
0 0 0
Sample Output
9
No Solution
【数据规模】
10%的数据,a,p,b≤10000;
对于另外30%的数据,p为质数;
100%的数据,a,p,b≤10^9。
拓展BSGS。。
附上本蒟蒻的代码:
Time Limit: 10 Sec Memory Limit: 128 MB
Submit: 183 Solved: 66
Description
经典
已知数a,p,b,求满足a^x≡b(mod p)的最小自然数x。
Input
每个测试文件中最多包含100组测试数据。
每组数据中,每行包含3个正整数a,p,b。
当a=p=b=0时,表示测试数据读入完全。
Output
对于每组数据,输出一行。
如果无解,输出“No Solution”(不含引号),否则输出最小自然数解。
Sample Input
5 58 33
2 4 3
0 0 0
Sample Output
9
No Solution
【数据规模】
10%的数据,a,p,b≤10000;
对于另外30%的数据,p为质数;
100%的数据,a,p,b≤10^9。
拓展BSGS。。
附上本蒟蒻的代码:
#include<cstdio> #include<map> #include<cmath> #include<iostream> using namespace std; long long gcd(long long x,long long y) { return y==0?x:gcd(y,x%y); } long long exgcd(long long a,long long b,long long &x,long long &y) { if (!b) { x=1,y=0; return a; } else { long long g=exgcd(b,a%b,x,y),t=x; x=y,y=t-a/b*y; return g; } } long long inv(long long a,long long p) { long long x,y,d=exgcd(a,p,x,y); return d==1?(x+p)%p:-1; } long long pow(long long x,long long a,long long p) { long long t; if (!a) return 1%p; if (a==1) return x%p; t=pow(x,a/2,p); if (a%2) return ((t*t)%p*x)%p; else return (t*t)%p; } int BSGS(long long a,long long b,long long p) { long long m=0; for (;m*m<=p;m++); b%=p; map<long long,int>hash; hash[b]=0; long long e=b,v=inv(a,p),mul=pow(a,m,p); for (int i=1;i<m;i++) { e=e*v%p; if (!hash.count(e)) hash[e]=i; else break; } e=1; for (int i=0;i<=m;i++) { if (hash.count(e)) return hash[e]+i*m; e=e*mul%p; } return -1; } void solve(long long a,long long b,long long p) { long long e=1; b%=p,a%=p; for (int i=0;i<100;i++) { if (e==b) { printf("%d\n",i); return; } e=e*a%p; } int sum=0; while (gcd(a,p)!=1) { long long d=gcd(a,p); if (b%d) { printf("No Solution\n"); return; } p/=d,sum++,b/=d; b=b*inv(a/d,p)%p; } int ans=BSGS(a,b,p); if (ans==-1) { printf("No Solution\n"); return; } printf("%d\n",ans+sum); } int main() { long long a,p,b; while (cin>>a>>p>>b) { if (!a && !p && !b) break; solve(a,b,p); } return 0; }
相关文章推荐
- 【VB.net】三层的理论认识
- Linux平台下的内存泄漏检测
- S5PV210加文件头
- jquery 使用方法
- 题目1010:A + B
- 题目1003:A+B
- 求a^b
- Python使用sqlite3操作数据库
- 题目1047:素数判定
- android项目引用library导致引用android-support-v4.jar冲突
- BZOJ_P1452 [JSOI2009]Count(二维树状数组)
- hdu 【1715】大菲波数
- 更新ubuntu15.10内核后,驱动解决
- win7系统安装
- iOS 断言 NSAssert的使用 调试程序错误
- c++设计一个计时器(能够暂停,重新开始,继续)的功能。写的不好,仅供参考!
- 求最大子数组02
- hdu5650 so easy 组合数
- oracle11g 在azure云中使用rman进行实例迁移
- 基于javascript实现九九乘法表